<?php
// customer/my_requests.php
session_start();
require_once '../config/database.php';

// Check if logged in
if(!isset($_SESSION['customer_id'])) {
    header('Location: ../login.php');
    exit;
}

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

// Get customer info
$customer_query = "SELECT first_name, last_name FROM customers WHERE id = :id";
$customer_stmt = $db->prepare($customer_query);
$customer_stmt->execute([':id' => $_SESSION['customer_id']]);
$customer = $customer_stmt->fetch(PDO::FETCH_ASSOC);

// Get filter parameters
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';

// Build query based on filters
$query = "SELECT 
            sr.*, 
            b.name as brand_name,
            a.name as appliance_name,
            c.city_name,
            u.name as urgency_name,
            u.time_frame as urgency_time,
            j.status_name,
            j.color_code as status_color
          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 urgency_levels u ON sr.urgency_level_id = u.id
          LEFT JOIN job_statuses j ON sr.job_status_id = j.id
          WHERE sr.customer_id = :customer_id";

if($status_filter != 'all') {
    $query .= " AND sr.job_status_id = :status_id";
}

if(!empty($search_query)) {
    $query .= " AND (sr.request_number LIKE :search 
                OR a.name LIKE :search 
                OR b.name LIKE :search
                OR sr.issue_description LIKE :search)";
}

$query .= " ORDER BY sr.requested_at DESC";

$stmt = $db->prepare($query);
$params = [':customer_id' => $_SESSION['customer_id']];

if($status_filter != 'all') {
    $params[':status_id'] = $status_filter;
}

if(!empty($search_query)) {
    $params[':search'] = '%' . $search_query . '%';
}

$stmt->execute($params);
$requests = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get statuses for filter dropdown
$statuses = $db->query("SELECT id, status_name FROM job_statuses ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);

// Get statistics
$stats_query = "SELECT 
                    COUNT(*) as total,
                    SUM(CASE WHEN job_status_id = 1 THEN 1 ELSE 0 END) as pending,
                    SUM(CASE WHEN job_status_id = 2 THEN 1 ELSE 0 END) as assigned,
                    SUM(CASE WHEN job_status_id = 3 THEN 1 ELSE 0 END) as in_progress,
                    SUM(CASE WHEN job_status_id = 4 THEN 1 ELSE 0 END) as completed,
                    SUM(CASE WHEN job_status_id = 5 THEN 1 ELSE 0 END) as cancelled
                FROM service_requests 
                WHERE customer_id = :customer_id";
$stats_stmt = $db->prepare($stats_query);
$stats_stmt->execute([':customer_id' => $_SESSION['customer_id']]);
$stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);

$pageTitle  = 'My Requests';
$activePage = 'requests';

// Notification count for shared customer header
$notif_count_stmt2 = $db->prepare("
    SELECT COUNT(*) AS count
    FROM notifications
    WHERE customer_id = :id
      AND is_read = 0
");
$notif_count_stmt2->execute([':id' => $_SESSION['customer_id']]);

$notifCount = (int)($notif_count_stmt2->fetch(PDO::FETCH_ASSOC)['count'] ?? 0);
$notification_count = $notifCount;

// Recent notifications for shared customer header dropdown
$recent_notifs_stmt2 = $db->prepare("
    SELECT *
    FROM notifications
    WHERE customer_id = :id
    ORDER BY created_at DESC
    LIMIT 5
");
$recent_notifs_stmt2->execute([':id' => $_SESSION['customer_id']]);

$recent_notifications = $recent_notifs_stmt2->fetchAll(PDO::FETCH_ASSOC);

include __DIR__ . '/includes/header.php';
?>
<style>
        body {
            background: linear-gradient(135deg, #080240 0%, #093349 100%) !important;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            margin-bottom: 80px;
            min-height: 100vh;
            color: #ffffff;
        }

        .app-header {
            background: rgba(15, 31, 74, 0.92) !important;
            color: #ffffff;
            padding: 12px 16px;
            position: sticky;
            top: 0;
            z-index: 1000;
            border-bottom: 1px solid rgba(96, 165, 250, 0.16);
            box-shadow: 0 2px 8px rgba(0,0,0,0.16);
        }
        
        .header-content {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        
        .back-btn {
            background: none;
            border: none;
            font-size: 22px;
            color: #ffffff;
            padding: 0;
            cursor: pointer;
            line-height: 1;
        }
        
        .header-title {
            font-weight: 700;
            font-size: 18px;
            color: #ffffff;
            margin: 0;
            letter-spacing: 0.2px;
        }
        
        .stats-container {
            padding: 18px 14px 10px;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #17295e 0%, #102448 100%);
            border: 1px solid rgba(96, 165, 250, 0.22);
            border-radius: 12px;
            padding: 12px;
            box-shadow: 0 10px 24px rgba(0, 0, 0, 0.22);
            text-align: center;
        }
        
        .stat-value {
            font-size: 21px;
            font-weight: 800;
            color: #f8fafc !important;
            line-height: 1.2;
        }
        
        .stat-label {
            font-size: 11px;
            color: #aebbd4;
            margin-top: 4px;
        }
        
        .filter-section {
            padding: 0 14px 18px;
        }
        
        .search-box {
            position: relative;
            margin-bottom: 12px;
        }
        
        .search-box i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #d7e7ff;
            font-size: 14px;
        }
        
        .search-box input {
            width: 100%;
            padding: 12px 15px 12px 45px;
            border: 1px solid rgba(96, 165, 250, 0.32);
            border-radius: 10px;
            font-size: 14px;
            background: rgba(8, 20, 48, 0.75);
            color: #ffffff;
            outline: none;
        }

        .search-box input::placeholder {
            color: #aebbd4;
        }
        
        .search-box input:focus {
            border-color: rgba(56, 189, 248, 0.55);
            box-shadow: 0 0 0 0.18rem rgba(56, 189, 248, 0.18);
        }
        
        .filter-buttons {
            display: flex;
            gap: 8px;
            overflow-x: auto;
            padding-bottom: 5px;
            -webkit-overflow-scrolling: touch;
        }
        
        .filter-buttons::-webkit-scrollbar {
            height: 3px;
        }
        
        .filter-buttons::-webkit-scrollbar-thumb {
            background: rgba(56, 189, 248, 0.45);
            border-radius: 3px;
        }
        
        .filter-btn {
            padding: 8px 16px;
            border: 1px solid rgba(56, 189, 248, 0.32);
            border-radius: 9px;
            background: linear-gradient(135deg, #17295e 0%, #102448 100%);
            color: #d7e7ff;
            font-size: 13px;
            font-weight: 700;
            white-space: nowrap;
            transition: all 0.3s ease;
        }
        
        .filter-btn:hover,
        .filter-btn.active {
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%);
            border-color: rgba(56, 189, 248, 0.55);
            color: #ffffff;
            box-shadow: 0 8px 18px rgba(29, 155, 240, 0.24);
        }
        
        .filter-btn i {
            margin-right: 5px;
        }
        
        .requests-container {
            padding: 0 14px;
        }
        
        .request-card {
            background: linear-gradient(135deg, #17295e 0%, #102448 100%);
            border: 1px solid rgba(96, 165, 250, 0.22);
            border-radius: 14px;
            padding: 16px;
            margin-bottom: 15px;
            box-shadow: 0 10px 24px rgba(0, 0, 0, 0.22);
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .request-card:hover {
            transform: translateX(5px);
            border-color: rgba(56, 189, 248, 0.45);
            box-shadow: 0 14px 30px rgba(0, 0, 0, 0.30);
        }
        
        .request-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
            gap: 10px;
        }
        
        .request-number {
            font-weight: 800;
            color: #f8fafc;
            font-size: 16px;
        }
        
        .request-date {
            font-size: 12px;
            color: #d7e7ff;
            white-space: nowrap;
        }
        
        .request-date i {
            margin-right: 3px;
            color: #d7e7ff;
        }
        
        .request-body {
            display: flex;
            gap: 14px;
            margin-bottom: 12px;
            align-items: center;
        }
        
        .request-icon {
            width: 50px;
            height: 50px;
            background: rgba(56, 189, 248, 0.14);
            border: 1px solid rgba(56, 189, 248, 0.32);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #dff7ff;
            font-size: 22px;
            flex-shrink: 0;
            box-shadow: inset 0 0 12px rgba(56, 189, 248, 0.12);
        }

        .request-icon i {
            color: #dff7ff;
        }
        
        .request-info {
            flex: 1;
            min-width: 0;
        }
        
        .appliance-name {
            font-weight: 800;
            color: #f8fafc;
            margin-bottom: 5px;
            font-size: 16px;
        }
        
        .brand-name {
            color: #d7e7ff;
            font-size: 13px;
            margin-bottom: 5px;
        }
        
        .brand-name i {
            margin-right: 5px;
            color: #dff7ff;
        }
        
        .request-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            font-size: 12px;
            color: #d7e7ff;
        }
        
        .request-meta span i {
            margin-right: 3px;
            color: #dff7ff;
        }
        
        .request-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-top: 1px solid rgba(255, 255, 255, 0.45);
            padding-top: 12px;
            gap: 12px;
        }
        
        .status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 700;
            color: #ffffff;
            border: 1px solid rgba(255, 255, 255, 0.12);
        }
        
        .view-details {
            color: #f8fafc;
            font-size: 13px;
            font-weight: 700;
            text-decoration: none;
            white-space: nowrap;
        }
        
        .empty-state {
            text-align: center;
            padding: 45px 20px;
            background: linear-gradient(135deg, #17295e 0%, #102448 100%);
            border: 1px solid rgba(96, 165, 250, 0.22);
            border-radius: 14px;
            box-shadow: 0 10px 24px rgba(0, 0, 0, 0.22);
        }
        
        .empty-state > i {
            font-size: 60px;
            color: #dff7ff;
            margin-bottom: 20px;
        }
        
        .empty-state h5 {
            color: #ffffff;
            margin-bottom: 10px;
            font-weight: 800;
        }
        
        .empty-state p {
            color: #aebbd4;
            margin-bottom: 20px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%);
            border: none;
            border-radius: 35px;
            padding: 12px 30px;
            font-weight: 700;
        }

        .bottom-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: #080240;
            display: flex;
            justify-content: space-around;
            padding: 10px 0;
            box-shadow: 0 -2px 12px rgba(0,0,0,0.22);
            border-top: 1px solid rgba(96, 165, 250, 0.18);
            z-index: 1000;
        }
        
        .nav-item {
            text-align: center;
            color: #aebbd4;
            text-decoration: none;
            font-size: 12px;
            flex: 1;
        }
        
        .nav-item.active {
            color: #ffffff;
        }
        
        .nav-item i {
            font-size: 22px;
            display: block;
            margin-bottom: 4px;
        }
        
        .loader {
            border: 3px solid #f3f3f3;
            border-radius: 50%;
            border-top: 3px solid #1d9bf0;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 30px auto;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        @media (max-width: 576px) {
            .stats-container {
                padding: 16px 12px 10px;
            }

            .filter-section,
            .requests-container {
                padding-left: 12px;
                padding-right: 12px;
            }

            .stat-card {
                padding: 10px 6px;
            }
            
            .stat-value {
                font-size: 18px;
            }
            
            .stat-label {
                font-size: 10px;
            }

            .request-card {
                padding: 15px;
            }

            .request-icon {
                width: 46px;
                height: 46px;
                font-size: 20px;
            }

            .request-date {
                font-size: 11px;
            }
        }

        /* ===============================
           POPUP / REQUEST DETAILS MODAL FIX
        =============================== */

        .modal-backdrop.show {
            opacity: 0.72 !important;
            background-color: #020617 !important;
        }

        #requestDetailsModal .modal-dialog {
            max-width: 720px;
        }

        #requestDetailsModal .modal-content,
        #imageZoomModal .modal-content {
            background: linear-gradient(135deg, #17295e 0%, #102448 100%) !important;
            border: 1px solid rgba(96, 165, 250, 0.30) !important;
            color: #ffffff !important;
            border-radius: 16px !important;
            overflow: hidden !important;
            box-shadow: 0 25px 70px rgba(0, 0, 0, 0.45) !important;
        }

        #requestDetailsModal .modal-header,
        #imageZoomModal .modal-header {
            background: linear-gradient(135deg, #17295e 0%, #102448 100%) !important;
            color: #ffffff !important;
            border-bottom: 1px solid rgba(96, 165, 250, 0.25) !important;
            padding: 16px 20px !important;
        }

        #requestDetailsModal .modal-title,
        #imageZoomModal .modal-title {
            color: #ffffff !important;
            font-weight: 800 !important;
            font-size: 20px !important;
        }

        #requestDetailsModal .btn-close,
        #imageZoomModal .btn-close {
            filter: brightness(0) invert(1) !important;
            opacity: 1 !important;
        }

        #requestDetailsModal .modal-body,
        #imageZoomModal .modal-body {
            background: linear-gradient(135deg, #17295e 0%, #102448 100%) !important;
            color: #ffffff !important;
            padding: 14px !important;
            max-height: 68vh !important;
            overflow-y: auto !important;
        }

        #requestDetailsModal .modal-body::-webkit-scrollbar {
            width: 8px;
        }

        #requestDetailsModal .modal-body::-webkit-scrollbar-thumb {
            background: rgba(56, 189, 248, 0.45);
            border-radius: 999px;
        }

        #requestDetailsModal .modal-footer {
            background: #102448 !important;
            border-top: 1px solid rgba(96, 165, 250, 0.25) !important;
            padding: 14px !important;
        }

        #requestDetailsModal .btn-secondary {
            background: linear-gradient(135deg, #078ca0 0%, #066b80 100%) !important;
            border: none !important;
            color: #ffffff !important;
            border-radius: 10px !important;
            font-weight: 700 !important;
            padding: 8px 18px !important;
        }

        /* This removes the ugly white bars/cards loaded by AJAX */
        #requestDetailsBody .card,
        #requestDetailsBody .card-body,
        #requestDetailsBody .card-header,
        #requestDetailsBody .list-group,
        #requestDetailsBody .list-group-item,
        #requestDetailsBody .table,
        #requestDetailsBody .table td,
        #requestDetailsBody .table th,
        #requestDetailsBody section,
        #requestDetailsBody article,
        #requestDetailsBody .detail-section,
        #requestDetailsBody .info-section {
            background: rgba(8, 20, 48, 0.42) !important;
            color: #ffffff !important;
            border-color: rgba(96, 165, 250, 0.24) !important;
        }

        #requestDetailsBody .card {
            border-radius: 13px !important;
            overflow: hidden !important;
            margin-bottom: 12px !important;
            border: 1px solid rgba(96, 165, 250, 0.24) !important;
        }

        #requestDetailsBody .card-header {
            background: rgba(56, 189, 248, 0.10) !important;
            border-bottom: 1px solid rgba(96, 165, 250, 0.24) !important;
            padding: 11px 16px !important;
        }

        #requestDetailsBody .card-body {
            padding: 16px !important;
        }

        #requestDetailsBody h1,
        #requestDetailsBody h2,
        #requestDetailsBody h3,
        #requestDetailsBody h4,
        #requestDetailsBody h5,
        #requestDetailsBody h6,
        #requestDetailsBody p,
        #requestDetailsBody span,
        #requestDetailsBody small,
        #requestDetailsBody label,
        #requestDetailsBody strong,
        #requestDetailsBody div {
            color: #ffffff;
        }

        #requestDetailsBody .text-muted {
            color: #d7e7ff !important;
        }

        #requestDetailsBody .badge {
            color: #ffffff !important;
            border-radius: 999px !important;
            padding: 5px 10px !important;
            font-weight: 700 !important;
        }

        #requestDetailsBody hr {
            border-color: rgba(255, 255, 255, 0.30) !important;
            opacity: 1 !important;
        }

        #requestDetailsBody a {
            color: #dff7ff !important;
            font-weight: 700 !important;
        }

        #requestDetailsBody img,
        #imageZoomModal img {
            max-width: 100% !important;
            border-radius: 10px !important;
        }

        .image-gallery,
        .image-preview-container {
            display: grid !important;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)) !important;
            gap: 12px !important;
        }

        .image-thumbnail,
        .request-image-card,
        #requestDetailsBody figure {
            background: rgba(56, 189, 248, 0.10) !important;
            border: 1px solid rgba(56, 189, 248, 0.25) !important;
            border-radius: 12px !important;
            overflow: hidden !important;
            padding: 10px !important;
        }

        .image-thumbnail img {
            width: 100% !important;
            height: 120px !important;
            object-fit: cover !important;
            cursor: pointer !important;
        }

        .image-fallback {
            display: none;
            color: #fecaca !important;
            background: rgba(127, 29, 29, 0.35);
            border: 1px solid rgba(248, 113, 113, 0.35);
            border-radius: 10px;
            padding: 10px;
            font-size: 13px;
            margin-top: 8px;
        }

        @media print {
            .modal-header,
            .modal-footer,
            .bottom-nav,
            .app-header,
            .filter-section,
            .stats-container,
            .d-flex.gap-2 {
                display: none !important;
            }
            
            .modal-body {
                max-height: none !important;
                overflow: visible !important;
            }
            
            .card {
                break-inside: avoid;
                page-break-inside: avoid;
                border: 1px solid #ddd !important;
                margin-bottom: 20px !important;
            }
            
            .badge {
                border: 1px solid #000 !important;
                color: #000 !important;
                background: transparent !important;
            }
        }
    </style>

    <link rel="stylesheet" href="../assets/theme.css">
    <link rel="stylesheet" href="../assets/portal-dark.css">

    <style>
        /*
            Final override after portal-dark.css.
        */

        body {
            background: linear-gradient(135deg, #080240 0%, #093349 100%) !important;
            color: #ffffff !important;
        }

        .app-header {
            background: rgba(15, 31, 74, 0.92) !important;
            padding: 12px 16px !important;
            border-bottom: 1px solid rgba(96, 165, 250, 0.16) !important;
        }

        .header-title,
        .back-btn {
            color: #ffffff !important;
        }

        .stat-card,
        .request-card {
            background: linear-gradient(135deg, #17295e 0%, #102448 100%) !important;
            border: 1px solid rgba(96, 165, 250, 0.22) !important;
        }

        .request-icon {
            background: rgba(56, 189, 248, 0.14) !important;
            border: 1px solid rgba(56, 189, 248, 0.32) !important;
            color: #dff7ff !important;
            box-shadow: inset 0 0 12px rgba(56, 189, 248, 0.12) !important;
        }

        .request-icon i {
            color: #dff7ff !important;
        }

        .request-number,
        .appliance-name,
        .view-details {
            color: #f8fafc !important;
        }

        .brand-name,
        .request-meta,
        .request-date,
        .stat-label {
            color: #d7e7ff !important;
        }

        .brand-name i,
        .request-meta span i,
        .request-date i {
            color: #dff7ff !important;
        }

        .request-footer {
            border-top: 1px solid rgba(255, 255, 255, 0.45) !important;
        }

        .bottom-nav {
            background: #080240 !important;
            border-top: 1px solid rgba(96, 165, 250, 0.18) !important;
        }

        .nav-item {
            color: #aebbd4 !important;
        }

        .nav-item.active {
            color: #ffffff !important;
        }
    </style>

    <div class="stats-container">
        <div class="row g-2">
            <div class="col-4">
                <div class="stat-card">
                    <div class="stat-value"><?php echo $stats['total'] ?? 0; ?></div>
                    <div class="stat-label">Total</div>
                </div>
            </div>

            <div class="col-4">
                <div class="stat-card">
                    <div class="stat-value"><?php echo $stats['pending'] ?? 0; ?></div>
                    <div class="stat-label">New Request</div>
                </div>
            </div>

            <div class="col-4">
                <div class="stat-card">
                    <div class="stat-value"><?php echo $stats['in_progress'] ?? 0; ?></div>
                    <div class="stat-label">In Progress</div>
                </div>
            </div>
        </div>
    </div>

    <div class="filter-section">
        <form method="GET" id="filterForm">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input 
                    type="text" 
                    name="search" 
                    placeholder="Search requests..." 
                    value="<?php echo htmlspecialchars($search_query); ?>"
                >
            </div>
            
            <div class="filter-buttons">
                <button 
                    type="submit" 
                    name="status" 
                    value="all" 
                    class="filter-btn <?php echo $status_filter == 'all' ? 'active' : ''; ?>"
                >
                    <i class="fas fa-list"></i> All
                </button>

                <?php foreach($statuses as $status): ?>
                    <button 
                        type="submit" 
                        name="status" 
                        value="<?php echo $status['id']; ?>"
                        class="filter-btn <?php echo $status_filter == $status['id'] ? 'active' : ''; ?>"
                    >
                        <?php echo htmlspecialchars($status['status_name']); ?>
                    </button>
                <?php endforeach; ?>
            </div>
        </form>
    </div>

    <div class="requests-container">
        <?php if(empty($requests)): ?>
            <div class="empty-state">
                <i class="fas fa-clipboard-list"></i>

                <h5>No Service Requests Found</h5>

                <p>
                    <?php if(!empty($search_query) || $status_filter != 'all'): ?>
                        No requests match your search criteria.
                        <br>
                        <a href="my_requests.php" class="text-info">Clear filters</a>
                    <?php else: ?>
                        You haven't made any service requests yet.
                    <?php endif; ?>
                </p>

                <a href="request.php" class="btn btn-primary d-inline-flex align-items-center justify-content-center gap-2">
                    <i class="fas fa-plus-circle"></i>
                    <span>Request Service</span>
                </a>
            </div>
        <?php else: ?>
            <?php foreach($requests as $request): ?>
                <div class="request-card" onclick="viewRequestDetails(<?php echo $request['id']; ?>)">
                    <div class="request-header">
                        <span class="request-number">
                            #<?php echo htmlspecialchars($request['request_number']); ?>
                        </span>

                        <span class="request-date">
                            <i class="far fa-calendar-alt"></i>
                            <?php echo date('M d, Y', strtotime($request['requested_at'])); ?>
                        </span>
                    </div>
                    
                    <div class="request-body">
                        <div class="request-icon">
                            <i class="fas fa-tools"></i>
                        </div>

                        <div class="request-info">
                            <div class="appliance-name">
                                <?php echo htmlspecialchars($request['appliance_name'] ?? $request['manual_appliance_type'] ?? 'Unknown Appliance'); ?> Service
                            </div>

                            <div class="brand-name">
                                <i class="fas fa-tag"></i>
                                <?php echo htmlspecialchars($request['brand_name'] ?? $request['manual_brand'] ?? 'Unknown Brand'); ?>
                            </div>

                            <div class="request-meta">
                                <span>
                                    <i class="fas fa-map-marker-alt"></i>
                                    <?php echo htmlspecialchars($request['city_name'] ?? 'Unknown City'); ?>
                                </span>

                                <span>
                                    <i class="fas fa-clock"></i>
                                    <?php echo htmlspecialchars($request['urgency_name'] ?? 'Normal'); ?>
                                </span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="request-footer">
                        <span class="status-badge" style="background-color: <?php echo htmlspecialchars($request['status_color'] ?? '#16a34a'); ?>;">
                            <?php echo htmlspecialchars($request['status_name'] ?? 'Unknown'); ?>
                        </span>

                        <span class="view-details">
                            View Details <i class="fas fa-chevron-right ms-1"></i>
                        </span>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <div class="modal fade" id="requestDetailsModal" tabindex="-1">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Request Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body" id="requestDetailsBody">
                    <div class="text-center py-4">
                        <div class="loader"></div>
                        <p class="mt-2">Loading details...</p>
                    </div>
                </div>

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

    <div class="modal fade" id="imageZoomModal" tabindex="-1">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Image Preview</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body text-center p-3">
                    <img src="" id="zoomedImage" class="img-fluid" style="max-height: 70vh;">
                </div>
            </div>
        </div>
    </div>

<?php include __DIR__ . '/includes/footer.php'; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        let requestDetailsModal;
        let imageZoomModal;
        
        $(document).ready(function() {
            requestDetailsModal = new bootstrap.Modal(document.getElementById('requestDetailsModal'));
            imageZoomModal = new bootstrap.Modal(document.getElementById('imageZoomModal'));
            
            let searchTimer;

            $('input[name="search"]').on('input', function() {
                clearTimeout(searchTimer);

                searchTimer = setTimeout(() => {
                    $('#filterForm').submit();
                }, 500);
            });

            const urlParams = new URLSearchParams(window.location.search);
            const requestIdFromNotification = parseInt(urlParams.get('request_id') || '0', 10);
            if (requestIdFromNotification > 0) {
                setTimeout(() => viewRequestDetails(requestIdFromNotification), 250);
            }
        });
        
        function viewRequestDetails(requestId) {
            $('#requestDetailsBody').html(`
                <div class="text-center py-4">
                    <div class="loader"></div>
                    <p class="mt-2">Loading details...</p>
                </div>
            `);

            requestDetailsModal.show();
            
            $.ajax({
                url: 'ajax/get_customer_request_details.php',
                method: 'GET',
                data: { id: requestId },
                success: function(response) {
                    $('#requestDetailsBody').html(response);

                    cleanRequestDetailsModal();
                    fixModalImages();
                },
                error: function() {
                    $('#requestDetailsBody').html(`
                        <div class="alert alert-danger m-3">
                            Error loading request details. Please try again.
                        </div>
                    `);
                }
            });
        }

        function cleanRequestDetailsModal() {
            const body = document.getElementById('requestDetailsBody');

            if (!body) return;

            body.querySelectorAll('.card-header').forEach(header => {
                header.style.background = 'rgba(56, 189, 248, 0.10)';
                header.style.color = '#ffffff';
                header.style.borderBottom = '1px solid rgba(96, 165, 250, 0.24)';
            });

            body.querySelectorAll('.card, .card-body, .list-group-item').forEach(card => {
                card.style.background = 'rgba(8, 20, 48, 0.42)';
                card.style.color = '#ffffff';
                card.style.borderColor = 'rgba(96, 165, 250, 0.24)';
            });

            body.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span,small,label,strong,div').forEach(el => {
                if (!el.classList.contains('badge')) {
                    el.style.color = '#ffffff';
                }
            });

            body.querySelectorAll('.text-muted').forEach(el => {
                el.style.color = '#d7e7ff';
            });
        }

        function fixModalImages() {
            $('#requestDetailsBody img').each(function() {
                const img = this;

                if (!img.getAttribute('data-original-src')) {
                    img.setAttribute('data-original-src', img.getAttribute('src') || '');
                }

                img.onerror = function() {
                    const originalSrc = img.getAttribute('data-original-src') || '';
                    let fileName = originalSrc.split('/').pop() || img.alt || 'image';

                    try {
                        fileName = decodeURIComponent(fileName);
                    } catch(e) {}

                    const encodedFile = encodeURIComponent(fileName);

                    const currentTry = parseInt(img.getAttribute('data-try') || '0', 10);

                    const possiblePaths = [
                        '../uploads/request_images/' + encodedFile,
                        '../uploads/requests/' + encodedFile,
                        '../uploads/' + encodedFile,
                        '../../uploads/request_images/' + encodedFile,
                        '../../uploads/requests/' + encodedFile,
                        '../../uploads/' + encodedFile,
                        '/ushs/uploads/request_images/' + encodedFile,
                        '/ushs/uploads/requests/' + encodedFile,
                        '/ushs/uploads/' + encodedFile
                    ];

                    if (currentTry < possiblePaths.length) {
                        img.setAttribute('data-try', currentTry + 1);
                        img.src = possiblePaths[currentTry];
                    } else {
                        img.style.display = 'none';

                        if (!img.nextElementSibling || !img.nextElementSibling.classList.contains('image-fallback')) {
                            const fallback = document.createElement('div');
                            fallback.className = 'image-fallback';
                            fallback.innerHTML = 'Image not found: ' + fileName;
                            img.insertAdjacentElement('afterend', fallback);
                            fallback.style.display = 'block';
                        }
                    }
                };

                img.style.cursor = 'pointer';

                img.onclick = function(e) {
                    e.stopPropagation();
                    zoomImage(img.src);
                };
            });
        }
        
        function zoomImage(src) {
            document.getElementById('zoomedImage').src = src;
            imageZoomModal.show();
        }
    </script>
</body>
</html>