<?php
try {

    header("Content-Type: application/json");

    include_once dirname(__DIR__, 2) . "/config/dbcon.php";
    include_once dirname(__DIR__, 2) . "/helpers/api_helper.php";

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(405, "Method Not Allowed");
    }

    // -------- READ INPUT --------
    $input = json_decode(file_get_contents("php://input"), true);

    $id = $input['id'] ?? null;
    $status = $input['user_status'] ?? null;
    $permissions = $input['user_permissions'] ?? [];

    // -------- BASIC VALIDATION --------
    if (!$id) {
        sendResponse(400, "Id is required");
    }

    if (!$status) {
        sendResponse(400, "Status is required");
    }

    if (!in_array($status, ['accept', 'reject'])) {
        sendResponse(400, "Invalid status selected");
    }

    // -------- PERMISSION VALIDATION --------
    if ($status === 'accept' && empty($permissions)) {
        sendResponse(400, "Please select at least one user permission");
    }

    if ($status === 'reject') {
        $permissions = [];
    }

    $allowedPermissions = [
        "manage_user",
        "manage_category",
        "manage_country",
        "manage_state",
        "manage_city",
        "manage_policies"
    ];

    if (!empty($permissions)) {
        if (!is_array($permissions)) {
            sendResponse(400, "Invalid permission format");
        }

        $invalidPermissions = array_diff($permissions, $allowedPermissions);
        if (!empty($invalidPermissions)) {
            sendResponse(400, "Invalid permission selected");
        }
    }

    // -------- FETCH SUB-ADMIN --------
    $stmt = $conn->prepare(
        "SELECT name, email FROM users WHERE id = ? AND deleted_at IS NULL"
    );
    $stmt->execute([$id]);
    $subAdmin = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$subAdmin) {
        sendResponse(404, "User not found");
    }

    $subAdminName = $subAdmin['name'] ?? 'User';
    $subAdminEmail = $subAdmin['email'] ?? null;

    if (!$subAdminEmail) {
        sendResponse(400, "Sub-admin email not found");
    }

    // -------- UPDATE USER --------
    $encodedPermissions = json_encode(array_values(array_unique($permissions)));

    $stmt = $conn->prepare(
        "UPDATE users 
         SET status = ?, user_permissions = ?, updated_at = NOW() 
         WHERE id = ?"
    );
    $stmt->execute([$status, $encodedPermissions, $id]);

    // -------- PREPARE EMAIL --------
    if ($status === 'accept') {

        $permissionList = '';
        foreach ($permissions as $perm) {
            $permissionList .= "<li>" . ucwords(str_replace('_', ' ', $perm)) . "</li>";
        }

        $subject = "Your Sub-Admin Request Has Been Approved";

        $body = "
            <p>Hello <strong>{$subAdminName}</strong>,</p>

            <p>Your <strong>Sub-Admin request</strong> has been 
            <span style='color:green;'><strong>APPROVED</strong></span>.</p>

            <p>You have been granted the following permissions:</p>
            <ul>
                {$permissionList}
            </ul>

            <p>You can now log in and start managing assigned modules.</p>

            <br>
            <p>Regards,<br>
            <strong>Carrier Jobs Team</strong></p>
        ";

    } else {

        $subject = "Your Sub-Admin Request Has Been Rejected";

        $body = "
            <p>Hello <strong>{$subAdminName}</strong>,</p>

            <p>Your <strong>Sub-Admin request</strong> has been 
            <span style='color:red;'><strong>REJECTED</strong></span>.</p>

            <p>If you believe this is a mistake, please contact the administrator.</p>

            <br>
            <p>Regards,<br>
            <strong>Carrier Jobs Team</strong></p>
        ";
    }

    // -------- SEND EMAIL --------
    $senderMail = $subAdminEmail;

    include dirname(__DIR__) . "/email_send/send_email.php";

    // -------- RESPONSE --------
    sendResponse(200, "Permissions updated successfully");

} catch (PDOException $e) {
    sendResponse(500, "Server Error");
}
