<?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">Database connection error.</div>';
    exit;
}

function requestAdminBadgeClass(string $status): string
{
    $status = strtolower(trim($status));

    if ($status === 'cancelled') {
        return 'badge-danger';
    }
    if (in_array($status, ['closed', 'complete', 'completed'], true)) {
        return 'badge-success';
    }
    if (in_array($status, ['acknowledged', 'in_progress', 'open', 'awaiting_client'], true)) {
        return 'badge-warning text-dark';
    }
    if ($status === 'new') {
        return 'badge-info';
    }

    return 'badge-light text-dark';
}

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

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))
    };
}
$statusFilter = trim((string)($_REQUEST['status'] ?? ''));
$typeFilter = trim((string)($_REQUEST['request_type'] ?? ''));
$actionFlagFilter = trim((string)($_REQUEST['action_flag'] ?? ''));
$keywordFilter = trim((string)($_REQUEST['keyword'] ?? ''));

$baseSql = "
    FROM `client_portal_requests`
    WHERE 1=1
";
$types = '';
$params = [];

if ($statusFilter !== '') {
    $baseSql .= " AND `status` = ?";
    $types .= 's';
    $params[] = $statusFilter;
}

if ($typeFilter !== '') {
    $baseSql .= " AND `request_type` = ?";
    $types .= 's';
    $params[] = $typeFilter;
}

if ($actionFlagFilter !== '') {
    $baseSql .= " AND `action_flag` = ?";
    $types .= 's';
    $params[] = $actionFlagFilter;
}

if ($keywordFilter !== '') {
    $like = '%' . $keywordFilter . '%';
    $baseSql .= " AND (`subject` LIKE ? OR `message` LIKE ? OR `requested_by` LIKE ? OR `requested_email` LIKE ?)";
    $types .= 'ssss';
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}

$sqlCounts = "SELECT
    SUM(CASE WHEN `status` NOT IN ('closed', 'complete', 'completed', 'cancelled') THEN 1 ELSE 0 END) AS open_total,
    SUM(CASE WHEN `status` = 'new' THEN 1 ELSE 0 END) AS new_total,
    SUM(CASE WHEN `status` = 'in_progress' THEN 1 ELSE 0 END) AS progress_total,
    SUM(CASE WHEN `status` = 'awaiting_client' THEN 1 ELSE 0 END) AS awaiting_total
    {$baseSql}";

$stmt = $con->prepare($sqlCounts) or die(mysqli_error($con));
if ($types !== '') {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$res = $stmt->get_result();
$counts = [
    'open_total' => 0,
    'new_total' => 0,
    'progress_total' => 0,
    'awaiting_total' => 0
];
if ($res && $row = $res->fetch_assoc()) {
    $counts = array_merge($counts, $row);
}
$stmt->close();

$sql = "SELECT
    r.`id`,
    r.`clientnumber`,
    r.`locnumber`,
    r.`request_type`,
    r.`subject`,
    r.`requested_by`,
    r.`status`,
    r.`action_flag`,
    r.`manager_name`,
    r.`created`,
    r.`updated`,
    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 1=1";

$listTypes = '';
$listParams = [];

if ($statusFilter !== '') {
    $sql .= " AND r.`status` = ?";
    $listTypes .= 's';
    $listParams[] = $statusFilter;
}

if ($typeFilter !== '') {
    $sql .= " AND r.`request_type` = ?";
    $listTypes .= 's';
    $listParams[] = $typeFilter;
}

if ($actionFlagFilter !== '') {
    $sql .= " AND r.`action_flag` = ?";
    $listTypes .= 's';
    $listParams[] = $actionFlagFilter;
}

if ($keywordFilter !== '') {
    $like = '%' . $keywordFilter . '%';
    $sql .= " AND (
        r.`subject` LIKE ?
        OR r.`message` LIKE ?
        OR r.`requested_by` LIKE ?
        OR r.`requested_email` LIKE ?
        OR c.`clientname` LIKE ?
    )";
    $listTypes .= 'sssss';
    $listParams[] = $like;
    $listParams[] = $like;
    $listParams[] = $like;
    $listParams[] = $like;
    $listParams[] = $like;
}
$sql .= "
    ORDER BY
        CASE
            WHEN r.`status` = 'new' THEN 0
            WHEN r.`status` = 'acknowledged' THEN 1
            WHEN r.`status` = 'in_progress' THEN 2
            WHEN r.`status` = 'awaiting_client' THEN 3
            ELSE 4
        END,
        GREATEST(IFNULL(r.`updated`, 0), IFNULL(r.`created`, 0)) DESC,
        r.`id` DESC";
$stmt = $con->prepare($sql) or die(mysqli_error($con));
if ($listTypes !== '') {
    $stmt->bind_param($listTypes, ...$listParams);
}
$stmt->execute();
$res = $stmt->get_result();

$rows = [];
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $rows[] = $row;
    }
}
$stmt->close();

$isAjaxOnly = isset($_SERVER['REQUEST_METHOD']) && strtoupper($_SERVER['REQUEST_METHOD']) === 'POST';
if (!$isAjaxOnly):
?>
<div class="container-fluid px-0" id="requestAdminPage">

    <div class="note note-secondary mb-3">
        <strong>Client Portal Requests:</strong> Review visit requests and fault reports submitted via the client
        portal.
        Track request progress, update status and actions, and manage communication with clients.
    </div>

    <div class="row g-3 mb-4">
        <div class="container-fluid px-0" id="requestAdminPage">
            <div class="row g-3 mb-4">
                <div class="col-12">
                    <div class="card shadow-0 border rounded-4">
                        <div class="card-body p-4">
                            <div class="row g-3 align-items-end">
                                <div class="col-12 col-md-6 col-xl-3">
                                    <label class="form-label" for="request_admin_status">Status</label>
                                    <select id="request_admin_status" name="request_admin_status" class="form-select"
                                        data-mdb-select-init data-mdb-filter="true" data-mdb-visible-options="8"
                                        data-mdb-container="#requestAdminPage">
                                        <option value="">All statuses</option>
                                        <option value="new">New</option>
                                        <option value="acknowledged">Acknowledged</option>
                                        <option value="in_progress">In Progress</option>
                                        <option value="awaiting_client">Awaiting Client</option>
                                        <option value="completed">Completed</option>
                                        <option value="closed">Closed</option>
                                        <option value="cancelled">Cancelled</option>
                                    </select>
                                </div>

                                <div class="col-12 col-md-6 col-xl-3">
                                    <label class="form-label" for="request_admin_type">Request Type</label>
                                    <select id="request_admin_type" class="form-select">
                                        <option value="">All types</option>
                                        <option value="visit_request">Visit Request</option>
                                        <option value="fault_report">Fault Report</option>
                                    </select>
                                </div>

                                <div class="col-12 col-md-6 col-xl-3">
                                    <label class="form-label" for="request_admin_action_flag">Action</label>
                                    <select id="request_admin_action_flag" name="request_admin_action_flag"
                                        class="form-select" data-mdb-select-init data-mdb-filter="true"
                                        data-mdb-visible-options="8" data-mdb-container="#requestAdminPage">
                                        <option value="">All actions</option>
                                        <option value="none">none</option>
                                        <option value="call_client">call_client</option>
                                        <option value="schedule_visit">schedule_visit</option>
                                        <option value="review_fault">review_fault</option>
                                        <option value="awaiting_parts">awaiting_parts</option>
                                        <option value="awaiting_access">awaiting_access</option>
                                        <option value="engineer_assigned">engineer_assigned</option>
                                        <option value="no_action_required">no_action_required</option>
                                        <option value="client_cancelled">client_cancelled</option>
                                    </select>
                                </div>

                                <div class="col-12 col-md-6 col-xl-3">
                                    <label class="form-label" for="request_admin_keyword">Keyword</label>
                                    <input type="text" id="request_admin_keyword" class="form-control"
                                        placeholder="Subject, message, requester...">
                                </div>

                                <div class="col-12">
                                    <div class="d-flex flex-wrap gap-2">
                                        <button type="button" class="btn btn-info" onclick="requestAdminApplyFilters()"
                                            data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                            title="Apply filters">
                                            <i class="fad fa-filter me-2"></i>Apply Filters
                                        </button>

                                        <button type="button" class="btn btn-outline-secondary"
                                            onclick="requestAdminClearFilters()" data-mdb-tooltip-init
                                            data-mdb-placement="top" data-mdb-trigger="hover" title="Clear filters">
                                            <i class="fad fa-undo me-2"></i>Clear
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-6 col-xl-3">
                    <div class="card shadow-1 border rounded-4 h-100 bg-light">
                        <div class="card-body p-3">
                            <div class="small text-muted text-uppercase mb-1">Open</div>
                            <div class="fs-4 fw-bold"><?= (int)$counts['open_total'] ?></div>
                        </div>
                    </div>
                </div>
                <div class="col-6 col-xl-3">
                    <div class="card shadow-1 border rounded-4 h-100 bg-light">
                        <div class="card-body p-3">
                            <div class="small text-muted text-uppercase mb-1">New</div>
                            <div class="fs-4 fw-bold"><?= (int)$counts['new_total'] ?></div>
                        </div>
                    </div>
                </div>
                <div class="col-6 col-xl-3">
                    <div class="card shadow-1 border rounded-4 h-100 bg-light">
                        <div class="card-body p-3">
                            <div class="small text-muted text-uppercase mb-1">In Progress</div>
                            <div class="fs-4 fw-bold"><?= (int)$counts['progress_total'] ?></div>
                        </div>
                    </div>
                </div>
                <div class="col-6 col-xl-3">
                    <div class="card shadow-1 border rounded-4 h-100 bg-light">
                        <div class="card-body p-3">
                            <div class="small text-muted text-uppercase mb-1">Awaiting Client</div>
                            <div class="fs-4 fw-bold"><?= (int)$counts['awaiting_total'] ?></div>
                        </div>
                    </div>
                </div>

                <div class="col-12" id="requestAdminListContainer">
                    <?php endif; ?>

                    <div class="card shadow-0 border rounded-4">
                        <div class="card-body p-4">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h4 class="mb-0">Portal Requests</h4>
                                <span class="badge badge-light text-dark"><?= count($rows) ?>
                                    result<?= count($rows) === 1 ? '' : 's' ?></span>
                            </div>

                            <?php if (!empty($rows)): ?>
                            <div class="table-responsive">
                                <table class="table table-sm align-middle mb-0">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>ID</th>
                                            <th>Client</th>
                                            <th>Site</th>
                                            <th>Type</th>
                                            <th>Subject</th>
                                            <th>Requested By</th>
                                            <th>Status</th>
                                            <th>Action</th>
                                            <th>Manager</th>
                                            <th>Created</th>
                                            <th>Updated</th>
                                            <th class="text-end" style="width:120px;">View</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($rows as $row): ?>
                                        <tr>
                                            <td>#<?= (int)$row['id'] ?></td>
                                            <td>
                                                <div class="fw-bold">
                                                    <?= htmlspecialchars((string)$row['client_name'], ENT_QUOTES, 'UTF-8') ?>
                                                </div>

                                            </td>
                                            <td><?= (int)$row['locnumber'] > 0 ? (int)$row['locnumber'] : 'All' ?></td>
                                            <td><?= htmlspecialchars(requestAdminTypeLabel((string)$row['request_type']), ENT_QUOTES, 'UTF-8') ?>
                                            </td>
                                            <td><?= htmlspecialchars((string)$row['subject'], ENT_QUOTES, 'UTF-8') ?>
                                            </td>
                                            <td><?= htmlspecialchars((string)$row['requested_by'], ENT_QUOTES, 'UTF-8') ?>
                                            </td>
                                            <td>
                                                <span
                                                    class="badge <?= requestAdminBadgeClass((string)$row['status']) ?>">
                                                    <?= htmlspecialchars(requestAdminStatusLabel((string)$row['status']), ENT_QUOTES, 'UTF-8') ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?= htmlspecialchars(requestAdminActionLabel((string)($row['action_flag'] ?: 'none')), ENT_QUOTES, 'UTF-8') ?>
                                            </td>
                                            <td><?= htmlspecialchars((string)$row['manager_name'], ENT_QUOTES, 'UTF-8') ?>
                                            </td>
                                            <td><?= !empty($row['created']) ? date('d-m-Y H:i', (int)$row['created']) : '-' ?>
                                            </td>
                                            <td><?= !empty($row['updated']) ? date('d-m-Y H:i', (int)$row['updated']) : '-' ?>
                                            </td>
                                            <td class="text-end">
                                                <button type="button" class="btn btn-info btn-sm"
                                                    onclick="requestAdminOpenDetail(<?= (int)$row['id'] ?>)"
                                                    data-mdb-tooltip-init data-mdb-placement="top"
                                                    data-mdb-trigger="hover" title="View request">
                                                    <i class="fad fa-eye me-1"></i>View
                                                </button>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php else: ?>
                            <div class="alert alert-light border mb-0">No requests were found for the selected filters.
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <?php if (!$isAjaxOnly): ?>
                </div>
            </div>
        </div>

        <script>
        document.getElementById('navBox').innerHTML =
            ' <li class="breadcrumb-item">Client Portal <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li>' +
            '<li class="breadcrumb-item active">Requests</li>';

        (function() {
            const pageElement = document.getElementById('requestAdminPage');
            if (!pageElement) {
                return;
            }

            const selectElements = pageElement.querySelectorAll('[data-mdb-select-init]');
            selectElements.forEach((selectEl) => {
                new mdb.Select(selectEl, {
                    container: '#requestAdminPage'
                });
            });
        })();
        </script>
        <?php endif; ?>