<?php
if (file_exists('../../..' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../..' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

switch ($_REQUEST['FCN']) {
    default:
        break;

    case "new":
        $stmt = $GLOBALS['con']->prepare("INSERT INTO `admins` VALUES(
NULL,
'" . $_REQUEST['name'] . "',
'" . $_REQUEST['email'] . "',
'" . $_REQUEST['tel'] . "',
AES_ENCRYPT('" . $_REQUEST['password'] . "','" . $_REQUEST['email'] . "'),
'" . $_REQUEST['permissions'] . "',
'active'
)
") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        //echo $stmt->error();
        echo "success";
        $stmt->close();
        break;

    case "update":
        $perms = 'permissions' . $_REQUEST['id'];
        $stmt = $GLOBALS['con']->prepare("UPDATE `admins` SET
`name`='" . $_REQUEST['name'] . "',
`email`='" . $_REQUEST['email'] . "',
`tel`='" . $_REQUEST['tel'] . "',
`access`='" . $_REQUEST[$perms] . "',
`password`=AES_ENCRYPT('" . $_REQUEST['password'] . "','" . $_REQUEST['email'] . "')
WHERE `id`='" . $_REQUEST['id'] . "'
") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        //echo $stmt->error();
        echo "success";
        $stmt->close();
        break;

    case "remove":
        $stmt = $GLOBALS['con']->prepare("DELETE FROM `admins` WHERE `id`='" . $_REQUEST['id'] . "'") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        //echo $stmt->error();
        echo "success";
        $stmt->close();
        break;


    case "setPermissions":
        $admin_id = $_POST['admin_id'];
        $clientnumbers = $_POST['clientnumbers'] ?? []; // Get selected client numbers

        // Convert to JSON for storage
        $clientnumbersJson = json_encode($clientnumbers);

        // Check if the admin already has an entry in admin_access
        $checkQuery = "SELECT * FROM admin_access WHERE admin_id = ?";
        $stmt = $con->prepare($checkQuery);
        $stmt->bind_param('i', $admin_id);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            // Update existing entry
            $updateQuery = "UPDATE admin_access SET clientnumbers = ? WHERE admin_id = ?";
            $updateStmt = $con->prepare($updateQuery);
            $updateStmt->bind_param('si', $clientnumbersJson, $admin_id);
            $updateStmt->execute();
        } else {
            // Insert new entry
            $insertQuery = "INSERT INTO admin_access (admin_id, clientnumbers) VALUES (?, ?)";
            $insertStmt = $con->prepare($insertQuery);
            $insertStmt->bind_param('is', $admin_id, $clientnumbersJson);
            $insertStmt->execute();
        }

        echo 'success';
        break;
}

exit();