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

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

if (!isset($con) || !$con instanceof mysqli || $con->connect_error) {
    echo json_encode([
        'status' => 'danger',
        'message' => 'Database connection error'
    ]);
    exit;
}

function requestAdminJson(string $status, string $message): void
{
    echo json_encode([
        'status' => $status,
        'message' => $message
    ]);
    exit;
}

$mode = trim((string)($_REQUEST['mode'] ?? ''));

switch ($mode) {
    case 'updateRequest':
        $requestId = isset($_POST['request_id']) ? (int)$_POST['request_id'] : 0;
        $status = trim((string)($_POST['status'] ?? ''));
        $actionFlag = trim((string)($_POST['action_flag'] ?? 'none'));
        $adminNotes = trim((string)($_POST['admin_notes'] ?? ''));

        if ($requestId <= 0) {
            requestAdminJson('danger', 'Invalid request');
        }

        $allowedStatuses = ['new', 'acknowledged', 'in_progress', 'awaiting_client', 'completed', 'closed', 'cancelled'];
        $allowedActionFlags = ['none', 'call_client', 'schedule_visit', 'review_fault', 'awaiting_parts', 'awaiting_access', 'engineer_assigned', 'no_action_required', 'client_cancelled', 'admin_cancelled'];

        if (!in_array($status, $allowedStatuses, true)) {
            requestAdminJson('danger', 'Invalid status');
        }

        if (!in_array($actionFlag, $allowedActionFlags, true)) {
            requestAdminJson('danger', 'Invalid action flag');
        }

        $stmt = $con->prepare("SELECT `id` FROM `client_portal_requests` WHERE `id` = ? LIMIT 1") or die(mysqli_error($con));
        $stmt->bind_param('i', $requestId);
        $stmt->execute();
        $res = $stmt->get_result();
        $exists = $res && $res->num_rows > 0;
        $stmt->close();

        if (!$exists) {
            requestAdminJson('danger', 'Request not found');
        }

        $updated = time();
        $closedBy = '';
        $closedAt = 0;

        if (in_array($status, ['completed', 'closed', 'cancelled'], true)) {
            $closedAt = $updated;
            if (!empty($_SESSION['admin_id'])) {
                $closedBy = 'admin:' . (int)$_SESSION['admin_id'];
            } else {
                $closedBy = 'admin';
            }
        }

        $stmt = $con->prepare("
            UPDATE `client_portal_requests`
            SET
                `status` = ?,
                `action_flag` = ?,
                `admin_notes` = ?,
                `updated` = ?,
                `closed_by` = ?,
                `closed_at` = ?
            WHERE `id` = ?
            LIMIT 1
        ") or die(mysqli_error($con));
        $stmt->bind_param(
            'sssissi',
            $status,
            $actionFlag,
            $adminNotes,
            $updated,
            $closedBy,
            $closedAt,
            $requestId
        );
        $ok = $stmt->execute();
        $stmt->close();

        if (!$ok) {
            requestAdminJson('danger', 'There was an error updating the request');
        }

        requestAdminJson('success', 'Request updated successfully');
        break;

    case 'cancelRequest':
        $requestId = (int)($_POST['request_id'] ?? 0);

        if ($requestId <= 0) {
            requestAdminJson('danger', 'Invalid request');
        }

        $updated = time();
        $closedBy = !empty($_SESSION['admin_id']) ? 'admin:' . (int)$_SESSION['admin_id'] : 'admin';

        $stmt = $con->prepare("
                UPDATE `client_portal_requests`
                SET
                    `status` = 'cancelled',
                    `action_flag` = 'admin_cancelled',
                    `updated` = ?,
                    `closed_by` = ?,
                    `closed_at` = ?
                WHERE `id` = ?
                LIMIT 1
            ");
        $stmt->bind_param('isii', $updated, $closedBy, $updated, $requestId);
        $ok = $stmt->execute();
        $stmt->close();

        if (!$ok) {
            requestAdminJson('danger', 'Cancellation failed');
        }

        requestAdminJson('success', 'Request cancelled');
        break;


    case 'deleteRequest':
        $requestId = (int)($_POST['request_id'] ?? 0);

        if ($requestId <= 0) {
            requestAdminJson('danger', 'Invalid request');
        }

        $stmt = $con->prepare("DELETE FROM `client_portal_requests` WHERE `id` = ? LIMIT 1");
        $stmt->bind_param('i', $requestId);
        $ok = $stmt->execute();
        $stmt->close();

        if (!$ok) {
            requestAdminJson('danger', 'Delete failed');
        }

        requestAdminJson('success', 'Request removed');
        break;

    default:
        requestAdminJson('danger', 'Invalid request');
        break;
}