<?php
require_once __DIR__ . '/../../functions/security.php';
require_once __DIR__ . '/../../functions/logging.php';
$tenant = enrep_tenant_segment();
if (file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
enrep_require_admin();

$action = enrep_request_enum('FCN', ['new', 'update', 'profileUpdate', 'remove', 'setPermissions'], '');
enrep_log_request_completion('admins', 'FCN', [
    'new' => ['action' => 'created', 'message' => 'Created admin user', 'entity_type' => 'admins'],
    'update' => ['action' => 'updated', 'message' => 'Updated admin user', 'entity_type' => 'admins'],
    'profileUpdate' => ['action' => 'profile_updated', 'message' => 'Updated own admin profile', 'entity_type' => 'admins'],
    'remove' => ['action' => 'deleted', 'message' => 'Deleted admin user', 'entity_type' => 'admins'],
    'setPermissions' => ['action' => 'permissions_updated', 'message' => 'Updated admin client permissions', 'entity_type' => 'admin_access'],
]);

switch ($action) {
    default:
        break;

    case "new":
        $name = enrep_request_string('name', '', 255);
        $email = enrep_request_string('email', '', 255);
        $tel = enrep_request_string('tel', '', 80);
        $password = enrep_request_string('password', '', 255);
        $access = enrep_request_int('permissions', 0);

        $stmt = $GLOBALS['con']->prepare(
            "INSERT INTO `admins` (`name`, `email`, `tel`, `password`, `access`, `status`) VALUES (?, ?, ?, AES_ENCRYPT(?, ?), ?, 'active')"
        ) or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('sssssi', $name, $email, $tel, $password, $email, $access);
        $stmt->execute();
        echo "success";
        $stmt->close();
        break;

    case "update":
        $id = enrep_request_int('id', 0);
        $perms = 'permissions' . $id;
        $name = enrep_request_string('name', '', 255);
        $email = enrep_request_string('email', '', 255);
        $tel = enrep_request_string('tel', '', 80);
        $password = enrep_request_string('password', '', 255);
        $access = enrep_request_int($perms, 0);

        $stmt = $GLOBALS['con']->prepare(
            "UPDATE `admins` SET `name`=?, `email`=?, `tel`=?, `access`=?, `password`=AES_ENCRYPT(?, ?) WHERE `id`=?"
        ) or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('sssissi', $name, $email, $tel, $access, $password, $email, $id);
        $stmt->execute();
        echo "success";
        $stmt->close();
        break;

    case "profileUpdate":
        $id = (int)($_SESSION['admin_id'] ?? ($_SESSION['userid'] ?? 0));
        if ($id <= 0) {
            echo "error";
            break;
        }

        $name = enrep_request_string('name', '', 255);
        $email = enrep_request_string('email', '', 255);
        $tel = enrep_request_string('tel', '', 80);
        $password = enrep_request_string('password', '', 255);

        $stmt = $GLOBALS['con']->prepare(
            "UPDATE `admins` SET `name`=?, `email`=?, `tel`=?, `password`=AES_ENCRYPT(?, ?) WHERE `id`=?"
        ) or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('sssssi', $name, $email, $tel, $password, $email, $id);
        $stmt->execute();
        $_SESSION['user'] = $name;
        echo "success";
        $stmt->close();
        break;

    case "remove":
        $id = enrep_request_int('id', 0);
        $stmt = $GLOBALS['con']->prepare("DELETE FROM `admins` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $id);
        $stmt->execute();
        echo "success";
        $stmt->close();
        break;


    case "setPermissions":
        $admin_id = enrep_request_int('admin_id', 0);
        $clientnumbers = enrep_request_int_array('clientnumbers');

        $clientnumbersJson = json_encode($clientnumbers);

        $checkQuery = "SELECT * FROM admin_access WHERE admin_id = ?";
        $stmt = $GLOBALS['con']->prepare($checkQuery);
        $stmt->bind_param('i', $admin_id);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            $updateQuery = "UPDATE admin_access SET clientnumbers = ? WHERE admin_id = ?";
            $updateStmt = $GLOBALS['con']->prepare($updateQuery);
            $updateStmt->bind_param('si', $clientnumbersJson, $admin_id);
            $updateStmt->execute();
            $updateStmt->close();
        } else {
            $insertQuery = "INSERT INTO admin_access (admin_id, clientnumbers) VALUES (?, ?)";
            $insertStmt = $GLOBALS['con']->prepare($insertQuery);
            $insertStmt->bind_param('is', $admin_id, $clientnumbersJson);
            $insertStmt->execute();
            $insertStmt->close();
        }
        $stmt->close();

        echo 'success';
        break;
}

exit();
