<?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');
}

if (!isset($con) || !$con instanceof mysqli || $con->connect_error) {
    echo '<div class="alert alert-danger mb-0">Database connection error.</div>';
    exit;
}

$payload = [];
if (!empty($_REQUEST['data'])) {
    $decoded = json_decode(urldecode((string)$_REQUEST['data']), true);
    if (is_array($decoded)) {
        $payload = $decoded;
    }
}

$requestId = isset($payload['id']) ? (int)$payload['id'] : 0;
if ($requestId <= 0) {
    echo '<div class="alert alert-warning mb-0">Invalid request.</div>';
    exit;
}

$stmt = $con->prepare("
    SELECT
        r.`id`,
        r.`clientnumber`,
        r.`locnumber`,
        r.`request_type`,
        r.`subject`,
        r.`message`,
        r.`requested_by`,
        r.`requested_email`,
        r.`requested_phone`,
        r.`status`,
        r.`action_flag`,
        r.`manager_name`,
        r.`manager_email`,
        r.`created`,
        r.`updated`,
        r.`admin_notes`,
        r.`closed_by`,
        r.`closed_at`,
        COALESCE(NULLIF(TRIM(c.`clientname`), ''), CONCAT('Client #', r.`clientnumber`)) AS `client_name`
    FROM `client_portal_requests` r
    LEFT JOIN `clientdetails` c
        ON c.`clientnumber` = r.`clientnumber`
    WHERE r.`id` = ?
    LIMIT 1
") or die(mysqli_error($con));
$stmt->bind_param('i', $requestId);
$stmt->execute();
$res = $stmt->get_result();
$request = $res ? $res->fetch_assoc() : null;
$stmt->close();

if (!$request) {
    echo '<div class="alert alert-warning mb-0">Request not found.</div>';
    exit;
}

function requestAdminTypeLabelDetail(string $type): string
{
    return match ($type) {
        'visit_request' => 'Visit Request',
        'fault_report' => 'Fault Report',
        default => ucwords(str_replace('_', ' ', $type))
    };
}

function requestAdminDateTime(int $value): string
{
    return $value > 0 ? date('d-m-Y H:i', $value) : '-';
}

function requestAdminStatusLabel(string $status): string
{
    return match ($status) {
        'new' => 'New',
        'acknowledged' => 'Acknowledged',
        'in_progress' => 'In Progress',
        'awaiting_client' => 'Awaiting Client',
        'completed' => 'Completed',
        'closed' => 'Closed',
        'cancelled' => 'Cancelled',
        default => ucwords(str_replace('_', ' ', $status))
    };
}

function requestAdminActionLabel(string $action): string
{
    return match ($action) {
        'none' => 'None',
        'call_client' => 'Call Client',
        'schedule_visit' => 'Schedule Visit',
        'review_fault' => 'Review Fault',
        'awaiting_parts' => 'Awaiting Parts',
        'awaiting_access' => 'Awaiting Access',
        'engineer_assigned' => 'Engineer Assigned',
        'no_action_required' => 'No Action Required',
        'client_cancelled' => 'Client Cancelled',
        default => ucwords(str_replace('_', ' ', $action))
    };
}

$statusOptions = ['new', 'acknowledged', 'in_progress', 'awaiting_client', 'completed', 'closed', 'cancelled'];
$actionOptions = ['none', 'call_client', 'schedule_visit', 'review_fault', 'awaiting_parts', 'awaiting_access', 'engineer_assigned', 'no_action_required', 'client_cancelled'];
?>

<div id="requestAdminDetailStart">
    <div class="row g-3 mb-3">
        <div class="col-12 col-lg-8">
            <h4 class="mb-1">
                <?= htmlspecialchars(requestAdminTypeLabelDetail((string)$request['request_type']), ENT_QUOTES, 'UTF-8') ?>
            </h4>
            <div class="text-muted">
                Request ID: <strong>#<?= (int)$request['id'] ?></strong>
            </div>
        </div>
        <div class="col-12 col-lg-4 text-lg-end">
            <span
                class="badge badge-light text-dark"><?= htmlspecialchars((string)$request['status'], ENT_QUOTES, 'UTF-8') ?></span>
        </div>
    </div>

    <div class="row g-3">
        <div class="col-12 col-lg-6">
            <div class="border rounded-4 p-3 h-100">
                <div class="small text-muted text-uppercase mb-1">Client</div>
                <div class="fw-bold"><?= htmlspecialchars((string)$request['client_name'], ENT_QUOTES, 'UTF-8') ?></div>


                <div class="small text-muted text-uppercase mt-3 mb-1">Site Scope</div>
                <div class="fw-bold"><?= (int)$request['locnumber'] > 0 ? (int)$request['locnumber'] : 'All' ?></div>

                <div class="small text-muted text-uppercase mt-3 mb-1">Subject</div>
                <div class="fw-bold"><?= htmlspecialchars((string)$request['subject'], ENT_QUOTES, 'UTF-8') ?></div>
            </div>
        </div>

        <div class="col-12 col-lg-6">
            <div class="border rounded-4 p-3 h-100">
                <div class="small text-muted text-uppercase mb-1">Requested By</div>
                <div class="fw-bold"><?= htmlspecialchars((string)$request['requested_by'], ENT_QUOTES, 'UTF-8') ?>
                </div>
                <div class="small mt-2">
                    <?= htmlspecialchars((string)$request['requested_email'], ENT_QUOTES, 'UTF-8') ?></div>
                <div class="small"><?= htmlspecialchars((string)$request['requested_phone'], ENT_QUOTES, 'UTF-8') ?>
                </div>

                <div class="small text-muted text-uppercase mt-3 mb-1">Manager</div>
                <div class="fw-bold"><?= htmlspecialchars((string)$request['manager_name'], ENT_QUOTES, 'UTF-8') ?>
                </div>
                <div class="small"><?= htmlspecialchars((string)$request['manager_email'], ENT_QUOTES, 'UTF-8') ?></div>
            </div>
        </div>

        <div class="col-12">
            <div class="border rounded-4 p-3">
                <div class="small text-muted text-uppercase mb-2">Request Details</div>
                <div><?= nl2br(htmlspecialchars((string)$request['message'], ENT_QUOTES, 'UTF-8')) ?></div>
            </div>
        </div>

        <div class="col-12 col-lg-6">
            <label class="form-label" for="request_admin_status_update">Status</label>
            <select id="request_admin_status_update" name="request_admin_status_update" class="form-select"
                data-mdb-select-init data-mdb-filter="true" data-mdb-visible-options="8"
                data-mdb-container="#requestAdminDetailBox">
                <?php foreach ($statusOptions as $status): ?>
                <option value="<?= htmlspecialchars($status, ENT_QUOTES, 'UTF-8') ?>"
                    <?= $status === (string)$request['status'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars(requestAdminStatusLabel($status), ENT_QUOTES, 'UTF-8') ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-12 col-lg-6">
            <label class="form-label" for="request_admin_action_flag_update">Action</label>
            <select id="request_admin_action_flag_update" name="request_admin_action_flag_update" class="form-select"
                data-mdb-select-init data-mdb-filter="true" data-mdb-visible-options="8"
                data-mdb-container="#requestAdminDetailBox">
                <?php foreach ($actionOptions as $flag): ?>
                <option value="<?= htmlspecialchars($flag, ENT_QUOTES, 'UTF-8') ?>"
                    <?= $flag === ((string)$request['action_flag'] ?: 'none') ? 'selected' : '' ?>>
                    <?= htmlspecialchars(requestAdminActionLabel($flag), ENT_QUOTES, 'UTF-8') ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-12">
            <label class="form-label" for="request_admin_notes_update">Admin Notes</label>
            <textarea id="request_admin_notes_update" class="form-control" rows="6"
                placeholder="Enter internal handling notes"><?= htmlspecialchars((string)$request['admin_notes'], ENT_QUOTES, 'UTF-8') ?></textarea>
        </div>

        <div class="col-12 col-lg-4">
            <div class="border rounded-4 p-3 h-100">
                <div class="small text-muted text-uppercase mb-1">Created</div>
                <div class="fw-bold"><?= requestAdminDateTime((int)$request['created']) ?></div>
            </div>
        </div>

        <div class="col-12 col-lg-4">
            <div class="border rounded-4 p-3 h-100">
                <div class="small text-muted text-uppercase mb-1">Updated</div>
                <div class="fw-bold"><?= requestAdminDateTime((int)$request['updated']) ?></div>
            </div>
        </div>

        <div class="col-12 col-lg-4">
            <div class="border rounded-4 p-3 h-100">
                <div class="small text-muted text-uppercase mb-1">Closed</div>
                <div class="fw-bold"><?= requestAdminDateTime((int)$request['closed_at']) ?></div>
                <div class="small mt-2"><?= htmlspecialchars((string)$request['closed_by'], ENT_QUOTES, 'UTF-8') ?>
                </div>
            </div>
        </div>

        <div class="col-12">
            <div class="border rounded-4 p-3 bg-light mb-3">
                <div class="small text-muted text-uppercase mb-2">Quick Actions</div>
                <div class="d-flex flex-wrap gap-2">
                    <button type="button" class="btn btn-outline-info btn-sm"
                        onclick="requestAdminQuickUpdate(<?= (int)$request['id'] ?>, 'acknowledged', 'call_client')"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                        title="Mark as acknowledged">
                        <i class="fad fa-check-circle me-1"></i>Acknowledge
                    </button>

                    <button type="button" class="btn btn-outline-warning btn-sm"
                        onclick="requestAdminQuickUpdate(<?= (int)$request['id'] ?>, 'in_progress', 'engineer_assigned')"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                        title="Mark as in progress">
                        <i class="fad fa-spinner-third me-1"></i>In Progress
                    </button>

                    <button type="button" class="btn btn-outline-secondary btn-sm"
                        onclick="requestAdminQuickUpdate(<?= (int)$request['id'] ?>, 'awaiting_client', 'awaiting_access')"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                        title="Mark as awaiting client">
                        <i class="fad fa-user-clock me-1"></i>Awaiting Client
                    </button>

                    <button type="button" class="btn btn-outline-success btn-sm"
                        onclick="requestAdminQuickUpdate(<?= (int)$request['id'] ?>, 'completed', 'no_action_required')"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                        title="Mark as completed">
                        <i class="fad fa-check-double me-1"></i>Complete
                    </button>

                    <button type="button" class="btn btn-outline-danger btn-sm"
                        onclick="requestAdminQuickUpdate(<?= (int)$request['id'] ?>, 'closed', 'no_action_required')"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Mark as closed">
                        <i class="fad fa-times-circle me-1"></i>Close
                    </button>

                    <button type="button" class="btn btn-outline-warning btn-sm"
                        onclick="requestAdminCancel(<?= (int)$request['id'] ?>)">
                        <i class="fad fa-ban me-1"></i>Cancel
                    </button>

                    <button type="button" class="btn btn-outline-danger btn-sm"
                        onclick="requestAdminDelete(<?= (int)$request['id'] ?>)">
                        <i class="fad fa-trash me-1"></i>Delete
                    </button>
                </div>
            </div>

            <div class="d-flex flex-wrap justify-content-center gap-2">
                <button type="button" class="btn btn-info" onclick="requestAdminSaveUpdate(<?= (int)$request['id'] ?>)"
                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save changes">
                    <i class="fad fa-save me-2"></i>Save Update
                </button>

                <button type="button" class="btn btn-outline-secondary" onclick="killModal('requestAdminDetailBox')"
                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Close">
                    <i class="fad fa-times me-2"></i>Close
                </button>
            </div>
        </div>
    </div>
</div>

<script>
(function() {
    const modalElement = document.getElementById('requestAdminDetailStart');
    if (!modalElement) {
        return;
    }

    const selectElements = modalElement.querySelectorAll('[data-mdb-select-init]');
    selectElements.forEach((selectEl) => {
        new mdb.Select(selectEl);
    });
})();

function requestAdminQuickUpdate(requestId, status, actionFlag) {
    const statusField = document.getElementById('request_admin_status_update');
    const actionField = document.getElementById('request_admin_action_flag_update');

    if (!statusField || !actionField) {
        showResponse('danger', 'Update fields could not be found');
        return;
    }

    statusField.value = status;
    actionField.value = actionFlag;

    requestAdminSaveUpdate(requestId);
}

function requestAdminSaveUpdate(requestId) {
    const status = document.getElementById('request_admin_status_update').value;
    const actionFlag = document.getElementById('request_admin_action_flag_update').value;
    const adminNotes = document.getElementById('request_admin_notes_update').value.trim();

    const params = new URLSearchParams();
    params.append('mode', 'updateRequest');
    params.append('tenant', TENANT_URL);
    params.append('request_id', requestId);
    params.append('status', status);
    params.append('action_flag', actionFlag);
    params.append('admin_notes', adminNotes);

    fetch(ROOT_URL + '/includes/requests/requests_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: params.toString()
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                killModal('requestAdminDetailBox');
                showResponse('success', data.message);
                requestAdminApplyFilters();
                return;
            }

            showResponse(data.status || 'danger', data.message || 'There was an error saving the request');
        })
        .catch(() => {
            showResponse('danger', 'There was an error saving the request');
        });
}

function requestAdminCancel(id) {
    if (!confirm('Cancel this request?')) return;

    const params = new URLSearchParams();
    params.append('mode', 'cancelRequest');
    params.append('tenant', TENANT_URL);
    params.append('request_id', id);

    fetch(ROOT_URL + '/includes/requests/requests_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: params.toString()
        })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'success') {
                killModal('requestAdminDetailBox');
                showResponse('success', data.message);
                requestAdminApplyFilters();
                return;
            }
            showResponse(data.status || 'danger', data.message);
        });
}

function requestAdminDelete(id) {
    if (!confirm('DELETE this request permanently? This cannot be undone.')) return;

    const params = new URLSearchParams();
    params.append('mode', 'deleteRequest');
    params.append('tenant', TENANT_URL);
    params.append('request_id', id);

    fetch(ROOT_URL + '/includes/requests/requests_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: params.toString()
        })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'success') {
                killModal('requestAdminDetailBox');
                showResponse('success', data.message);
                requestAdminApplyFilters();
                return;
            }
            showResponse(data.status || 'danger', data.message);
        });
}
</script>