<?php
require_once 'auth.php';
ensureAdminAuth();
// admin/requests.php
require_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

// Get all requests with details - handles manual entries
$requests = $db->query("
    SELECT 
        sr.*,
        CASE 
            WHEN sr.brand_id IS NULL THEN sr.manual_brand 
            ELSE b.name 
        END as brand_name,
        CASE 
            WHEN sr.appliance_type_id IS NULL THEN sr.manual_appliance_type 
            ELSE a.name 
        END as appliance_name,
        COALESCE(sz.city, l.location_name, c.city_name) AS city_name,
        COALESCE(sz.region, c.region, c.city_name) AS service_region_name,
        u.name as urgency_name,
        j.status_name,
        j.color_code as status_color,
        l.location_name
    FROM service_requests sr
    LEFT JOIN brands b ON sr.brand_id = b.id
    LEFT JOIN appliance_types a ON sr.appliance_type_id = a.id
    LEFT JOIN cities c ON sr.city_id = c.id
              LEFT JOIN service_areas sz ON sz.zip_code = sr.zip_code AND sz.is_active = 1
    LEFT JOIN urgency_levels u ON sr.urgency_level_id = u.id
    LEFT JOIN job_statuses j ON sr.job_status_id = j.id
    LEFT JOIN locations l ON sr.location_id = l.id
    ORDER BY sr.requested_at ASC
")->fetchAll(PDO::FETCH_ASSOC);

$statuses = $db->query("SELECT * FROM job_statuses ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);
$brands = $db->query("SELECT * FROM brands ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$appliance_types = $db->query("SELECT * FROM appliance_types ORDER BY sort_order")->fetchAll(PDO::FETCH_ASSOC);
$cities = $db->query("SELECT MIN(id) AS id, city AS city_name, state, region FROM service_areas WHERE is_active = 1 GROUP BY city, state, region ORDER BY region, city")->fetchAll(PDO::FETCH_ASSOC);
$urgency_levels = $db->query("SELECT * FROM urgency_levels")->fetchAll(PDO::FETCH_ASSOC);

$total = count($requests);
$pending = count(array_filter($requests, function($r) {
    return (int)$r['job_status_id'] === 1 || $r['status_name'] === 'Pending' || $r['status_name'] === 'New Request';
}));
$in_progress = count(array_filter($requests, function($r) {
    return (int)$r['job_status_id'] === 3 || $r['status_name'] === 'In Progress';
}));
$completed = count(array_filter($requests, function($r) {
    return (int)$r['job_status_id'] === 4 || $r['status_name'] === 'Completed' || $r['status_name'] === 'Repair Completed';
}));

$manual_brands = count(array_filter($requests, function($r) {
    return is_null($r['brand_id']);
}));
$manual_appliances = count(array_filter($requests, function($r) {
    return is_null($r['appliance_type_id']);
}));
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <title>Manage Requests - Admin</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">

    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css">

    <!-- Select2 -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet">

    <!-- Toastr -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">

    <style>
        :root {
            --admin-bg-1: #080240;
            --admin-bg-2: #093349;
            --admin-card-1: #17295e;
            --admin-card-2: #102448;
            --admin-border: rgba(96, 165, 250, 0.24);
            --admin-border-strong: rgba(56, 189, 248, 0.42);
            --admin-cyan: #17bdd4;
            --admin-blue: #1d9bf0;
            --admin-text: #f8fafc;
            --admin-muted: #aebbd4;
            --admin-soft: #d7e7ff;
            --admin-green: #22c55e;
            --admin-yellow: #facc15;
            --admin-red: #f43f5e;
            --admin-input: rgba(8, 20, 48, 0.72);
        }

        * {
            box-sizing: border-box;
        }

        body {
            background: linear-gradient(135deg, var(--admin-bg-1) 0%, var(--admin-bg-2) 100%) fixed !important;
            color: var(--admin-text) !important;
            font-family: 'Montserrat', sans-serif !important;
            min-height: 100vh;
            overflow-x: hidden;
        }

        a {
            color: #9ee7ff;
        }

        a:hover {
            color: #ffffff;
        }

        .sidebar {
            min-height: 100vh;
            background: rgba(8, 2, 64, 0.96);
            backdrop-filter: blur(14px);
            color: white;
            position: fixed;
            width: 250px;
            transition: all 0.3s;
            overflow-y: auto;
            z-index: 1000;
            border-right: 1px solid rgba(96, 165, 250, 0.18);
        }

        .sidebar-header {
            padding: 24px 18px;
            text-align: center;
            border-bottom: 1px solid rgba(96, 165, 250, 0.18);
        }

        .sidebar-header i {
            color: var(--admin-cyan);
        }

        .sidebar-header h4 {
            font-size: 1.1rem;
            margin-top: 10px;
            font-weight: 900;
            color: #ffffff;
        }

        .sidebar-header p {
            font-size: 0.8rem;
            color: var(--admin-muted);
        }

        .sidebar-menu {
            padding: 20px 0;
        }

        .sidebar-menu a {
            color: #b9dcff !important;
            padding: 13px 20px;
            display: block;
            text-decoration: none;
            transition: all 0.25s;
            border-left: 4px solid transparent;
            font-weight: 700;
            font-size: 14px;
        }

        .sidebar-menu a:hover,
        .sidebar-menu a.active {
            background: rgba(56, 189, 248, 0.12);
            color: #ffffff !important;
            border-left-color: var(--admin-cyan);
        }

        .sidebar-menu i {
            margin-right: 10px;
            width: 20px;
        }

        .main-content {
            margin-left: 250px;
            padding: 24px;
            min-height: 100vh;
            background: transparent !important;
        }

        .content-header {
            background: linear-gradient(135deg, var(--admin-card-1), var(--admin-card-2)) !important;
            padding: 20px;
            border-radius: 18px;
            border: 1px solid rgba(56, 189, 248, 0.28);
            box-shadow: 0 10px 24px rgba(0, 0, 0, 0.24);
            margin-bottom: 20px;
            color: #ffffff;
        }

        .content-header h2 {
            color: #ffffff;
            font-weight: 900;
        }

        .content-header p,
        .text-muted {
            color: var(--admin-muted) !important;
        }

        .card {
            background: linear-gradient(135deg, var(--admin-card-1), var(--admin-card-2)) !important;
            border: 1px solid rgba(56, 189, 248, 0.24) !important;
            border-radius: 16px !important;
            box-shadow:
                0 10px 24px rgba(0, 0, 0, 0.24),
                inset 0 0 0 1px rgba(255, 255, 255, 0.025) !important;
            color: #ffffff !important;
            overflow: hidden;
        }

        .card:hover {
            border-color: rgba(56, 189, 248, 0.38) !important;
        }

        .card-header {
            background: linear-gradient(135deg, rgba(29, 155, 240, 0.16), rgba(23, 189, 212, 0.08)) !important;
            border-bottom: 1px solid rgba(56, 189, 248, 0.22) !important;
            padding: 15px 20px;
            font-weight: 900;
            border-radius: 16px 16px 0 0 !important;
            color: #ffffff !important;
        }

        .card-header i {
            color: #dff7ff !important;
        }

        .card-body {
            padding: 20px;
            color: #ffffff !important;
        }

        .stat-card {
            transition: all 0.25s ease;
        }

        .stat-card:hover {
            transform: translateY(-3px);
        }

        .stat-card .card-body {
            min-height: 98px;
        }

        h3, h6, strong, label {
            color: #ffffff;
        }

        .stat-icon-box {
            background: rgba(56, 189, 248, 0.14) !important;
            border: 1px solid rgba(56, 189, 248, 0.22);
            border-radius: 12px;
            width: 46px;
            height: 46px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .text-primary,
        .text-info {
            color: #dff7ff !important;
        }

        .text-warning {
            color: #fde68a !important;
        }

        .text-success {
            color: #bbf7d0 !important;
        }

        .text-danger {
            color: #fecaca !important;
        }

        .manual-entry {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 4px 8px;
            background: rgba(250, 204, 21, 0.16);
            color: #fde68a;
            border-radius: 999px;
            font-size: 10px;
            font-weight: 900;
            margin-left: 5px;
            border: 1px solid rgba(250, 204, 21, 0.34);
            vertical-align: middle;
        }

        .manual-entry i {
            font-size: 9px;
        }

        .status-dropdown {
            min-width: 138px;
            padding: 6px 30px 6px 10px;
            border-radius: 999px;
            border: 1px solid rgba(255, 255, 255, 0.22);
            font-size: 11px;
            font-weight: 900;
            color: white;
            cursor: pointer;
            transition: all 0.3s;
            background-color: transparent;
            appearance: none;
            background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><polyline points='6 9 12 15 18 9'/></svg>");
            background-repeat: no-repeat;
            background-position: right 9px center;
            background-size: 12px;
        }

        .status-dropdown:hover {
            transform: translateY(-1px);
            box-shadow: 0 8px 18px rgba(0,0,0,0.20);
            border-color: rgba(255, 255, 255, 0.42);
        }

        .status-dropdown:focus {
            outline: none;
            border-color: rgba(56, 189, 248, 0.72);
            box-shadow: 0 0 0 0.16rem rgba(56, 189, 248, 0.18);
        }

        .status-dropdown option {
            background: #102448;
            color: #ffffff;
            padding: 8px;
        }

        .action-btn {
            width: 36px;
            height: 34px;
            padding: 0 !important;
            border-radius: 10px !important;
            font-size: 13px;
            margin: 0 2px;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: 1px solid rgba(56, 189, 248, 0.34) !important;
            color: #dff7ff !important;
            background: rgba(56, 189, 248, 0.10) !important;
        }

        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 18px rgba(0,0,0,0.22);
            background: rgba(56, 189, 248, 0.24) !important;
            color: #ffffff !important;
        }

        .btn-primary,
        .btn-info {
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
            border: none !important;
            color: #ffffff !important;
            font-weight: 800 !important;
            border-radius: 10px !important;
        }

        .btn-outline-primary {
            border-color: rgba(56, 189, 248, 0.42) !important;
            color: #dff7ff !important;
            background: rgba(56, 189, 248, 0.10) !important;
            font-weight: 800 !important;
            border-radius: 10px !important;
        }

        .btn-outline-primary:hover {
            background: rgba(56, 189, 248, 0.24) !important;
            color: #ffffff !important;
        }

        .btn-secondary {
            background: rgba(148, 163, 184, 0.22) !important;
            border: 1px solid rgba(148, 163, 184, 0.30) !important;
            color: #ffffff !important;
            font-weight: 800 !important;
            border-radius: 10px !important;
        }

        .badge.bg-primary {
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
            color: #ffffff !important;
            border-radius: 999px;
            font-weight: 900;
        }

        .badge.bg-light,
        .badge.bg-secondary {
            background: rgba(8, 20, 48, 0.58) !important;
            color: #dff7ff !important;
            border: 1px solid rgba(56, 189, 248, 0.28);
            border-radius: 999px;
            font-weight: 900;
        }

        .badge.bg-warning {
            background: rgba(250, 204, 21, 0.16) !important;
            color: #fde68a !important;
            border: 1px solid rgba(250, 204, 21, 0.34);
            border-radius: 999px;
        }

        .alert-info {
            background: linear-gradient(135deg, rgba(29, 155, 240, 0.16), rgba(23, 189, 212, 0.08)) !important;
            border: 1px solid rgba(56, 189, 248, 0.28) !important;
            color: #dff7ff !important;
            border-radius: 14px !important;
        }

        .alert-info strong {
            color: #ffffff;
        }

        .alert .btn-close {
            filter: brightness(0) invert(1);
            opacity: 0.9;
        }

        .modal-content {
            background: linear-gradient(135deg, var(--admin-card-1), var(--admin-card-2)) !important;
            border: 1px solid rgba(96, 165, 250, 0.30) !important;
            color: #ffffff !important;
            border-radius: 16px !important;
            overflow: hidden;
            box-shadow: 0 25px 70px rgba(0,0,0,0.45) !important;
        }

        .modal-header {
            background: linear-gradient(135deg, rgba(29, 155, 240, 0.16), rgba(23, 189, 212, 0.08)) !important;
            color: white;
            border-bottom: 1px solid rgba(56, 189, 248, 0.22) !important;
            border-radius: 16px 16px 0 0;
            padding: 15px 20px;
        }

        .modal-header .btn-close {
            filter: brightness(0) invert(1);
            opacity: 1;
        }

        .modal-title {
            font-weight: 900;
            color: #ffffff;
        }

        .modal-body {
            padding: 20px;
            color: #ffffff;
        }

        .modal-footer {
            background: rgba(8, 20, 48, 0.52);
            border-top: 1px solid rgba(96, 165, 250, 0.22);
            padding: 15px 20px;
        }

        #viewModalBody,
        #editModalBody,
        #historyModalBody {
            color: #ffffff;
        }

        #viewModalBody .card,
        #editModalBody .card,
        #historyModalBody .card {
            background: rgba(8, 20, 48, 0.38) !important;
        }

        #viewModalBody table,
        #editModalBody table,
        #historyModalBody table {
            color: #ffffff !important;
        }

        .form-control,
        .form-select,
        textarea,
        input {
            background-color: var(--admin-input) !important;
            border: 1px solid rgba(96, 165, 250, 0.34) !important;
            color: #ffffff !important;
            border-radius: 10px !important;
        }

        .form-control::placeholder,
        input::placeholder,
        textarea::placeholder {
            color: #aebbd4 !important;
            opacity: 1;
        }

        .form-control:focus,
        .form-select:focus {
            border-color: rgba(56, 189, 248, 0.62) !important;
            box-shadow: 0 0 0 0.18rem rgba(56, 189, 248, 0.18) !important;
        }

        .form-select option {
            background: #102448;
            color: #ffffff;
        }

        .info-label {
            font-size: 12px;
            color: var(--admin-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 5px;
            font-weight: 900;
        }

        .info-value {
            font-size: 15px;
            font-weight: 700;
            color: #ffffff;
            padding: 10px 12px;
            background: rgba(8, 20, 48, 0.45);
            border: 1px solid rgba(96, 165, 250, 0.22);
            border-radius: 10px;
        }

        .info-value i {
            color: #dff7ff;
            margin-right: 8px;
        }

        .history-item {
            padding: 12px;
            border-left: 3px solid var(--admin-cyan);
            background: rgba(8, 20, 48, 0.45);
            border-radius: 0 10px 10px 0;
            margin-bottom: 10px;
            border-top: 1px solid rgba(96, 165, 250, 0.16);
            border-right: 1px solid rgba(96, 165, 250, 0.16);
            border-bottom: 1px solid rgba(96, 165, 250, 0.16);
        }

        .history-status {
            font-weight: 900;
            color: #ffffff;
        }

        .history-date {
            font-size: 11px;
            color: var(--admin-muted);
        }

        .history-note {
            font-size: 13px;
            margin-top: 5px;
            color: var(--admin-soft);
        }

        .table-responsive {
            border-radius: 12px;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
            background: transparent !important;
        }

        .table {
            min-width: 1000px;
            color: var(--admin-text) !important;
            margin-bottom: 0 !important;
        }

        .table th {
            font-weight: 900;
            color: #ffffff !important;
            white-space: nowrap;
            background: rgba(8, 20, 48, 0.58) !important;
            border-color: rgba(96, 165, 250, 0.22) !important;
            font-size: 13px;
        }

        .table td {
            vertical-align: middle;
            white-space: nowrap;
            color: var(--admin-soft) !important;
            border-color: rgba(96, 165, 250, 0.20) !important;
            background: rgba(8, 20, 48, 0.18) !important;
        }

        .table tbody tr {
            transition: all 0.2s ease;
        }

        .table tbody tr:hover td {
            background: rgba(56, 189, 248, 0.10) !important;
            color: #ffffff !important;
        }

        .table strong {
            color: #ffffff !important;
        }

        .table .fa-city,
        .table .fa-user {
            color: #dff7ff !important;
        }

        .dataTables_wrapper {
            color: var(--admin-soft) !important;
        }

        .dataTables_wrapper .dataTables_length label,
        .dataTables_wrapper .dataTables_filter label,
        .dataTables_wrapper .dataTables_info {
            color: var(--admin-soft) !important;
            font-weight: 700;
        }

        .dataTables_wrapper .dataTables_filter input,
        .dataTables_wrapper .dataTables_length select {
            background: rgba(8, 20, 48, 0.72) !important;
            border: 1px solid rgba(96, 165, 250, 0.34) !important;
            color: #ffffff !important;
            border-radius: 10px !important;
        }

                /* Fix DataTables "Show entries" dropdown */
        .dataTables_wrapper .dataTables_length select {
            background-color: #17bdd4 !important;
            color: #ffffff !important;
            border: 1px solid rgba(56, 189, 248, 0.55) !important;
            border-radius: 10px !important;
            font-weight: 800 !important;
        }

        /* Dropdown options */
        .dataTables_wrapper .dataTables_length select option {
            background-color: #17bdd4 !important;
            color: #ffffff !important;
            font-weight: 800 !important;
        }

        /* Hover/focus effect */
        .dataTables_wrapper .dataTables_length select:focus {
            background-color: #1d9bf0 !important;
            color: #ffffff !important;
            border-color: #9ee7ff !important;
            box-shadow: 0 0 0 0.18rem rgba(56, 189, 248, 0.22) !important;
        }
        .dataTables_wrapper .page-link {
            background: rgba(8, 20, 48, 0.54) !important;
            border-color: rgba(96, 165, 250, 0.24) !important;
            color: #dff7ff !important;
            font-weight: 800;
        }

        .dataTables_wrapper .page-item.active .page-link {
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
            border-color: transparent !important;
            color: #ffffff !important;
        }

        .dataTables_wrapper .page-item.disabled .page-link {
            background: rgba(8, 20, 48, 0.25) !important;
            color: #64748b !important;
        }

        table.dataTable thead .sorting:before,
        table.dataTable thead .sorting:after,
        table.dataTable thead .sorting_asc:before,
        table.dataTable thead .sorting_asc:after,
        table.dataTable thead .sorting_desc:before,
        table.dataTable thead .sorting_desc:after {
            color: rgba(215, 231, 255, 0.55) !important;
        }

        .table-responsive::-webkit-scrollbar {
            height: 6px;
        }

        .table-responsive::-webkit-scrollbar-track {
            background: rgba(8, 20, 48, 0.40);
            border-radius: 10px;
        }

        .table-responsive::-webkit-scrollbar-thumb {
            background: rgba(96, 165, 250, 0.40);
            border-radius: 10px;
        }

        .table-responsive::-webkit-scrollbar-thumb:hover {
            background: rgba(56, 189, 248, 0.70);
        }

        .spinner-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(8, 2, 64, 0.70);
            backdrop-filter: blur(6px);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid rgba(255,255,255,0.12);
            border-top: 5px solid var(--admin-cyan);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        .spinner-border {
            color: var(--admin-cyan) !important;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .updating {
            opacity: 0.5;
            pointer-events: none;
            position: relative;
        }

        .updating::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 20px;
            height: 20px;
            margin: -10px 0 0 -10px;
            border: 2px solid rgba(255,255,255,0.18);
            border-top: 2px solid var(--admin-cyan);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        .select2-container--bootstrap-5 .select2-selection {
            background-color: var(--admin-input) !important;
            border: 1px solid rgba(96, 165, 250, 0.34) !important;
            color: #ffffff !important;
            border-radius: 10px !important;
        }

        .select2-container--bootstrap-5 .select2-selection--single {
            height: 45px;
            padding: 8px 12px;
        }

        .select2-container--bootstrap-5 .select2-selection__rendered {
            color: #ffffff !important;
        }

        .select2-dropdown {
            background: #102448 !important;
            border: 1px solid rgba(96, 165, 250, 0.34) !important;
            color: #ffffff !important;
        }

        .select2-results__option {
            color: #ffffff !important;
        }

        .select2-results__option--highlighted {
            background: rgba(56, 189, 248, 0.24) !important;
        }

        .toast-success {
            background-color: #16a34a !important;
        }

        .toast-error {
            background-color: #dc2626 !important;
        }

        .toast-warning {
            background-color: #f59e0b !important;
        }

        .toast-info {
            background-color: #1d9bf0 !important;
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: relative;
                min-height: auto;
            }

            .main-content {
                margin-left: 0;
                padding: 14px;
            }

            .content-header {
                padding: 15px;
                display: block !important;
            }

            .content-header > div:last-child {
                margin-top: 12px;
            }

            .content-header h2 {
                font-size: 1.3rem;
            }

            .card-body {
                padding: 15px;
            }

            .table-responsive {
                margin: 0 -15px;
                width: calc(100% + 30px);
                padding: 0 15px;
            }

            .table {
                min-width: 850px;
            }

            .status-dropdown {
                min-width: 118px;
                font-size: 10px;
                padding: 5px 25px 5px 8px;
            }

            .action-btn {
                width: 34px;
                height: 32px;
            }
        }
    </style>

    <link rel="stylesheet" href="../assets/theme.css">
    <link rel="stylesheet" href="../assets/portal-dark.css">
    <link rel="stylesheet" href="../assets/ushs-global-theme.css">
    <link rel="stylesheet" href="../assets/admin-sidebar.css">
</head>

<body>
    <div class="spinner-overlay" id="spinnerOverlay">
        <div class="spinner"></div>
    </div>

    <?php require_once __DIR__ . '/admin_sidebar.php'; render_admin_sidebar(); ?>

    <div class="main-content">
        <div class="content-header d-flex justify-content-between align-items-center">
            <div>
                <h2 class="mb-1">
                    <i class="fas fa-clipboard-list me-2" style="color: var(--admin-cyan);"></i>
                    Service Requests
                </h2>
                <p class="text-muted mb-0">Manage and track all service requests</p>
            </div>

            <div>
                <span class="badge bg-primary p-2">
                    <i class="fas fa-calendar me-1"></i> 
                    <?php echo date('F d, Y'); ?>
                </span>

                <button class="btn btn-sm btn-outline-primary ms-2" onclick="location.reload()">
                    <i class="fas fa-sync-alt"></i>
                </button>
            </div>
        </div>

        <div class="row mb-4">
            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-muted mb-1">Total</h6>
                                <h3 class="mb-0"><?php echo $total; ?></h3>
                            </div>
                            <div class="stat-icon-box">
                                <i class="fas fa-clipboard-list text-primary"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-muted mb-1">Pending</h6>
                                <h3 class="mb-0"><?php echo $pending; ?></h3>
                            </div>
                            <div class="stat-icon-box">
                                <i class="fas fa-clock text-warning"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-muted mb-1">In Progress</h6>
                                <h3 class="mb-0"><?php echo $in_progress; ?></h3>
                            </div>
                            <div class="stat-icon-box">
                                <i class="fas fa-spinner text-info"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-3 col-6 mb-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="text-muted mb-1">Completed</h6>
                                <h3 class="mb-0"><?php echo $completed; ?></h3>
                            </div>
                            <div class="stat-icon-box">
                                <i class="fas fa-check-circle text-success"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php if($manual_brands > 0 || $manual_appliances > 0): ?>
        <div class="alert alert-info alert-dismissible fade show mb-4" role="alert">
            <i class="fas fa-info-circle me-2"></i>
            <strong>Manual Entries Detected:</strong>

            <?php if($manual_brands > 0): ?>
                <span class="badge bg-warning text-dark ms-2">
                    <?php echo $manual_brands; ?> manual brand(s)
                </span>
            <?php endif; ?>

            <?php if($manual_appliances > 0): ?>
                <span class="badge bg-warning text-dark ms-2">
                    <?php echo $manual_appliances; ?> manual appliance(s)
                </span>
            <?php endif; ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php endif; ?>
        
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span>
                    <i class="fas fa-list me-2" style="color: var(--admin-cyan);"></i>
                    All Service Requests
                </span>

                <span class="badge bg-light text-dark">
                    <?php echo count($requests); ?> records found
                </span>
            </div>

            <div class="card-body">
                <div class="table-responsive">
                    <table id="requestsTable" class="table table-hover" style="width:100%">
                        <thead>
                            <tr>
                                <th>Request #</th>
                                <th>Date</th>
                                <th>Customer</th>
                                <th>Appliance</th>
                                <th>Brand</th>
                                <th>City</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php foreach($requests as $req): ?>
                            <tr id="request-row-<?php echo $req['id']; ?>">
                                <td>
                                    <strong><?php echo htmlspecialchars($req['request_number']); ?></strong>
                                </td>

                                <td>
                                    <span class="badge bg-light text-dark">
                                        <i class="far fa-calendar-alt me-1"></i>
                                        <?php echo date('M d, Y', strtotime($req['requested_at'])); ?>
                                    </span>
                                </td>

                                <td>
                                    <i class="fas fa-user me-1 text-muted"></i>
                                    <?php echo htmlspecialchars($req['full_name']); ?>
                                </td>

                                <td>
                                    <?php echo htmlspecialchars($req['appliance_name']); ?>

                                    <?php if(is_null($req['appliance_type_id'])): ?>
                                        <span class="manual-entry" title="Manually entered">
                                            <i class="fas fa-pencil-alt"></i> 
                                        </span>
                                    <?php endif; ?>
                                </td>

                                <td>
                                    <?php echo htmlspecialchars($req['brand_name']); ?>

                                    <?php if(is_null($req['brand_id'])): ?>
                                        <span class="manual-entry" title="Manually entered">
                                            <i class="fas fa-pencil-alt"></i> 
                                        </span>
                                    <?php endif; ?>
                                </td>

                                <td>
                                    <i class="fas fa-city me-1 text-muted"></i>
                                    <?php echo htmlspecialchars($req['city_name']); ?>
                                </td>

                                <td>
                                    <select class="status-dropdown" 
                                            onchange="updateStatus(<?php echo $req['id']; ?>, this.value, this)"
                                            style="background-color: <?php echo htmlspecialchars($req['status_color']); ?>; color: white;">
                                        <?php foreach($statuses as $status): ?>
                                        <option value="<?php echo $status['id']; ?>" 
                                                data-color="<?php echo htmlspecialchars($status['color_code']); ?>"
                                                style="background-color: <?php echo htmlspecialchars($status['color_code']); ?>; color: white;"
                                                <?php echo $status['id'] == $req['job_status_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($status['status_name']); ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>

                                <td>
                                    <button class="btn btn-sm btn-info action-btn" onclick="viewRequest(<?php echo $req['id']; ?>)" title="View Details">
                                        <i class="fas fa-eye"></i>
                                    </button>

                                    <button class="btn btn-sm btn-primary action-btn" onclick="editRequest(<?php echo $req['id']; ?>)" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </button>

                                    <button class="btn btn-sm btn-secondary action-btn" onclick="viewHistory(<?php echo $req['id']; ?>)" title="View History">
                                        <i class="fas fa-history"></i>
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="viewRequestModal" tabindex="-1" aria-labelledby="viewRequestModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewRequestModalLabel">
                        <i class="fas fa-eye me-2"></i>Request Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <div class="modal-body" id="viewModalBody">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">Loading request details...</p>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>

                    <button type="button" class="btn btn-primary" onclick="editFromView()">
                        <i class="fas fa-edit me-2"></i>Edit Request
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="editRequestModal" tabindex="-1" aria-labelledby="editRequestModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editRequestModalLabel">
                        <i class="fas fa-edit me-2"></i>Edit Request
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <form id="editRequestForm">
                    <div class="modal-body" id="editModalBody">
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2">Loading edit form...</p>
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>

                        <button type="submit" class="btn btn-primary" id="saveEditBtn">
                            <i class="fas fa-save me-2"></i>Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="historyModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-history me-2"></i>Status History
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <div class="modal-body" id="historyModalBody">
                    <!-- Content will be loaded via AJAX -->
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    
    <script>
        toastr.options = {
            closeButton: true,
            progressBar: true,
            positionClass: "toast-top-right",
            timeOut: 3000
        };
        
        let currentRequestId = null;
        let viewModal;
        let editModal;
        let historyModal;
        
        $(document).ready(function() {
            $('#requestsTable').DataTable({
                order: [[1, 'asc']],
                pageLength: 25,
                language: {
                    search: "<i class='fas fa-search'></i> _INPUT_",
                    searchPlaceholder: "Search requests...",
                    lengthMenu: "Show _MENU_ entries",
                    info: "Showing _START_ to _END_ of _TOTAL_ entries",
                    infoEmpty: "Showing 0 to 0 of 0 entries",
                    infoFiltered: "(filtered from _MAX_ total entries)"
                },
                initComplete: function() {
                    $('div.dataTables_filter input').addClass('form-control form-control-sm');
                    $('div.dataTables_filter input').attr('placeholder', 'Search...');
                    $('div.dataTables_length select').addClass('form-select form-select-sm');
                }
            });
            
            viewModal = new bootstrap.Modal(document.getElementById('viewRequestModal'));
            editModal = new bootstrap.Modal(document.getElementById('editRequestModal'));
            historyModal = new bootstrap.Modal(document.getElementById('historyModal'));
            
            $('#editRequestForm').on('submit', function(e) {
                e.preventDefault();
                updateRequest();
            });
        });
        
        function showSpinner() {
            document.getElementById('spinnerOverlay').style.display = 'flex';
        }
        
        function hideSpinner() {
            document.getElementById('spinnerOverlay').style.display = 'none';
        }
        
        function updateStatus(requestId, statusId, selectElement) {
            $(selectElement).addClass('updating');
            
            let selectedOption = $(selectElement).find('option:selected');
            let newColor = selectedOption.data('color');
            
            $.ajax({
                url: 'ajax/quick_update_status.php',
                method: 'POST',
                data: {
                    id: requestId,
                    status_id: statusId
                },
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        $(selectElement).css('background-color', newColor);
                        toastr.success('Status updated successfully');
                        refreshStats();
                    } else {
                        toastr.error(response.message || 'Error updating status');
                        loadCurrentStatus(requestId, selectElement);
                    }
                },
                error: function() {
                    toastr.error('Error updating status');
                    loadCurrentStatus(requestId, selectElement);
                },
                complete: function() {
                    $(selectElement).removeClass('updating');
                }
            });
        }
        
        function loadCurrentStatus(requestId, selectElement) {
            $.ajax({
                url: 'ajax/get_current_status.php',
                method: 'GET',
                data: { id: requestId },
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        $(selectElement).val(response.status_id);
                        $(selectElement).css('background-color', response.color);
                    }
                }
            });
        }
        
        function refreshStats() {
            $.ajax({
                url: 'ajax/get_stats.php',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    // Optional stats refresh endpoint.
                }
            });
        }
        
        function viewRequest(id) {
            currentRequestId = id;
            showSpinner();
            
            $.ajax({
                url: 'ajax/get_request_details.php',
                method: 'GET',
                data: { id: id },
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        $('#viewModalBody').html(response.html);
                        viewModal.show();
                    } else {
                        toastr.error(response.message || 'Error loading request details');
                    }
                },
                error: function() {
                    toastr.error('Error loading request details');
                },
                complete: function() {
                    hideSpinner();
                }
            });
        }
        
        function editRequest(id) {
            currentRequestId = id;
            showSpinner();
            
            $.ajax({
                url: 'ajax/get_edit_form.php',
                method: 'GET',
                data: { id: id },
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        $('#editModalBody').html(response.html);
                        editModal.show();
                        
                        $('.status-selector').select2({
                            theme: 'bootstrap-5',
                            dropdownParent: $('#editRequestModal')
                        });
                        
                        handleManualFields();
                    } else {
                        toastr.error(response.message || 'Error loading edit form');
                    }
                },
                error: function() {
                    toastr.error('Error loading edit form');
                },
                complete: function() {
                    hideSpinner();
                }
            });
        }
        
        function handleManualFields() {
            if ($('#brand_id').val() === '' && $('#manual_brand').val()) {
                $('#brand_id').prop('disabled', true);
                $('#manual_brand_field').show();
            }
            
            if ($('#appliance_type_id').val() === '' && $('#manual_appliance_type').val()) {
                $('#appliance_type_id').prop('disabled', true);
                $('#manual_appliance_field').show();
            }
            
            $('#brand_id').on('change', function() {
                if ($(this).val() === '') {
                    $('#manual_brand_field').show();
                    $('#manual_brand').prop('required', true);
                } else {
                    $('#manual_brand_field').hide();
                    $('#manual_brand').prop('required', false);
                }
            });
            
            $('#appliance_type_id').on('change', function() {
                if ($(this).val() === '') {
                    $('#manual_appliance_field').show();
                    $('#manual_appliance_type').prop('required', true);
                } else {
                    $('#manual_appliance_field').hide();
                    $('#manual_appliance_type').prop('required', false);
                }
            });
        }
        
        function updateRequest() {
            $('#brand_id, #appliance_type_id').prop('disabled', false);
            
            let formData = $('#editRequestForm').serialize();
            formData += '&id=' + currentRequestId;
            
            showSpinner();
            
            $.ajax({
                url: 'ajax/update_request.php',
                method: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        toastr.success(response.message);
                        editModal.hide();
                        
                        if(response.new_status) {
                            let selectElement = $(`#request-row-${currentRequestId} .status-dropdown`);
                            selectElement.val(response.new_status.id);
                            selectElement.css('background-color', response.new_status.color);
                        }
                        
                        setTimeout(function() {
                            location.reload();
                        }, 1500);
                    } else {
                        toastr.error(response.message);
                    }
                },
                error: function() {
                    toastr.error('Error updating request');
                },
                complete: function() {
                    hideSpinner();
                }
            });
        }
        
        function viewHistory(id) {
            showSpinner();
            
            $.ajax({
                url: 'ajax/get_status_history.php',
                method: 'GET',
                data: { id: id },
                dataType: 'json',
                success: function(response) {
                    if(response.success) {
                        $('#historyModalBody').html(response.html);
                        historyModal.show();
                    } else {
                        toastr.error(response.message || 'Error loading history');
                    }
                },
                error: function() {
                    toastr.error('Error loading history');
                },
                complete: function() {
                    hideSpinner();
                }
            });
        }
        
        function editFromView() {
            viewModal.hide();

            setTimeout(function() {
                editRequest(currentRequestId);
            }, 500);
        }
        
        function deleteRequest(id) {
            if(confirm('Are you sure you want to delete this request? This action cannot be undone.')) {
                showSpinner();
                
                $.ajax({
                    url: 'ajax/delete_request.php',
                    method: 'POST',
                    data: { id: id },
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            toastr.success(response.message);
                            $(`#request-row-${id}`).fadeOut('slow', function() {
                                $(this).remove();
                                location.reload();
                            });
                        } else {
                            toastr.error(response.message);
                        }
                    },
                    error: function() {
                        toastr.error('Error deleting request');
                    },
                    complete: function() {
                        hideSpinner();
                    }
                });
            }
        }
    </script>
</body>
</html>