<?php

include("../../config.php");
error_log(json_encode($_POST));
session_start();
$_POST["user_id"] = (int)$_POST["user_id"];
if ($_POST["user_id"] < 1) {
    echo json_encode(["ok" => false, "error_code" => 99]);
    exit();
}

if (!isset($_SESSION["id"])) {
    echo json_encode(["ok" => false, "error_code" => 100]);
    exit();
}

if (!isset($_POST["user_id"]) || !isset($_POST["status"]) || !isset($_POST["login_try"])) {
    echo json_encode(["ok" => false, "error_code" => 101]);
    exit();
}

if (is_null($_POST["user_id"]) || is_null($_POST["status"]) || is_null($_POST["login_try"])) {
    echo json_encode(["ok" => false, "error_code" => 102]);
    exit();
}


include("../../config.php");
$admins_function = new \Functions\Admins();
$users_function = new \Functions\Bot_Users();
$persian_date = new \Classes\PersianDate();
$admin_info = $admins_function->get_by_id($_SESSION["id"])[0];
$root = "api/update_user.php";
if (in_array($root, json_decode($admin_info->permissions))) {

    $user_info = $users_function->get_by_id($_POST["user_id"])[0];

    if ($user_info->use_bot !== $_POST["status"] ||
        $user_info->login_try !== $_POST["login_try"]) {

        $users_function->update(
            $user_info->id,
            [
                "limit_login" => $persian_date->jdate("Y-m-d H:i"),
                "login_try" => $_POST["login_try"],
                "use_bot" => $_POST["status"]
            ]
        );

        echo json_encode(["ok" => true, "status" => $users_function->show_status($_POST["status"])]);
        exit();
    } else {
        echo json_encode(["ok" => false, "error_code" => 103]);
        exit();
    }
} else {
    echo json_encode(["ok" => false, "error_code" => 104]);
    exit();
}