<?php
// customer/dashboard.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 * 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 unread notifications count
$notif_count_query = "SELECT COUNT(*) as count FROM notifications 
                      WHERE customer_id = :id AND is_read = 0";
$notif_count_stmt = $db->prepare($notif_count_query);
$notif_count_stmt->execute([':id' => $_SESSION['customer_id']]);
$notification_count = $notif_count_stmt->fetch(PDO::FETCH_ASSOC)['count'];

// Get recent notifications for dropdown
$recent_notifs_query = "SELECT * FROM notifications 
                        WHERE customer_id = :id 
                        ORDER BY created_at DESC 
                        LIMIT 5";
$recent_notifs_stmt = $db->prepare($recent_notifs_query);
$recent_notifs_stmt->execute([':id' => $_SESSION['customer_id']]);
$recent_notifications = $recent_notifs_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get customer-specific stats
$total_query = "SELECT COUNT(*) as total FROM service_requests WHERE customer_id = :id";
$total_stmt = $db->prepare($total_query);
$total_stmt->execute([':id' => $_SESSION['customer_id']]);
$total = $total_stmt->fetch(PDO::FETCH_ASSOC)['total'];

$completed_query = "SELECT COUNT(*) as completed FROM service_requests WHERE customer_id = :id AND job_status_id = 4";
$completed_stmt = $db->prepare($completed_query);
$completed_stmt->execute([':id' => $_SESSION['customer_id']]);
$completed = $completed_stmt->fetch(PDO::FETCH_ASSOC)['completed'];

$pending_query = "SELECT COUNT(*) as pending 
                  FROM service_requests 
                  WHERE customer_id = :id 
                  AND job_status_id IN (1, 2, 3)";
$pending_stmt = $db->prepare($pending_query);
$pending_stmt->execute([':id' => $_SESSION['customer_id']]);
$pending = $pending_stmt->fetch(PDO::FETCH_ASSOC)['pending'];

$in_progress_query = "SELECT COUNT(*) as in_progress FROM service_requests WHERE customer_id = :id AND job_status_id = 3";
$in_progress_stmt = $db->prepare($in_progress_query);
$in_progress_stmt->execute([':id' => $_SESSION['customer_id']]);
$in_progress = $in_progress_stmt->fetch(PDO::FETCH_ASSOC)['in_progress'];

// Get customer's recent requests
$recent_query = "SELECT sr.*, a.name as appliance_name, j.status_name, j.color_code,
                 u.name as urgency_name
                 FROM service_requests sr
                 LEFT JOIN appliance_types a ON sr.appliance_type_id = a.id
                 LEFT JOIN job_statuses j ON sr.job_status_id = j.id
                 LEFT JOIN urgency_levels u ON sr.urgency_level_id = u.id
                 WHERE sr.customer_id = :customer_id
                 ORDER BY sr.requested_at DESC LIMIT 5";
$recent_stmt = $db->prepare($recent_query);
$recent_stmt->execute([':customer_id' => $_SESSION['customer_id']]);
$recent_requests = $recent_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get all appliance types for services grid
$appliance_query = "SELECT * FROM appliance_types ORDER BY sort_order";
$appliances = $db->query($appliance_query)->fetchAll(PDO::FETCH_ASSOC);
$icons = ['fa-tools', 'fa-tools', 'fa-tools', 'fa-tools', 'fa-tools', 'fa-tools', 'fa-tools', 'fa-tools', 'fa-tools'];
?>

<!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>Dashboard - Home Service App</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">

    <style>
        :root {
            --primary-color: #3498db;
            --light-blue: #e3f2fd;
            --card-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        body {
            background: linear-gradient(135deg, #080240 0%, #093349 100%) !important;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            margin-bottom: 70px;
            color: #ffffff;
        }
        
        .app-header {
            background: rgba(15, 31, 74, 0.92) !important;
            padding: 12px 16px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.16);
            position: sticky;
            top: 0;
            z-index: 1000;
            border-bottom: 1px solid rgba(96, 165, 250, 0.16);
        }
        
        .header-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .header-title {
            font-weight: 700;
            font-size: 18px;
            color: #ffffff;
        }
        
        .back-btn, 
        .notification-btn {
            background: none;
            border: none;
            font-size: 24px;
            color: #ffffff;
            padding: 0;
            cursor: pointer;
            position: relative;
        }

        .back-btn i,
        .notification-btn i {
            color: #ffffff;
        }
        
        .notification-badge {
            position: absolute;
            top: -5px;
            right: -8px;
            background-color: #e74c3c;
            color: white;
            border-radius: 50%;
            padding: 2px 6px;
            font-size: 10px;
            min-width: 18px;
            text-align: center;
        }
        
        .notification-dropdown {
            position: absolute;
            top: 60px;
            right: 15px;
            width: 320px;
            background: linear-gradient(135deg, #17295e 0%, #102448 100%);
            border: 1px solid rgba(96, 165, 250, 0.22);
            border-radius: 15px;
            box-shadow: 0 10px 24px rgba(0,0,0,0.30);
            display: none;
            z-index: 1001;
            overflow: hidden;
        }
        
        .notification-dropdown.show {
            display: block;
        }
        
        .notification-header {
            padding: 15px;
            border-bottom: 1px solid rgba(96, 165, 250, 0.22);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .notification-header h6 {
            margin: 0;
            font-weight: 700;
            color: #ffffff;
        }
        
        .mark-all-read {
            font-size: 12px;
            color: #dff7ff;
            text-decoration: none;
            font-weight: 700;
        }
        
        .notification-item {
            padding: 12px 15px;
            border-bottom: 1px solid rgba(96, 165, 250, 0.18);
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .notification-item:hover {
            background: rgba(56, 189, 248, 0.10);
        }
        
        .notification-item.unread {
            background: rgba(56, 189, 248, 0.12);
        }
        
        .notification-icon {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            float: left;
        }
        
        .notification-content {
            margin-left: 44px;
        }
        
        .notification-title {
            font-weight: 700;
            font-size: 14px;
            margin-bottom: 3px;
            color: #ffffff;
        }
        
        .notification-message {
            font-size: 12px;
            color: #d7e7ff;
            margin-bottom: 3px;
        }
        
        .notification-time {
            font-size: 10px;
            color: #aebbd4;
        }
        
        .notification-footer {
            padding: 12px 15px;
            text-align: center;
            border-top: 1px solid rgba(96, 165, 250, 0.18);
        }
        
        .notification-footer a {
            color: #dff7ff;
            text-decoration: none;
            font-size: 13px;
            font-weight: 700;
        }
        
        .notification-dropdown-header-fixed {
            display: flex !important;
            align-items: center !important;
            justify-content: space-between !important;
            gap: 12px !important;
            padding: 14px 16px !important;
            border-bottom: 1px solid rgba(96, 165, 250, 0.22) !important;
        }
        
        .notification-dropdown-header-fixed span {
            color: #ffffff !important;
            font-weight: 800 !important;
            font-size: 14px !important;
        }
        
        .notif-view-all-top {
            color: #ffffff !important;
            font-size: 12px !important;
            font-weight: 800 !important;
            text-decoration: underline !important;
            white-space: nowrap !important;
        }
        
        .notif-view-all-top:hover {
            color: #dff7ff !important;
        }
        
        .cover-banner {
            background: linear-gradient(135deg, #17295e 0%, #102448 100%);
            color: white;
            padding: 16px 20px 25px !important;
            border-radius: 0 0 25px 25px;
            margin-bottom: 20px;
            border-bottom: 1px solid rgba(96, 165, 250, 0.22);
        }
        
        .profile-section {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 20px;
            transform: translateY( 2px);
        }

        .profile-avatar {
            width: 70px;
            height: 70px;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2px solid rgba(255, 255, 255, 0.85);
            overflow: hidden;
            flex-shrink: 0;
            padding: 0;
            box-shadow: 0 0 18px rgba(56, 189, 248, 0.18);
        }

        .profile-avatar img.dashboard-logo {
            width: 120px;
            height: 120px;
            max-width: none;
            max-height: none;
            object-fit: contain;
            object-position: center;
            display: block;
            transform: translateY(-3px) !important;
        }
        
        .profile-info h2 {
            font-size: 20px;
            font-weight: 700;
            margin-bottom: 5px;
        }
        
        .profile-info p {
            font-size: 14px;
            opacity: 0.9;
            margin-bottom: 0;
        }
        
        .member-since {
            font-size: 12px;
            opacity: 0.8;
            margin-top: 5px;
        }
        
        .welcome-text {
            font-size: 20px;
            font-weight: 700;
            margin-bottom: 20px;
        }
        
        .request-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%);
            color: #ffffff;
            border: none;
            border-radius: 12px;
            font-weight: 700;
            font-size: 16px;
            box-shadow: 0 10px 18px rgba(29, 155, 240, 0.20);
            transition: transform 0.2s;
        }
        
        .request-btn:hover {
            transform: translateY(-2px);
        }

        .customer-main-actions {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
            width: 100%;
        }

        .call-request-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #16a34a 0%, #22c55e 100%);
            color: #ffffff;
            border: none;
            border-radius: 12px;
            font-weight: 800;
            font-size: 16px;
            box-shadow: 0 10px 18px rgba(34, 197, 94, 0.20);
            transition: transform 0.2s, filter 0.2s;
        }

        .call-request-btn:hover {
            transform: translateY(-2px);
            filter: brightness(1.05);
        }

        @media (max-width: 576px) {
            .customer-main-actions {
                grid-template-columns: 1fr;
            }
        }
        

        .customer-call-overlay {
            position: fixed;
            inset: 0;
            background: rgba(2, 6, 23, 0.72);
            z-index: 5000;
            display: none;
            align-items: center;
            justify-content: center;
            padding: 18px;
        }

        .customer-call-modal {
            width: min(520px, 100%);
            background: linear-gradient(135deg, #17295e, #102448);
            border: 1px solid rgba(56, 189, 248, 0.42);
            border-radius: 18px;
            color: #ffffff;
            box-shadow: 0 24px 80px rgba(0,0,0,0.55);
            overflow: hidden;
        }

        .customer-call-header {
            padding: 16px;
            background: rgba(56, 189, 248, 0.12);
            border-bottom: 1px solid rgba(96, 165, 250, 0.25);
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 12px;
        }

        .customer-call-header h4 {
            font-size: 18px;
            font-weight: 900;
            margin: 0;
        }

        .customer-call-body {
            padding: 20px;
            text-align: center;
        }

        .customer-call-icon {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #1d9bf0, #17bdd4);
            color: #ffffff;
            font-size: 28px;
            margin-bottom: 14px;
            animation: callPulse 1.4s infinite;
        }

        @keyframes callPulse {
            0% { box-shadow: 0 0 0 0 rgba(56,189,248,0.55); }
            70% { box-shadow: 0 0 0 14px rgba(56,189,248,0); }
            100% { box-shadow: 0 0 0 0 rgba(56,189,248,0); }
        }

        .customer-call-status {
            color: #d7e7ff;
            font-weight: 700;
            margin-bottom: 8px;
        }

        .customer-call-note {
            color: #aebbd4;
            font-size: 13px;
            margin-bottom: 0;
        }

        .customer-call-footer {
            padding: 14px 18px;
            border-top: 1px solid rgba(96, 165, 250, 0.22);
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            flex-wrap: wrap;
        }

        .customer-call-close,
        .customer-call-secondary {
            background: rgba(148, 163, 184, 0.18);
            border: 1px solid rgba(148, 163, 184, 0.30);
            color: #ffffff;
            border-radius: 10px;
            padding: 9px 14px;
            font-weight: 800;
        }

        .customer-call-primary {
            background: linear-gradient(135deg, #1d9bf0, #17bdd4);
            border: none;
            color: #ffffff;
            border-radius: 10px;
            padding: 9px 14px;
            font-weight: 900;
        }

        .btn-primary {
            background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%);
            border: none;
            border-radius: 35px;
            padding: 12px 30px;
            font-weight: 700;
        }

        .stats-container {
            padding: 0 15px;
            margin-bottom: 25px;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #17295e 0%, #102448 100%);
            border: 1px solid rgba(96, 165, 250, 0.22);
            border-radius: 12px;
            padding: 15px;
            box-shadow: 0 10px 24px rgba(0, 0, 0, 0.22);
            text-align: center;
            height: 100%;
            transition: transform 0.3s;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            border-color: rgba(56, 189, 248, 0.45);
            box-shadow: 0 14px 30px rgba(0,0,0,0.30);
        }
        
        .stat-number {
            font-size: 24px;
            font-weight: 800;
            color: #f8fafc;
        }
        
        .stat-label {
            font-size: 14px;
            color: #aebbd4;
            margin-top: 5px;
        }
        
        .section-title {
            font-size: 18px;
            font-weight: 700;
            color: #ffffff;
            margin: 20px 15px 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .view-all {
            font-size: 14px;
            color: #9ee7ff;
            text-decoration: none;
            font-weight: 700;
        }

        .view-all i {
            color: #9ee7ff;
        }
        
        .services-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            padding: 0 15px;
            margin-bottom: 20px;
        }
        
        .service-item {
            background: linear-gradient(135deg, #17295e 0%, #102448 100%);
            border: 1px solid rgba(96, 165, 250, 0.22);
            border-radius: 12px;
            padding: 14px 8px;
            text-align: center;
            box-shadow: 0 10px 24px rgba(0, 0, 0, 0.22);
            transition: all 0.3s ease;
            cursor: pointer;
            min-height: 74px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        
        .service-item:hover {
            transform: translateY(-2px);
            border-color: rgba(56, 189, 248, 0.45);
            box-shadow: 0 14px 30px rgba(0, 0, 0, 0.30);
        }

        .service-icon-box {
            width: 36px;
            height: 36px;
            background: rgba(56, 189, 248, 0.14);
            border: 1px solid rgba(56, 189, 248, 0.32);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #dff7ff;
            font-size: 18px;
            flex-shrink: 0;
            box-shadow: inset 0 0 12px rgba(56, 189, 248, 0.12);
            margin-bottom: 8px;
        }

        .service-icon-box i {
            color: #dff7ff !important;
            font-size: 18px;
            margin: 0;
            opacity: 1 !important;
        }
        
        .service-name {
            font-size: 12px;
            color: #f8fafc;
            font-weight: 700;
            line-height: 1.2;
        }
        
        .recent-requests {
            padding: 0 15px;
        }

        .request-card {
            background: linear-gradient(135deg, #17295e 0%, #102448 100%);
            border: 1px solid rgba(96, 165, 250, 0.22);
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 10px;
            box-shadow: 0 10px 24px rgba(0, 0, 0, 0.22);
            display: flex;
            align-items: center;
            gap: 15px;
            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-icon {
            width: 40px;
            height: 40px;
            background: rgba(56, 189, 248, 0.14);
            border: 1px solid rgba(56, 189, 248, 0.32);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #dff7ff;
            font-size: 20px;
            flex-shrink: 0;
            box-shadow: inset 0 0 12px rgba(56, 189, 248, 0.12);
        }

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

        .request-details {
            flex: 1;
        }

        .request-title {
            font-weight: 700;
            color: #f8fafc;
            margin-bottom: 5px;
        }

        .request-meta {
            display: flex;
            gap: 15px;
            font-size: 12px;
            color: #b7c4d8;
        }

        .request-meta i {
            color: #d7e7ff;
        }

        .status-badge {
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 700;
            color: #ffffff;
            border: 1px solid rgba(255, 255, 255, 0.12);
            white-space: nowrap;
        }

        .quick-actions {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            padding: 0 15px;
            margin: 20px 0;
        }
        
        .quick-action-item {
            background: linear-gradient(135deg, #17295e 0%, #102448 100%);
            border: 1px solid rgba(96, 165, 250, 0.22);
            border-radius: 12px;
            padding: 12px 5px;
            text-align: center;
            box-shadow: 0 10px 24px rgba(0, 0, 0, 0.22);
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .quick-action-item:hover {
            transform: translateY(-2px);
            border-color: rgba(56, 189, 248, 0.45);
            box-shadow: 0 14px 30px rgba(0, 0, 0, 0.30);
        }
        
        .quick-action-item i {
            font-size: 20px;
            color: #dff7ff;
            margin-bottom: 5px;
            display: block;
        }
        
        .quick-action-item span {
            font-size: 11px;
            color: #f8fafc;
            font-weight: 700;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            background: linear-gradient(135deg, #17295e 0%, #102448 100%);
            border: 1px solid rgba(96, 165, 250, 0.22);
            border-radius: 15px;
            margin: 0 15px;
            box-shadow: 0 10px 24px rgba(0, 0, 0, 0.22);
        }
        
        .empty-state > i {
            font-size: 48px;
            color: #dff7ff;
            margin-bottom: 15px;
        }

        .empty-state h5 {
            color: #ffffff;
            font-weight: 700;
        }
        
        .empty-state p {
            color: #aebbd4;
            margin-bottom: 15px;
        }

        .modal-content {
            background: linear-gradient(135deg, #17295e 0%, #102448 100%);
            border: 1px solid rgba(96, 165, 250, 0.22);
            color: #ffffff;
            box-shadow: 0 25px 70px rgba(0, 0, 0, 0.45);
        }

        .modal-header {
            border-bottom: 1px solid rgba(96, 165, 250, 0.22);
        }

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

        .modal-title i {
            color: #dff7ff;
        }

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

        .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;
            transition: color 0.3s;
            flex: 1;
        }
        
        .nav-item.active {
            color: #ffffff;
        }
        
        .nav-item i {
            font-size: 22px;
            display: block;
            margin-bottom: 4px;
            color: inherit;
        }

        .nav-item span {
            color: inherit;
        }
        
        @media (max-width: 576px) {
            .services-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .quick-actions {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .notification-dropdown {
                width: 280px;
                right: 10px;
            }

            .profile-section {
                align-items: center;
            }

            .profile-avatar {
                width: 72px;
                height: 72px;
            }

            .profile-avatar img.dashboard-logo {
                width: 118px;
                height: 118px;
            }

            .status-badge {
                font-size: 10px;
                padding: 4px 8px;
            }

            .request-meta {
                flex-direction: column;
                gap: 2px;
            }
        }
    </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;
        }

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

        .profile-avatar {
            width: 100px !important;
            height: 100px !important;
            background: rgba(255, 255, 255, 0.95) !important;
            border-radius: 50% !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            border: 2px solid rgba(255, 255, 255, 0.85) !important;
            overflow: hidden !important;
            flex-shrink: 0 !important;
            padding: 0 !important;
            box-shadow: 0 0 18px rgba(56, 189, 248, 0.18) !important;
        }

        .profile-avatar img.dashboard-logo {
            width: 120px !important;
            height: 120px !important;
            max-width: none !important;
            max-height: none !important;
            object-fit: contain !important;
            object-position: center !important;
            display: block !important;
        }

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

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

        .service-icon-box i,
        .request-icon i {
            color: #dff7ff !important;
            opacity: 1 !important;
        }

        .service-name,
        .request-title {
            color: #f8fafc !important;
        }

        .bottom-nav {
            background: #080240 !important;
        }
    </style>
    <link rel="stylesheet" href="../assets/ushs-global-theme.css">
    <link rel="stylesheet" href="../assets/ushs-header.css">
</head>

<body>
    <!-- ===== USHS Unified Customer Header ===== -->
    <header class="ushs-header app-header">
        <!-- Back button -->
        <button class="ushs-header__back-btn back-btn" onclick="history.back()" aria-label="Go back">
            <i class="fas fa-arrow-left"></i>
        </button>

        <!-- Brand -->
        <a class="ushs-header__brand" href="dashboard.php" style="text-decoration:none;">
            <div class="ushs-header__logo">
                <img src="../assets/icons/ushs.avif" alt="USHS"
                     onerror="this.style.display='none';this.parentNode.innerHTML='<i class=\'fas fa-home\' style=\'font-size:16px;\'></i>'">
            </div>
            <div class="ushs-header__brand-text">
                <span class="ushs-header__brand-name">US In Home Services</span>
                <span class="ushs-header__brand-sub">Customer Portal</span>
            </div>
        </a>

        <span class="ushs-header__title">My Dashboard</span>

        <!-- Actions -->
        <div class="ushs-header__actions">
            <!-- Notifications -->
            <div class="dropdown">
                <button class="ushs-header__icon-btn notification-btn" data-bs-toggle="dropdown" aria-label="Notifications">
                    <i class="fas fa-bell"></i>
                    <?php if($notification_count > 0): ?>
                        <span class="ushs-header__badge"><?= $notification_count ?></span>
                    <?php endif; ?>
                </button>
                <div class="dropdown-menu dropdown-menu-end ushs-notif-panel">
                    <div class="dropdown-header">
                        <span>Notifications</span>
                            <div class="dropdown-divider"></div>
                                <a href="notifications.php" class="notif-view-all-top">
                                    View all
                                </a>
                        <?php if($notification_count > 0): ?>
                            <a href="#" style="font-size:.75rem;" onclick="markAllRead(event)">Mark all read</a>
                        <?php endif; ?>
                    </div>
                    <?php if(empty($recent_notifications)): ?>
                        <div style="padding:16px;text-align:center;color:oklch(0.72 0.02 260);font-size:.8rem;">
                            <i class="fas fa-bell-slash mb-2" style="font-size:1.4rem;"></i>
                            <p class="mb-0">No notifications yet</p>
                        </div>
                        <?php else: ?>
                            <?php foreach($recent_notifications as $notif): ?>
                                <a class="notif-item <?= !empty($notif['is_read']) ? '' : 'unread' ?>"
                                   href="open_notification.php?id=<?= (int)$notif['id'] ?>">
                                    <div class="notif-icon" style="background:oklch(0.62 0.22 255 / 0.14);">
                                        <i class="fas <?= match($notif['type'] ?? 'info') {
                                            'success' => 'fa-check-circle',
                                            'warning' => 'fa-exclamation-triangle',
                                            'danger'  => 'fa-times-circle',
                                            default   => 'fa-info-circle',
                                        } ?>" style="color:oklch(0.62 0.22 255);"></i>
                                    </div>
                                    <div class="notif-body">
                                        <strong><?= htmlspecialchars($notif['title'] ?? 'Notification', ENT_QUOTES, 'UTF-8') ?></strong>
                                        <small><?= htmlspecialchars(mb_strimwidth($notif['message'] ?? '', 0, 70, '…'), ENT_QUOTES, 'UTF-8') ?></small>
                                    </div>
                                </a>
                            <?php endforeach; ?>
                        <?php endif; ?>
                </div>
</div>
            <!-- User chip -->
            <div class="dropdown">
                <div class="ushs-header__user" data-bs-toggle="dropdown" style="cursor:pointer;">
                    <div class="ushs-header__avatar">
                        <?= strtoupper(substr($customer['first_name'] ?? 'C', 0, 1) . substr($customer['last_name'] ?? 'U', 0, 1)) ?>
                    </div>
                    <div class="ushs-header__user-info">
                        <span class="ushs-header__user-name"><?= htmlspecialchars(($customer['first_name'] ?? '') . ' ' . ($customer['last_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                        <span class="ushs-header__user-role">Customer</span>
                    </div>
                    <i class="fas fa-chevron-down ushs-header__user-chevron"></i>
                </div>
                <div class="dropdown-menu dropdown-menu-end">
                    <a class="dropdown-item" href="profile.php"><i class="fas fa-user me-2"></i> Profile</a>
                    <a class="dropdown-item" href="my_requests.php"><i class="fas fa-clipboard-list me-2"></i> My Requests</a>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item text-danger" href="logout.php" onclick="return confirm('Log out of Customer Portal?');"><i class="fas fa-sign-out-alt me-2"></i> Logout</a>
                </div>
            </div>
        </div>
    </header>


    <div class="customer-call-overlay" id="customerCallOverlay">
        <div class="customer-call-modal">
            <div class="customer-call-header">
                <h4><i class="fas fa-phone-volume me-2"></i>Call Request</h4>
                <button class="customer-call-close" onclick="closeCustomerCallModal()"><i class="fas fa-times"></i></button>
            </div>
            <div class="customer-call-body">
                <div class="customer-call-icon" id="customerCallIcon">
                    <i class="fas fa-phone-volume"></i>
                </div>
                <h4 id="customerCallTitle">Connecting you to CSR...</h4>
                <p class="customer-call-status" id="customerCallStatus">Sending your call request to the queue.</p>
                <p class="customer-call-note" id="customerCallNote">Please keep your phone nearby. A CSR will handle your request shortly.</p>
            </div>
            <div class="customer-call-footer">
                <button class="customer-call-secondary" onclick="closeCustomerCallModal()">Close</button>
                <button class="customer-call-primary" onclick="window.location.href='my_requests.php'">View My Requests</button>
            </div>
        </div>
    </div>

    <!-- Cover Banner with Profile Info -->
    <div class="cover-banner">
        <div class="profile-section">
            <div class="profile-avatar">
                <img src="../assets/icons/ushs.avif" alt="USHS Logo" class="dashboard-logo">
            </div>

            <div class="profile-info">
                <h2>Welcome back, <?php echo htmlspecialchars($customer['first_name']); ?>!</h2>

                <p>
                    <i class="fas fa-envelope me-2"></i>
                    <?php echo htmlspecialchars($customer['email']); ?>
                </p>

                <p>
                    <i class="fas fa-phone me-2"></i>
                    <?php echo htmlspecialchars($customer['phone_number']); ?>
                </p>

                <div class="member-since">
                    <i class="far fa-clock me-1"></i>
                    Member since <?php echo date('F Y', strtotime($customer['created_at'])); ?>
                </div>
            </div>
        </div>
        
        <div class="text-center mt-3">
            <h2 class="welcome-text">What appliance can we fix for you today?</h2>

            <div class="customer-main-actions">
                <button class="request-btn" onclick="window.location.href='request.php'">
                    <i class="fas fa-plus-circle me-2"></i>
                    Request Repair Service
                </button>

                <button class="call-request-btn" onclick="requestCustomerCall()">
                    <i class="fas fa-phone-volume me-2"></i>
                    Request a Call
                </button>
            </div>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="stats-container">
        <div class="row g-2">
            <div class="col-3">
                <div class="stat-card">
                    <div class="stat-number"><?php echo $total; ?></div>
                    <div class="stat-label">Total</div>
                </div>
            </div>

            <div class="col-3">
                <div class="stat-card">
                    <div class="stat-number" style="color: #fca5a5;"><?php echo $pending; ?></div>
                    <div class="stat-label">New Request</div>
                </div>
            </div>

            <div class="col-3">
                <div class="stat-card">
                    <div class="stat-number" style="color: #93c5fd;"><?php echo $in_progress; ?></div>
                    <div class="stat-label">Scheduled</div>
                </div>
            </div>

            <div class="col-3">
                <div class="stat-card">
                    <div class="stat-number" style="color: #86efac;"><?php echo $completed; ?></div>
                    <div class="stat-label">Repair Completed</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="quick-actions">
        <div class="quick-action-item" onclick="window.location.href='request.php'">
            <i class="fas fa-plus-circle"></i>
            <span>New Request</span>
        </div>

        <div class="quick-action-item" onclick="window.location.href='my_requests.php'">
            <i class="fas fa-clipboard-list"></i>
            <span>My Requests</span>
        </div>

        <div class="quick-action-item" onclick="window.location.href='messages.php'">
            <i class="fas fa-comment-dots"></i>
            <span>Messages</span>
        </div>

        <div class="quick-action-item" onclick="window.location.href='profile.php'">
            <i class="fas fa-user-cog"></i>
            <span>Profile</span>
        </div>
    </div>

    <!-- Our Services -->
    <div class="section-title">
        Our Services

        <a href="#"
           class="view-all"
           data-bs-toggle="modal"
           data-bs-target="#servicesModal">
            View All <i class="fas fa-chevron-right"></i>
        </a>
    </div>

    <!-- Only show first 6 services -->
    <div class="services-grid">
        <?php foreach(array_slice($appliances, 0, 6) as $index => $appliance): ?>
            <div class="service-item"
                 onclick="window.location.href='request.php?type=<?php echo $appliance['id']; ?>'">

                <div class="service-icon-box">
                    <i class="fas <?php echo $icons[$index % count($icons)]; ?>"></i>
                </div>

                <div class="service-name">
                    <?php echo htmlspecialchars($appliance['name']); ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- Services Modal -->
    <div class="modal fade" id="servicesModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-scrollable modal-lg">
            <div class="modal-content border-0" style="border-radius: 20px;">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-tools me-2"></i>
                        All Available Services
                    </h5>

                    <button type="button"
                            class="btn-close"
                            data-bs-dismiss="modal">
                    </button>
                </div>

                <div class="modal-body">
                    <div class="row g-3">
                        <?php foreach($appliances as $index => $appliance): ?>
                            <div class="col-6 col-md-4">
                                <div class="service-item"
                                     onclick="window.location.href='request.php?type=<?php echo $appliance['id']; ?>'">

                                    <div class="service-icon-box">
                                        <i class="fas <?php echo $icons[$index % count($icons)]; ?>"></i>
                                    </div>

                                    <div class="service-name">
                                        <?php echo htmlspecialchars($appliance['name']); ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent Requests -->
    <div class="section-title">
        Recent Requests

        <?php if(!empty($recent_requests)): ?>
            <a href="my_requests.php" class="view-all">
                View All <i class="fas fa-chevron-right"></i>
            </a>
        <?php endif; ?>
    </div>
    
    <div class="recent-requests">
        <?php if(empty($recent_requests)): ?>
            <div class="empty-state">
                <i class="fas fa-tools"></i>
                <h5>No Service Requests Yet</h5>
                <p>Ready to get started? Book your first repair service today!</p>

                <a href="request.php" class="btn btn-primary d-inline-flex align-items-center justify-content-center gap-2" style="padding: 12px 30px;">
                    <i class="fas fa-plus-circle" style="font-size: 16px; line-height: 1;"></i>
                    <span style="font-size: 16px; line-height: 1;">Request Service</span>
                </a>
            </div>
        <?php else: ?>
            <?php foreach($recent_requests as $request): ?>
                <div class="request-card" onclick="window.location.href='my_requests.php?id=<?php echo $request['id']; ?>'">
                    <div class="request-icon">
                        <i class="fas fa-tools"></i>
                    </div>

                    <div class="request-details">
                        <div class="request-title">
                            <?php echo htmlspecialchars($request['appliance_name']); ?> Service
                        </div>

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

                            <span>
                                <i class="fas fa-tag me-1"></i>
                                <?php echo $request['urgency_name'] ?? 'Normal'; ?>
                            </span>
                        </div>
                    </div>

                    <span class="status-badge" style="background-color: <?php echo $request['color_code']; ?>">
                        <?php echo $request['status_name']; ?>
                    </span>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- Bottom Navigation -->
    <nav class="bottom-nav">
        <a href="dashboard.php" class="nav-item active">
            <i class="fas fa-home"></i>
            <span>Home</span>
        </a>

        <a href="request.php" class="nav-item">
            <i class="fas fa-plus-circle"></i>
            <span>Request</span>
        </a>

        <a href="my_requests.php" class="nav-item">
            <i class="fas fa-clipboard-list"></i>
            <span>My Requests</span>
        </a>

        <a href="messages.php" class="nav-item">
            <i class="fas fa-comments"></i>
            <span>Messages</span>
        </a>

        <a href="profile.php" class="nav-item">
            <i class="fas fa-user"></i>
            <span>Profile</span>
        </a>
    </nav>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        $(document).ready(function() {
            var currentUrl = window.location.pathname.split('/').pop();

            $('.bottom-nav a').each(function() {
                if($(this).attr('href') === currentUrl) {
                    $(this).addClass('active');
                }
            });
            
            setTimeout(function() {
                $('.alert').fadeOut('slow');
            }, 5000);
            
            $('#notificationBtn').click(function(e) {
                e.stopPropagation();
                $('#notificationDropdown').toggleClass('show');
            });
            
            $(document).click(function(e) {
                if (!$(e.target).closest('.notification-dropdown, #notificationBtn').length) {
                    $('#notificationDropdown').removeClass('show');
                }
            });
            
            $('.notification-item').click(function() {
                var notifId = $(this).data('id');

                if(notifId) {
                    $.ajax({
                        url: 'ajax/mark_notification_read.php',
                        method: 'POST',
                        data: { id: notifId },
                        success: function() {
                            updateNotificationCount();
                        }
                    });
                }
            });
        });
        
        function markAllRead(e) {
            e.preventDefault();

            $.ajax({
                url: 'ajax/mark_all_read.php',
                method: 'POST',
                success: function() {
                    $('.notification-item').removeClass('unread');
                    $('.notification-badge').remove();
                    $('#notificationDropdown').removeClass('show');
                }
            });
        }
        
        function updateNotificationCount() {
            $.ajax({
                url: 'ajax/get_notification_count.php',
                method: 'GET',
                success: function(count) {
                    if(count > 0) {
                        if($('.notification-badge').length) {
                            $('.notification-badge').text(count);
                        } else {
                            $('#notificationBtn').append('<span class="notification-badge">' + count + '</span>');
                        }
                    } else {
                        $('.notification-badge').remove();
                    }
                }
            });
        }
        
        let customerCallPollTimer = null;
        let activeCustomerCallId = null;

        function openCustomerCallModal(title, status, note) {
            $('#customerCallTitle').text(title || 'Connecting you to CSR...');
            $('#customerCallStatus').text(status || 'Sending your call request to the queue.');
            $('#customerCallNote').text(note || 'Please keep your phone nearby. A CSR will handle your request shortly.');
            $('#customerCallOverlay').css('display', 'flex');
        }

        function closeCustomerCallModal() {
            $('#customerCallOverlay').hide();
        }

        function startCustomerCallPolling(callId) {
            activeCustomerCallId = callId;

            if (customerCallPollTimer) {
                clearInterval(customerCallPollTimer);
            }

            pollCustomerCallStatus();
            customerCallPollTimer = setInterval(pollCustomerCallStatus, 5000);
        }

        function pollCustomerCallStatus() {
            if (!activeCustomerCallId) return;

            $.ajax({
                url: 'ajax/get_call_request_status.php',
                method: 'GET',
                dataType: 'json',
                data: { call_id: activeCustomerCallId },
                success: function(response) {
                    if (!response.success || !response.call) return;

                    const call = response.call;
                    const csrName = call.accepted_by_name || call.assigned_csr_name || 'a CSR';

                    if (call.status === 'manager_queue') {
                        openCustomerCallModal(
                            'Waiting for Team Leader...',
                            'Your call request is in the Team Leader queue.',
                            'Please keep your phone nearby. A Team Leader will route your call request shortly.'
                        );
                    } else if (call.status === 'assigned') {
                        openCustomerCallModal(
                            'CSR Assigned',
                            csrName + ' has been assigned to your call request.',
                            'Please keep your phone nearby. The CSR will assist you shortly.'
                        );
                    } else if (call.status === 'accepted') {
                        openCustomerCallModal(
                            'CSR Connected',
                            csrName + ' accepted your call request.',
                            'Please keep your phone nearby while the CSR handles your request.'
                        );
                    } else if (call.status === 'completed') {
                        openCustomerCallModal(
                            'Call Completed',
                            'Your call request has been completed.',
                            'Thank you. You may view your request details anytime.'
                        );
                        clearInterval(customerCallPollTimer);
                    } else if (call.status === 'missed') {
                        openCustomerCallModal(
                            'Call Missed',
                            'The CSR marked this call request as missed.',
                            'You may request another call if you still need assistance.'
                        );
                        clearInterval(customerCallPollTimer);
                    } else if (call.status === 'cancelled') {
                        openCustomerCallModal(
                            'Call Cancelled',
                            'This call request has been cancelled.',
                            'You may request another call if needed.'
                        );
                        clearInterval(customerCallPollTimer);
                    }
                }
            });
        }

        function requestCustomerCall() {
            const latestRequestId = <?php echo !empty($recent_requests) ? (int)$recent_requests[0]['id'] : 0; ?>;

            if (!latestRequestId) {
                openCustomerCallModal(
                    'Repair Request Needed',
                    'Please create a repair request before requesting a call.',
                    'This helps the CSR see your appliance details while handling the call.'
                );
                return;
            }

            openCustomerCallModal(
                'Connecting you to CSR...',
                'Sending your call request to the Team Leader queue.',
                'Please keep this page open and keep your phone nearby.'
            );

            $.ajax({
                url: 'ajax/create_call_request.php',
                method: 'POST',
                dataType: 'json',
                data: {
                    request_id: latestRequestId
                },
                success: function(response) {
                    if (response.success) {
                        activeCustomerCallId = response.call_id;
                        openCustomerCallModal(
                            'Call Request Sent',
                            response.message || 'Your call request has been sent to CSR.',
                            'You will see updates here once a CSR accepts or completes your call request.'
                        );

                        if (response.room_url) {
                            window.location.href = response.room_url;
                            return;
                        }

                        if (response.call_id) {
                            startCustomerCallPolling(response.call_id);
                        }
                    } else {
                        openCustomerCallModal(
                            'Unable to Request Call',
                            response.message || 'Unable to send call request.',
                            'Please try again or create a repair request first.'
                        );
                    }
                },
                error: function() {
                    openCustomerCallModal(
                        'Connection Error',
                        'Unable to send call request right now.',
                        'Please try again in a few seconds.'
                    );
                }
            });
        }

        function refreshStats() {
            location.reload();
        }
    </script>
</body>
</html>