<?php

session_start();

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


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

if (is_null($_POST["username"]) || is_null($_POST["password"]) || is_null($_POST["apps"])) {
    echo json_encode(["ok" => false, "error_code" => 102]);
    exit();
}

if ($_POST["userid"]  == "0") {
    echo json_encode(["ok" => false, "error_code" => 100]);
    exit();
}

include("../../config.php");
$admins_function = new \Functions\Admins();
$account_function = new \Functions\Bot_Accounts();
$admin_info = $admins_function->get_by_id($_SESSION["id"])[0];
$persian_date = new \Classes\PersianDate();

$root = "api/add_account.php";
if (in_array($root, json_decode($admin_info->permissions))) {

    if($_POST["apps"] == "" || $_POST["apps"] == null){
        $_POST["apps"] = [];
    }
    $account_id = $account_function->add(
        [
            $_POST["username"],
            md5($_POST["password"]),
            json_encode($_POST["apps"])
        ]
    );
    $output = '
    <tr id="account_' . $account_id . '">
        <td class="text-center">
            ' . $account_id . '
        </td>
        <td class="text-center"  id="username_' . $account_id . '">' . $_POST["username"] . '</td>
        <td class="text-center no-print">
            <i class="fas fa-user-edit text-primary font-20" data-toggle="tooltip"
               data-placement="top" title="ویرایش اکانت" data-original-title=""
               id="edit_admin"
               data-id="' . $account_id . '"></i>
               
            <i class="mdi mdi-textbox-password font-20" data-toggle="tooltip"
               data-placement="top" title="تغییر رمز عبور" data-original-title=""
               id="edit_admin_password"
               data-id="' . $account_id . '"></i>
        </td>
    </tr>
    ';
    echo json_encode(["ok" => true,'output'=>$output]);
    exit();
} else {
    echo json_encode(["ok" => false, "error_code" => 103]);
    exit();
}