<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
include 'layouts/dbconn.php';

// Fix the menu config include with error handling
if (file_exists('includes/menu_config.php')) {
    require_once 'includes/menu_config.php';
} else {
    function getMenuConfig($userRole = 'guest') {
        return [
            [
                'title' => 'Dashboard',
                'icon' => 'ph-chart-line',
                'url' => 'index.php',
                'type' => 'link'
            ]
        ];
    }
}

// Set timezone
date_default_timezone_set('Africa/Nairobi');

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

// Fetch user details with proper schema alignment
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name, ur.role_code,
                     CASE 
                         WHEN c.caregiver_id IS NOT NULL THEN 'CAREGIVER'
                         WHEN cl.client_id IS NOT NULL THEN 'CLIENT'
                         ELSE 'ADMIN'
                     END as user_category,
                     c.caregiver_id,
                     cl.client_id
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     LEFT JOIN caregivers c ON u.user_id = c.user_id
                     LEFT JOIN clients cl ON u.user_id = cl.user_id
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details) {
    header('Location: login.php');
    exit();
}

$role_code = $user_details['role_code'];
$role_name = $user_details['role_name'];

// Extract full name from profile JSON
$profile = json_decode($user_details['profile'], true);
$full_name = isset($profile['first_name']) && isset($profile['last_name']) 
    ? $profile['first_name'] . ' ' . $profile['last_name'] 
    : $user_details['username'];

$email = $user_details['email'];
$phone_primary = $user_details['phone'];
$user_category = $user_details['user_category'];

// Initialize metrics array
$metrics = [];

// Universal Caregiver System Metrics
$today = date('Y-m-d');
$current_month = date('Y-m');
$current_week = date('Y-m-d', strtotime('monday this week'));

// Today's schedules
$today_schedules_sql = "SELECT COUNT(*) as count FROM schedules 
                       WHERE shift_date = ? AND status IN ('scheduled', 'confirmed', 'in_progress')";
$stmt = $conn->prepare($today_schedules_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['today_schedules'] = $stmt->get_result()->fetch_assoc()['count'];

// Active caregivers
$active_caregivers_sql = "SELECT COUNT(*) as count FROM caregivers c
                         JOIN users u ON c.user_id = u.user_id 
                         WHERE c.is_active = 1 AND u.status = 'ACTIVE'";
$metrics['active_caregivers'] = $conn->query($active_caregivers_sql)->fetch_assoc()['count'];

// Total active clients
$total_clients_sql = "SELECT COUNT(*) as count FROM clients WHERE status = 'ACTIVE'";
$metrics['total_clients'] = $conn->query($total_clients_sql)->fetch_assoc()['count'];

// Today's attendance records
$today_attendance_sql = "SELECT COUNT(*) as count FROM attendance_records 
                        WHERE DATE(check_in_time) = ?";
$stmt = $conn->prepare($today_attendance_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['today_attendance'] = $stmt->get_result()->fetch_assoc()['count'];

// Monthly revenue
$monthly_revenue_sql = "SELECT COALESCE(SUM(net_amount), 0) as revenue FROM payments 
                       WHERE DATE(payment_date) LIKE ? AND status = 'completed'";
$stmt = $conn->prepare($monthly_revenue_sql);
$current_month_pattern = $current_month . '%';
$stmt->bind_param("s", $current_month_pattern);
$stmt->execute();
$metrics['monthly_revenue'] = $stmt->get_result()->fetch_assoc()['revenue'];

// Pending invoices
$pending_invoices_sql = "SELECT COUNT(*) as count FROM invoices 
                        WHERE status IN ('sent', 'partial_payment', 'overdue')";
$metrics['pending_invoices'] = $conn->query($pending_invoices_sql)->fetch_assoc()['count'];

// Active care plans
$active_careplans_sql = "SELECT COUNT(*) as count FROM care_plans WHERE status = 'active'";
$metrics['active_careplans'] = $conn->query($active_careplans_sql)->fetch_assoc()['count'];

// Expiring certifications (next 30 days)
$expiring_certs_sql = "SELECT COUNT(*) as count FROM caregiver_certifications 
                      WHERE status = 'active' 
                      AND expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)";
$metrics['expiring_certifications'] = $conn->query($expiring_certs_sql)->fetch_assoc()['count'];

// Completed shifts today
$completed_shifts_sql = "SELECT COUNT(*) as count FROM schedules 
                        WHERE shift_date = ? AND status = 'completed'";
$stmt = $conn->prepare($completed_shifts_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['completed_shifts'] = $stmt->get_result()->fetch_assoc()['count'];

// No-shows today
$no_shows_sql = "SELECT COUNT(*) as count FROM schedules 
                WHERE shift_date = ? AND status = 'no_show'";
$stmt = $conn->prepare($no_shows_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['no_shows_today'] = $stmt->get_result()->fetch_assoc()['count'];

// New clients this week
$new_clients_sql = "SELECT COUNT(*) as count FROM clients 
                   WHERE DATE(created_at) >= ?";
$stmt = $conn->prepare($new_clients_sql);
$stmt->bind_param("s", $current_week);
$stmt->execute();
$metrics['new_clients_week'] = $stmt->get_result()->fetch_assoc()['count'];

// Available caregivers today
$available_caregivers_sql = "SELECT COUNT(DISTINCT c.caregiver_id) as count 
                            FROM caregivers c
                            JOIN users u ON c.user_id = u.user_id
                            LEFT JOIN schedules s ON c.caregiver_id = s.caregiver_id AND s.shift_date = ?
                            WHERE c.is_active = 1 AND u.status = 'ACTIVE' 
                            AND s.schedule_id IS NULL";
$stmt = $conn->prepare($available_caregivers_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['available_caregivers_today'] = $stmt->get_result()->fetch_assoc()['count'];

// Role-specific metrics
switch($user_category) {
    case 'CAREGIVER':
        $caregiver_id = $user_details['caregiver_id'];
        
        // My schedules today
        $my_schedules_sql = "SELECT COUNT(*) as count FROM schedules 
                           WHERE caregiver_id = ? AND shift_date = ? 
                           AND status IN ('scheduled', 'confirmed', 'in_progress')";
        $stmt = $conn->prepare($my_schedules_sql);
        $stmt->bind_param("is", $caregiver_id, $today);
        $stmt->execute();
        $metrics['my_schedules_today'] = $stmt->get_result()->fetch_assoc()['count'];
        
        // My completed shifts this month
        $my_shifts_sql = "SELECT COUNT(*) as count, COALESCE(SUM(total_amount), 0) as earnings 
                        FROM schedules 
                        WHERE caregiver_id = ? AND DATE(shift_date) LIKE ? AND status = 'completed'";
        $stmt = $conn->prepare($my_shifts_sql);
        $stmt->bind_param("is", $caregiver_id, $current_month_pattern);
        $stmt->execute();
        $shift_data = $stmt->get_result()->fetch_assoc();
        $metrics['my_monthly_shifts'] = $shift_data['count'];
        $metrics['my_monthly_earnings'] = $shift_data['earnings'];
        
        // My active clients
        $my_clients_sql = "SELECT COUNT(DISTINCT client_id) as count FROM schedules 
                         WHERE caregiver_id = ? AND status != 'cancelled'";
        $stmt = $conn->prepare($my_clients_sql);
        $stmt->bind_param("i", $caregiver_id);
        $stmt->execute();
        $metrics['my_active_clients'] = $stmt->get_result()->fetch_assoc()['count'];
        
        // My pending tasks
        $my_tasks_sql = "SELECT COUNT(*) as count FROM care_plan_tasks cpt
                       JOIN care_plans cp ON cpt.care_plan_id = cp.care_plan_id
                       JOIN schedules s ON cp.client_id = s.client_id
                       WHERE s.caregiver_id = ? AND cpt.status = 'pending'";
        $stmt = $conn->prepare($my_tasks_sql);
        $stmt->bind_param("i", $caregiver_id);
        $stmt->execute();
        $metrics['my_pending_tasks'] = $stmt->get_result()->fetch_assoc()['count'];
        break;
        
    case 'CLIENT':
        $client_id = $user_details['client_id'];
        
        // My upcoming visits
        $my_visits_sql = "SELECT COUNT(*) as count FROM schedules 
                        WHERE client_id = ? AND shift_date >= CURDATE() 
                        AND status IN ('scheduled', 'confirmed')";
        $stmt = $conn->prepare($my_visits_sql);
        $stmt->bind_param("i", $client_id);
        $stmt->execute();
        $metrics['my_upcoming_visits'] = $stmt->get_result()->fetch_assoc()['count'];
        
        // My active care plan
        $my_careplan_sql = "SELECT * FROM care_plans WHERE client_id = ? AND status = 'active'";
        $stmt = $conn->prepare($my_careplan_sql);
        $stmt->bind_param("i", $client_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $metrics['has_active_careplan'] = $result->num_rows > 0;
        
        // My pending payments
        $my_payments_sql = "SELECT COUNT(*) as count, COALESCE(SUM(balance_due), 0) as balance 
                          FROM invoices 
                          WHERE client_id = ? AND status IN ('sent', 'partial_payment', 'overdue')";
        $stmt = $conn->prepare($my_payments_sql);
        $stmt->bind_param("i", $client_id);
        $stmt->execute();
        $payment_data = $stmt->get_result()->fetch_assoc();
        $metrics['my_pending_invoices'] = $payment_data['count'];
        $metrics['my_balance_due'] = $payment_data['balance'];
        
        // My assigned caregiver
        $my_caregiver_sql = "SELECT c.*, u.full_name FROM schedules s
                           JOIN caregivers c ON s.caregiver_id = c.caregiver_id
                           JOIN users u ON c.user_id = u.user_id
                           WHERE s.client_id = ? AND s.shift_date >= CURDATE()
                           ORDER BY s.shift_date LIMIT 1";
        $stmt = $conn->prepare($my_caregiver_sql);
        $stmt->bind_param("i", $client_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $metrics['assigned_caregiver'] = $result->fetch_assoc();
        }
        break;
}

// Revenue trends (last 30 days)
$revenue_trends_sql = "SELECT 
    DATE(payment_date) as date,
    SUM(net_amount) as revenue,
    COUNT(*) as transaction_count
    FROM payments 
    WHERE payment_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    AND status = 'completed'
    GROUP BY DATE(payment_date)
    ORDER BY date";
$revenue_trends_result = $conn->query($revenue_trends_sql);
$revenue_data = [];
while ($row = $revenue_trends_result->fetch_assoc()) {
    $revenue_data[] = $row;
}

// Schedule status distribution
$schedule_status_sql = "SELECT status, COUNT(*) as count 
                       FROM schedules 
                       WHERE shift_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
                       GROUP BY status";
$schedule_status_result = $conn->query($schedule_status_sql);
$schedule_status_data = [];
while ($row = $schedule_status_result->fetch_assoc()) {
    $schedule_status_data[] = $row;
}

// Recent activities based on role
$recent_activities = [];
switch($user_category) {
    case 'CAREGIVER':
        if (isset($caregiver_id)) {
            $recent_activities_sql = "SELECT 'shift' as type, s.schedule_number as reference,
                                    c.client_number, u.full_name as client_name, s.shift_date, s.start_time
                                    FROM schedules s
                                    JOIN clients c ON s.client_id = c.client_id
                                    JOIN users u ON c.user_id = u.user_id
                                    WHERE s.caregiver_id = ? 
                                    ORDER BY s.shift_date DESC, s.start_time DESC LIMIT 5";
            $stmt = $conn->prepare($recent_activities_sql);
            $stmt->bind_param("i", $caregiver_id);
            $stmt->execute();
            $recent_activities = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        }
        break;
        
    case 'CLIENT':
        if (isset($client_id)) {
            $recent_activities_sql = "SELECT 'visit' as type, s.schedule_number as reference,
                                    c.employee_number, u.full_name as caregiver_name, s.shift_date, s.start_time
                                    FROM schedules s
                                    JOIN caregivers c ON s.caregiver_id = c.caregiver_id
                                    JOIN users u ON c.user_id = u.user_id
                                    WHERE s.client_id = ?
                                    ORDER BY s.shift_date DESC, s.start_time DESC LIMIT 5";
            $stmt = $conn->prepare($recent_activities_sql);
            $stmt->bind_param("i", $client_id);
            $stmt->execute();
            $recent_activities = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        }
        break;
        
    default:
        // Admin view - show general system activities
        $recent_activities_sql = "SELECT 
                                        'schedule' AS type, 
                                        s.schedule_number AS reference,
                                        c.client_number, 
                                        CONCAT(
                                            JSON_UNQUOTE(JSON_EXTRACT(cu.profile, '$.first_name')), ' ', 
                                            JSON_UNQUOTE(JSON_EXTRACT(cu.profile, '$.last_name'))
                                        ) AS client_name,
                                        cg.employee_number, 
                                        CONCAT(
                                            JSON_UNQUOTE(JSON_EXTRACT(cgu.profile, '$.first_name')), ' ', 
                                            JSON_UNQUOTE(JSON_EXTRACT(cgu.profile, '$.last_name'))
                                        ) AS caregiver_name,
                                        s.shift_date, 
                                        s.start_time, 
                                        s.status
                                    FROM schedules s
                                    JOIN clients c ON s.client_id = c.client_id
                                    JOIN users cu ON c.user_id = cu.user_id
                                    JOIN caregivers cg ON s.caregiver_id = cg.caregiver_id
                                    JOIN users cgu ON cg.user_id = cgu.user_id
                                    ORDER BY s.created_at DESC
                                    LIMIT 5;
                                    ";
        $recent_activities = $conn->query($recent_activities_sql)->fetch_all(MYSQLI_ASSOC);
        break;
}

// Expiring certifications list
$expiring_certs_list_sql = "SELECT 
    cc.*, 
    cert.certification_name, 
    c.employee_number,
    CONCAT(
        JSON_UNQUOTE(JSON_EXTRACT(u.profile, '$.first_name')), ' ',
        JSON_UNQUOTE(JSON_EXTRACT(u.profile, '$.last_name'))
    ) AS full_name
FROM caregiver_certifications cc
JOIN certifications cert ON cc.certification_id = cert.certification_id
JOIN caregivers c ON cc.caregiver_id = c.caregiver_id
JOIN users u ON c.user_id = u.user_id
WHERE cc.status = 'active'
  AND cc.expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
ORDER BY cc.expiry_date ASC
LIMIT 10";

$expiring_certs_list = $conn->query($expiring_certs_list_sql)->fetch_all(MYSQLI_ASSOC);

?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Caregiver Management Dashboard')); ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.css">
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 0.5rem 1.5rem 1.5rem 1.5rem;
        }
        
        /* Welcome Header - Caregiver Brand Colors */
        .welcome-header {
            background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            position: relative;
            overflow: hidden;
        }
        
        .welcome-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><path d="M20,20 Q50,5 80,20 Q85,50 80,80 Q50,95 20,80 Q5,50 20,20" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="1"/></svg>');
            animation: float 20s ease-in-out infinite;
        }
        
        @keyframes float {
            0%, 100% { transform: rotate(0deg) translateY(0px); }
            50% { transform: rotate(180deg) translateY(-20px); }
        }
        
        .welcome-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
            position: relative;
            z-index: 1;
        }
        
        .welcome-text h2 {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .welcome-text p {
            opacity: 0.9;
            margin: 0;
        }
        
        .datetime-display {
            text-align: right;
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            padding: 1rem;
            min-width: 200px;
        }
        
        .current-time {
            font-size: 1.5rem;
            font-weight: 700;
            font-family: 'Courier New', monospace;
        }
        
        .current-date {
            font-size: 0.9rem;
            opacity: 0.8;
        }
        
        /* Metrics Cards */
        .metrics-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .metric-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: all 0.2s ease;
            position: relative;
            overflow: hidden;
        }
        
        .metric-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: var(--accent-color, #10b981);
            opacity: 0;
            transition: opacity 0.2s ease;
        }
        
        .metric-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }
        
        .metric-card:hover::before {
            opacity: 1;
        }
        
        .metric-card.schedules { --accent-color: #2563eb; }
        .metric-card.caregivers { --accent-color: #10b981; }
        .metric-card.clients { --accent-color: #f59e0b; }
        .metric-card.revenue { --accent-color: #8b5cf6; }
        .metric-card.attendance { --accent-color: #ec4899; }
        .metric-card.careplans { --accent-color: #06b6d4; }
        
        .metric-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 1rem;
        }
        
        .metric-title {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin: 0;
        }
        
        .metric-icon {
            background: #f1f5f9;
            border-radius: 8px;
            padding: 0.5rem;
            font-size: 1.25rem;
            color: var(--accent-color, #10b981);
        }
        
        .metric-value {
            font-size: 2.25rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
            line-height: 1;
        }
        
        .metric-change {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
            margin-bottom: 1rem;
        }
        
        .metric-trend {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .trend-up { color: #10b981; }
        .trend-down { color: #ef4444; }
        .trend-neutral { color: #3b82f6; }
        
        .metric-link {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            margin-top: 0.5rem;
            color: var(--accent-color, #2563eb);
            text-decoration: none;
            font-size: 0.875rem;
            font-weight: 500;
            transition: color 0.2s ease;
        }
        
        .metric-link:hover {
            color: #1e40af;
        }
        
        /* Quick Actions */
        .quick-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .quick-action {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 1.5rem;
            text-align: center;
            text-decoration: none;
            color: #1e293b;
            transition: all 0.2s ease;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        
        .quick-action:hover {
            color: #2563eb;
            border-color: #2563eb;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }
        
        .quick-action-icon {
            font-size: 2.5rem;
            margin-bottom: 0.75rem;
            color: #2563eb;
            display: block;
        }
        
        .quick-action-title {
            font-weight: 600;
            font-size: 0.875rem;
            margin-bottom: 0.25rem;
        }
        
        .quick-action-desc {
            font-size: 0.75rem;
            color: #64748b;
            margin: 0;
        }
        
        /* Charts and Analytics */
        .chart-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .chart-header {
            padding: 1.5rem 1.5rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .chart-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 1rem 0;
        }
        
        .chart-body {
            padding: 1rem 1.5rem 1.5rem;
        }
        
        /* Tables */
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        /* Status Badges */
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-scheduled { background: #dbeafe; color: #1d4ed8; }
        .status-confirmed { background: #dcfce7; color: #166534; }
        .status-in_progress { background: #fef3c7; color: #92400e; }
        .status-completed { background: #d1fae5; color: #065f46; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        .status-no_show { background: #fecaca; color: #7f1d1d; }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .welcome-content {
                flex-direction: column;
                text-align: center;
            }
            
            .datetime-display {
                min-width: auto;
                width: 100%;
            }
            
            .metrics-row {
                grid-template-columns: 1fr;
            }
            
            .metric-value {
                font-size: 1.75rem;
            }
            
            .quick-actions {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Welcome Header -->
                    <div class="welcome-header">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>
                                    <?php 
                                    $hour = date('H');
                                    $greeting = $hour < 12 ? 'Good Morning' : ($hour < 17 ? 'Good Afternoon' : 'Good Evening');
                                    echo $greeting . ', ' . htmlspecialchars($full_name);
                                    ?>
                                </h2>
                                <p><?php echo htmlspecialchars($role_name); ?> - Caregiver Management System
                                    <?php if($phone_primary): ?> | <?php echo htmlspecialchars($phone_primary); ?><?php endif; ?>
                                </p>
                                <small style="opacity: 0.8;">Professional Healthcare Services Management</small>
                            </div>
                            <div class="datetime-display d-none d-md-block">
                                <div class="current-time" id="currentTime"><?php echo date('h:i A'); ?></div>
                                <div class="current-date" id="currentDate"><?php echo date('l, M j, Y'); ?></div>
                            </div>
                        </div>
                    </div>

                    <!-- System Overview Metrics -->
                    <div class="metrics-row">
                        <?php if ($user_category === 'ADMIN' || $role_code === 'SUPER_ADMIN'): ?>
                        <div class="metric-card schedules">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Today's Schedules</h6>
                                </div>
                                <span class="metric-icon">📅</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['today_schedules']); ?></div>
                            <div class="metric-change">Active shifts scheduled</div>
                            <div class="metric-trend trend-up">
                                <i class="ri-checkbox-circle-line"></i>
                                <span>Completed: <?php echo number_format($metrics['completed_shifts']); ?></span>
                            </div>
                            <a href="todays_schedules.php" class="metric-link">
                                View all schedules <i class="ri-arrow-right-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card caregivers">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Active Caregivers</h6>
                                </div>
                                <span class="metric-icon">👨‍⚕️</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['active_caregivers']); ?></div>
                            <div class="metric-change">Total workforce</div>
                            <div class="metric-trend trend-neutral">
                                <i class="ri-user-star-line"></i>
                                <span>Available: <?php echo number_format($metrics['available_caregivers_today']); ?></span>
                            </div>
                            <a href="list_caregivers.php" class="metric-link">
                                Manage caregivers <i class="ri-team-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card clients">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Active Clients</h6>
                                </div>
                                <span class="metric-icon">👥</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['total_clients']); ?></div>
                            <div class="metric-change">Receiving care</div>
                            <div class="metric-trend trend-up">
                                <i class="ri-user-add-line"></i>
                                <span>New this week: <?php echo $metrics['new_clients_week']; ?></span>
                            </div>
                            <a href="list_clients.php" class="metric-link">
                                View clients <i class="ri-group-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card revenue">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Monthly Revenue</h6>
                                </div>
                                <span class="metric-icon">💰</span>
                            </div>
                            <div class="metric-value">$<?php echo number_format($metrics['monthly_revenue'], 2); ?></div>
                            <div class="metric-change">This month's income</div>
                            <div class="metric-trend trend-up">
                                <i class="ri-funds-line"></i>
                                <span>Pending: <?php echo $metrics['pending_invoices']; ?> invoices</span>
                            </div>
                            <a href="revenue_reports.php" class="metric-link">
                                View financials <i class="ri-money-dollar-circle-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card attendance">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Today's Attendance</h6>
                                </div>
                                <span class="metric-icon">✅</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['today_attendance']); ?></div>
                            <div class="metric-change">Clock-ins recorded</div>
                            <div class="metric-trend trend-down">
                                <i class="ri-close-circle-line"></i>
                                <span>No-shows: <?php echo $metrics['no_shows_today']; ?></span>
                            </div>
                            <a href="attendance_records.php" class="metric-link">
                                View attendance <i class="ri-time-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card careplans">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Active Care Plans</h6>
                                </div>
                                <span class="metric-icon">📋</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['active_careplans']); ?></div>
                            <div class="metric-change">Ongoing care programs</div>
                            <div class="metric-trend trend-neutral">
                                <i class="ri-file-list-line"></i>
                                <span>Comprehensive care</span>
                            </div>
                            <a href="care_plans.php" class="metric-link">
                                Manage plans <i class="ri-file-list-3-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Certifications</h6>
                                </div>
                                <span class="metric-icon">🎓</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['expiring_certifications']); ?></div>
                            <div class="metric-change">Expiring in 30 days</div>
                            <div class="metric-trend trend-down">
                                <i class="ri-alarm-warning-line"></i>
                                <span>Requires renewal</span>
                            </div>
                            <a href="certifications.php" class="metric-link">
                                View details <i class="ri-award-line"></i>
                            </a>
                        </div>
                        
                        <?php elseif ($user_category === 'CAREGIVER'): ?>
                        <!-- Caregiver-specific metrics -->
                        <div class="metric-card schedules">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">My Schedules Today</h6>
                                </div>
                                <span class="metric-icon">📅</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['my_schedules_today'] ?? 0); ?></div>
                            <div class="metric-change">Shifts assigned</div>
                            <a href="my_schedule.php" class="metric-link">
                                View my schedule <i class="ri-calendar-check-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card revenue">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Monthly Earnings</h6>
                                </div>
                                <span class="metric-icon">💰</span>
                            </div>
                            <div class="metric-value">$<?php echo number_format($metrics['my_monthly_earnings'] ?? 0, 2); ?></div>
                            <div class="metric-change">Shifts: <?php echo $metrics['my_monthly_shifts'] ?? 0; ?></div>
                            <a href="my_earnings.php" class="metric-link">
                                View details <i class="ri-money-dollar-circle-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card clients">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">My Clients</h6>
                                </div>
                                <span class="metric-icon">👥</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['my_active_clients'] ?? 0); ?></div>
                            <div class="metric-change">Active assignments</div>
                            <a href="my_clients.php" class="metric-link">
                                View clients <i class="ri-user-heart-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Pending Tasks</h6>
                                </div>
                                <span class="metric-icon">📝</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['my_pending_tasks'] ?? 0); ?></div>
                            <div class="metric-change">Care tasks</div>
                            <a href="my_tasks.php" class="metric-link">
                                Complete tasks <i class="ri-task-line"></i>
                            </a>
                        </div>
                        
                        <?php elseif ($user_category === 'CLIENT'): ?>
                        <!-- Client-specific metrics -->
                        <div class="metric-card schedules">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Upcoming Visits</h6>
                                </div>
                                <span class="metric-icon">📅</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['my_upcoming_visits'] ?? 0); ?></div>
                            <div class="metric-change">Scheduled care visits</div>
                            <a href="my_schedule.php" class="metric-link">
                                View schedule <i class="ri-calendar-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card careplans">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">My Care Plan</h6>
                                </div>
                                <span class="metric-icon">📋</span>
                            </div>
                            <div class="metric-value"><?php echo ($metrics['has_active_careplan'] ?? false) ? 'Active' : 'None'; ?></div>
                            <div class="metric-change">Care program status</div>
                            <a href="my_care_plan.php" class="metric-link">
                                View plan <i class="ri-file-list-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card revenue">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Pending Payments</h6>
                                </div>
                                <span class="metric-icon">💳</span>
                            </div>
                            <div class="metric-value">$<?php echo number_format($metrics['my_balance_due'] ?? 0, 2); ?></div>
                            <div class="metric-change"><?php echo $metrics['my_pending_invoices'] ?? 0; ?> invoices</div>
                            <a href="my_invoices.php" class="metric-link">
                                View invoices <i class="ri-bill-line"></i>
                            </a>
                        </div>
                        
                        <?php if (isset($metrics['assigned_caregiver'])): ?>
                        <div class="metric-card caregivers">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">My Caregiver</h6>
                                </div>
                                <span class="metric-icon">👨‍⚕️</span>
                            </div>
                            <div class="metric-value" style="font-size: 1.25rem;">
                                <?php echo htmlspecialchars($metrics['assigned_caregiver']['full_name']); ?>
                            </div>
                            <div class="metric-change">Assigned care provider</div>
                            <a href="caregiver_profile.php?id=<?php echo $metrics['assigned_caregiver']['caregiver_id']; ?>" class="metric-link">
                                View profile <i class="ri-user-line"></i>
                            </a>
                        </div>
                        <?php endif; ?>
                        <?php endif; ?>
                    </div>

                    <!-- Role-specific Quick Actions -->
                    <?php if ($user_category === 'ADMIN' || $role_code === 'SUPER_ADMIN'): ?>
                    <div class="row">
                        <div class="col-12">
                            <h5 class="mb-3" style="color: #2563eb; font-weight: 600;">Quick Actions</h5>
                        </div>
                    </div>
                    <div class="quick-actions">
                        <a href="create_schedule.php" class="quick-action">
                            <span class="quick-action-icon">📅</span>
                            <div class="quick-action-title">Create Schedule</div>
                            <p class="quick-action-desc">Assign caregiver shifts</p>
                        </a>
                        <a href="register_client.php" class="quick-action">
                            <span class="quick-action-icon">👤</span>
                            <div class="quick-action-title">Register Client</div>
                            <p class="quick-action-desc">New client onboarding</p>
                        </a>
                        <a href="register_caregiver.php" class="quick-action">
                            <span class="quick-action-icon">👨‍⚕️</span>
                            <div class="quick-action-title">Add Caregiver</div>
                            <p class="quick-action-desc">Caregiver enrollment</p>
                        </a>
                        <a href="create_invoice.php" class="quick-action">
                            <span class="quick-action-icon">📄</span>
                            <div class="quick-action-title">Create Invoice</div>
                            <p class="quick-action-desc">Generate billing</p>
                        </a>
                        <a href="create_care_plan.php" class="quick-action">
                            <span class="quick-action-icon">📋</span>
                            <div class="quick-action-title">New Care Plan</div>
                            <p class="quick-action-desc">Client care program</p>
                        </a>
                        <a href="reports.php" class="quick-action">
                            <span class="quick-action-icon">📊</span>
                            <div class="quick-action-title">Reports</div>
                            <p class="quick-action-desc">Analytics & insights</p>
                        </a>
                    </div>
                    
                    <?php elseif ($user_category === 'CAREGIVER'): ?>
                    <div class="row">
                        <div class="col-12">
                            <h5 class="mb-3" style="color: #10b981; font-weight: 600;">My Actions</h5>
                        </div>
                    </div>
                    <div class="quick-actions">
                        <a href="clock_in.php" class="quick-action">
                            <span class="quick-action-icon">⏰</span>
                            <div class="quick-action-title">Clock In/Out</div>
                            <p class="quick-action-desc">Record attendance</p>
                        </a>
                        <a href="my_schedule.php" class="quick-action">
                            <span class="quick-action-icon">📅</span>
                            <div class="quick-action-title">My Schedule</div>
                            <p class="quick-action-desc">View assignments</p>
                        </a>
                        <a href="complete_tasks.php" class="quick-action">
                            <span class="quick-action-icon">✅</span>
                            <div class="quick-action-title">Complete Tasks</div>
                            <p class="quick-action-desc">Care plan tasks</p>
                        </a>
                        <a href="my_clients.php" class="quick-action">
                            <span class="quick-action-icon">👥</span>
                            <div class="quick-action-title">My Clients</div>
                            <p class="quick-action-desc">Client information</p>
                        </a>
                    </div>
                    
                    <?php elseif ($user_category === 'CLIENT'): ?>
                    <div class="row">
                        <div class="col-12">
                            <h5 class="mb-3" style="color: #f59e0b; font-weight: 600;">My Portal</h5>
                        </div>
                    </div>
                    <div class="quick-actions">
                        <a href="my_schedule.php" class="quick-action">
                            <span class="quick-action-icon">📅</span>
                            <div class="quick-action-title">My Schedule</div>
                            <p class="quick-action-desc">Upcoming visits</p>
                        </a>
                        <a href="my_care_plan.php" class="quick-action">
                            <span class="quick-action-icon">📋</span>
                            <div class="quick-action-title">Care Plan</div>
                            <p class="quick-action-desc">View my care</p>
                        </a>
                        <a href="my_invoices.php" class="quick-action">
                            <span class="quick-action-icon">💳</span>
                            <div class="quick-action-title">Invoices</div>
                            <p class="quick-action-desc">Billing & payments</p>
                        </a>
                        <a href="contact_support.php" class="quick-action">
                            <span class="quick-action-icon">💬</span>
                            <div class="quick-action-title">Contact Support</div>
                            <p class="quick-action-desc">Get help</p>
                        </a>
                    </div>
                    <?php endif; ?>

                    <!-- Charts Section -->
                    <?php if ($user_category === 'ADMIN' || $role_code === 'SUPER_ADMIN'): ?>
                    <div class="row">
                        <div class="col-xl-8">
                            <div class="chart-card">
                                <div class="chart-header">
                                    <h3 class="chart-title">Revenue Trends (Last 30 Days)</h3>
                                </div>
                                <div class="chart-body">
                                    <div id="revenue-chart" style="height: 350px;"></div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-4">
                            <div class="chart-card">
                                <div class="chart-header">
                                    <h3 class="chart-title">Schedule Status</h3>
                                </div>
                                <div class="chart-body">
                                    <div id="schedule-chart" style="height: 350px;"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Activities -->
                    <?php if (!empty($recent_activities)): ?>
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Recent Activities</h3>
                        </div>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Type</th>
                                    <th>Reference</th>
                                    <th>Client/Caregiver</th>
                                    <th>Date & Time</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($recent_activities as $activity): ?>
                                <tr>
                                    <td>
                                        <span class="status-badge status-<?php echo $activity['type']; ?>">
                                            <?php echo ucfirst($activity['type']); ?>
                                        </span>
                                    </td>
                                    <td style="font-weight: 600;"><?php echo htmlspecialchars($activity['reference']); ?></td>
                                    <td>
                                        <div>
                                            <div style="font-weight: 600;">
                                                <?php echo htmlspecialchars($activity['client_name'] ?? $activity['caregiver_name'] ?? 'N/A'); ?>
                                            </div>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                <?php echo htmlspecialchars($activity['client_number'] ?? $activity['employee_number'] ?? ''); ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td style="color: #64748b;">
                                        <?php echo date('M j, Y g:i A', strtotime($activity['shift_date'] . ' ' . $activity['start_time'])); ?>
                                    </td>
                                    <td>
                                        <?php if (isset($activity['status'])): ?>
                                        <span class="status-badge status-<?php echo $activity['status']; ?>">
                                            <?php echo str_replace('_', ' ', $activity['status']); ?>
                                        </span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>

                    <!-- Expiring Certifications Alert -->
                    <?php if (!empty($expiring_certs_list)): ?>
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">
                                <i class="ri-alarm-warning-line text-warning"></i>
                                Expiring Certifications (Next 30 Days)
                            </h3>
                        </div>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Caregiver</th>
                                    <th>Certification</th>
                                    <th>Issue Date</th>
                                    <th>Expiry Date</th>
                                    <th>Days Remaining</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($expiring_certs_list as $cert): 
                                    $days_remaining = (strtotime($cert['expiry_date']) - time()) / (60 * 60 * 24);
                                    $urgency_class = $days_remaining <= 7 ? 'text-danger' : ($days_remaining <= 14 ? 'text-warning' : 'text-info');
                                ?>
                                <tr>
                                    <td>
                                        <div>
                                            <div style="font-weight: 600;"><?php echo htmlspecialchars($cert['full_name']); ?></div>
                                            <div style="color: #64748b; font-size: 0.75rem;"><?php echo htmlspecialchars($cert['employee_number']); ?></div>
                                        </div>
                                    </td>
                                    <td style="font-weight: 600;"><?php echo htmlspecialchars($cert['certification_name']); ?></td>
                                    <td><?php echo date('M j, Y', strtotime($cert['issue_date'])); ?></td>
                                    <td class="<?php echo $urgency_class; ?>"><?php echo date('M j, Y', strtotime($cert['expiry_date'])); ?></td>
                                    <td>
                                        <span class="badge bg-<?php echo $days_remaining <= 7 ? 'danger' : ($days_remaining <= 14 ? 'warning' : 'info'); ?>">
                                            <?php echo floor($days_remaining); ?> days
                                        </span>
                                    </td>
                                    <td>
                                        <a href="renew_certification.php?id=<?php echo $cert['caregiver_id']; ?>&cert=<?php echo $cert['certification_id']; ?>" 
                                           class="btn btn-sm btn-outline-primary">
                                            <i class="ri-refresh-line"></i> Renew
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                    <?php endif; ?>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.min.js"></script>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Update time and date
        function updateDateTime() {
            const now = new Date();
            
            const timeElement = document.getElementById('currentTime');
            const dateElement = document.getElementById('currentDate');
            
            if (timeElement) {
                timeElement.textContent = now.toLocaleTimeString('en-US', {
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: true
                });
            }
            
            if (dateElement) {
                dateElement.textContent = now.toLocaleDateString('en-US', {
                    weekday: 'long',
                    month: 'short',
                    day: 'numeric',
                    year: 'numeric'
                });
            }
        }
        
        setInterval(updateDateTime, 60000);
        updateDateTime();

        <?php if ($user_category === 'ADMIN' || $role_code === 'SUPER_ADMIN'): ?>
        // Revenue Chart
        const revenueData = <?php echo json_encode($revenue_data); ?>;
        const revenueDates = revenueData.map(item => item.date);
        const revenueAmounts = revenueData.map(item => parseFloat(item.revenue));
        const transactionCounts = revenueData.map(item => parseInt(item.transaction_count));

        const revenueOptions = {
            series: [{
                name: 'Revenue ($)',
                type: 'area',
                data: revenueAmounts
            }, {
                name: 'Transactions',
                type: 'line',
                data: transactionCounts
            }],
            chart: {
                height: 350,
                type: 'line',
                toolbar: { show: false },
                animations: { enabled: true }
            },
            stroke: {
                curve: 'smooth',
                width: [0, 3]
            },
            fill: {
                type: ['gradient', 'solid'],
                gradient: {
                    shadeIntensity: 1,
                    type: 'vertical',
                    colorStops: [
                        { offset: 0, color: '#2563eb', opacity: 0.8 },
                        { offset: 100, color: '#2563eb', opacity: 0.1 }
                    ]
                }
            },
            colors: ['#2563eb', '#10b981'],
            labels: revenueDates.map(date => new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })),
            markers: { size: 4 },
            xaxis: { 
                type: 'category',
                labels: {
                    style: {
                        fontSize: '12px'
                    }
                }
            },
            yaxis: [{
                title: { text: 'Revenue ($)', style: { color: '#2563eb' } },
                labels: {
                    formatter: function (val) {
                        return ' + val.toLocaleString();
                    }
                }
            }, {
                opposite: true,
                title: { text: 'Transactions', style: { color: '#10b981' } }
            }],
            tooltip: {
                shared: true,
                intersect: false,
                y: [{
                    formatter: function (y) {
                        return typeof y !== "undefined" ? "$" + y.toLocaleString() : y;
                    }
                }, {
                    formatter: function (y) {
                        return typeof y !== "undefined" ? y + " transactions" : y;
                    }
                }]
            },
            grid: {
                borderColor: '#e2e8f0',
                strokeDashArray: 3
            }
        };

        try {
            const revenueChart = new ApexCharts(document.querySelector("#revenue-chart"), revenueOptions);
            revenueChart.render();
        } catch(e) {
            console.error("Error rendering revenue chart:", e);
            if (document.querySelector("#revenue-chart")) {
                document.querySelector("#revenue-chart").innerHTML = '<div class="text-center p-4"><p style="color: #64748b;">Revenue data will appear here</p></div>';
            }
        }

        // Schedule Status Chart
        const scheduleData = <?php echo json_encode($schedule_status_data); ?>;
        const scheduleLabels = scheduleData.map(item => item.status.replace('_', ' ').toUpperCase());
        const scheduleCounts = scheduleData.map(item => parseInt(item.count));

        const scheduleOptions = {
            series: scheduleCounts,
            chart: {
                type: 'donut',
                height: 350,
                animations: { enabled: true }
            },
            labels: scheduleLabels,
            plotOptions: {
                pie: {
                    donut: { 
                        size: '65%',
                        labels: {
                            show: true,
                            total: {
                                show: true,
                                label: 'Total Schedules',
                                formatter: function (w) {
                                    return w.globals.seriesTotals.reduce((a, b) => a + b, 0);
                                }
                            }
                        }
                    }
                }
            },
            legend: { 
                position: 'bottom',
                fontSize: '12px'
            },
            colors: ['#3b82f6', '#10b981', '#f59e0b', '#8b5cf6', '#ef4444', '#ec4899'],
            tooltip: {
                y: {
                    formatter: function(value) {
                        return value + " schedules";
                    }
                }
            },
            dataLabels: {
                enabled: true,
                formatter: function (val, opts) {
                    return opts.w.config.series[opts.seriesIndex];
                }
            }
        };

        try {
            const scheduleChart = new ApexCharts(document.querySelector("#schedule-chart"), scheduleOptions);
            scheduleChart.render();
        } catch(e) {
            console.error("Error rendering schedule chart:", e);
            if (document.querySelector("#schedule-chart")) {
                document.querySelector("#schedule-chart").innerHTML = '<div class="text-center p-4"><p style="color: #64748b;">Schedule data will appear here</p></div>';
            }
        }
        <?php endif; ?>

        // Add hover effects to metric cards
        document.querySelectorAll('.metric-card').forEach(card => {
            card.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-4px)';
                this.style.boxShadow = '0 8px 15px rgba(0, 0, 0, 0.1)';
            });
            
            card.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0)';
                this.style.boxShadow = '0 1px 3px 0 rgba(0, 0, 0, 0.1)';
            });
        });

        // Add hover effects to quick actions
        document.querySelectorAll('.quick-action').forEach(action => {
            action.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-2px) scale(1.02)';
            });
            
            action.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0) scale(1)';
            });
        });
    });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>