<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
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 role information
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name, ur.role_code
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_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) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $role_code = $user_details['role_code'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
    $phone_number = $user_details['phone_primary'];
    $user_type = $user_details['user_type'];
    $role_id = $user_details['role_id'];
}

// Initialize dashboard data variables
$dashboard_data = [];

// Role-specific dashboard data
switch ($role_code) {
    case 'SUPER_ADMIN':
    case 'HOSPITAL_ADMIN':
        // Admin dashboard data
        $dashboard_data = getAdminDashboardData($conn);
        break;
        
    case 'ENT_CONSULTANT':
    case 'ENT_DOCTOR':
    case 'RESIDENT_DOCTOR':
        // Doctor dashboard data
        $dashboard_data = getDoctorDashboardData($conn, $user_id);
        break;
        
    case 'HEAD_NURSE':
    case 'ENT_NURSE':
        // Nurse dashboard data
        $dashboard_data = getNurseDashboardData($conn, $user_id);
        break;
        
    case 'AUDIOLOGIST':
        // Audiologist dashboard data
        $dashboard_data = getAudiologistDashboardData($conn, $user_id);
        break;
        
    case 'LAB_TECHNICIAN':
        // Lab technician dashboard data
        $dashboard_data = getLabTechnicianDashboardData($conn, $user_id);
        break;
        
    case 'RECEPTIONIST':
        // Receptionist dashboard data
        $dashboard_data = getReceptionistDashboardData($conn);
        break;
        
    case 'BILLING_CLERK':
        // Billing clerk dashboard data
        $dashboard_data = getBillingClerkDashboardData($conn);
        break;
        
    case 'MEDICAL_RECORDS':
        // Medical records dashboard data
        $dashboard_data = getMedicalRecordsDashboardData($conn);
        break;
        
    case 'PATIENT':
        // Patient dashboard data
        $dashboard_data = getPatientDashboardData($conn, $user_id);
        break;
        
    default:
        // Default dashboard data
        $dashboard_data = getDefaultDashboardData($conn);
        break;
}

// Functions to get role-specific dashboard data

function getAdminDashboardData($conn) {
    $data = [];
    
    // Total patients
    $sql = "SELECT COUNT(*) as total FROM patients WHERE is_active = 1";
    $data['total_patients'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Total appointments today
    $sql = "SELECT COUNT(*) as total FROM appointments WHERE DATE(appointment_date) = CURDATE()";
    $data['today_appointments'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Active doctors
    $sql = "SELECT COUNT(*) as total FROM doctors d INNER JOIN users u ON d.user_id = u.user_id WHERE u.status = 'ACTIVE'";
    $data['active_doctors'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Today's revenue
    $sql = "SELECT COALESCE(SUM(amount), 0) as total FROM payments WHERE DATE(payment_date) = CURDATE() AND status = 'COMPLETED'";
    $data['today_revenue'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Pending appointments
    $sql = "SELECT COUNT(*) as total FROM appointments WHERE status IN ('SCHEDULED', 'CONFIRMED') AND appointment_date >= CURDATE()";
    $data['pending_appointments'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Total staff
    $sql = "SELECT COUNT(*) as total FROM users WHERE user_type = 'STAFF' AND status = 'ACTIVE'";
    $data['total_staff'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Recent appointments
    $sql = "SELECT a.*, p.patient_number, CONCAT(u.full_name) as patient_name, CONCAT(d.full_name) as doctor_name
            FROM appointments a
            INNER JOIN patients p ON a.patient_id = p.patient_id
            INNER JOIN users u ON p.user_id = u.user_id
            INNER JOIN doctors doc ON a.doctor_id = doc.doctor_id
            INNER JOIN users d ON doc.user_id = d.user_id
            ORDER BY a.created_at DESC LIMIT 10";
    $data['recent_appointments'] = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);
    
    return $data;
}

function getDoctorDashboardData($conn, $user_id) {
    $data = [];
    
    // Get doctor_id
    $sql = "SELECT doctor_id FROM doctors WHERE user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $doctor_id = $stmt->get_result()->fetch_assoc()['doctor_id'];
    
    // Today's appointments
    $sql = "SELECT COUNT(*) as total FROM appointments 
            WHERE doctor_id = ? AND DATE(appointment_date) = CURDATE()";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $data['today_appointments'] = $stmt->get_result()->fetch_assoc()['total'];
    
    // Pending appointments
    $sql = "SELECT COUNT(*) as total FROM appointments 
            WHERE doctor_id = ? AND status IN ('SCHEDULED', 'CONFIRMED') AND appointment_date >= CURDATE()";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $data['pending_appointments'] = $stmt->get_result()->fetch_assoc()['total'];
    
    // Total patients treated
    $sql = "SELECT COUNT(DISTINCT patient_id) as total FROM consultations WHERE doctor_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $data['total_patients'] = $stmt->get_result()->fetch_assoc()['total'];
    
    // This month's consultations
    $sql = "SELECT COUNT(*) as total FROM consultations 
            WHERE doctor_id = ? AND MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $data['month_consultations'] = $stmt->get_result()->fetch_assoc()['total'];
    
    // Today's appointments list
    $sql = "SELECT a.*, p.patient_number, CONCAT(u.full_name) as patient_name, u.phone_primary
            FROM appointments a
            INNER JOIN patients p ON a.patient_id = p.patient_id
            INNER JOIN users u ON p.user_id = u.user_id
            WHERE a.doctor_id = ? AND DATE(a.appointment_date) = CURDATE()
            ORDER BY a.appointment_time ASC";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $data['today_schedule'] = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    return $data;
}

function getNurseDashboardData($conn, $user_id) {
    $data = [];
    
    // Today's appointments
    $sql = "SELECT COUNT(*) as total FROM appointments WHERE DATE(appointment_date) = CURDATE()";
    $data['today_appointments'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Patients in ward (if applicable)
    $sql = "SELECT COUNT(*) as total FROM patient_visits WHERE status IN ('REGISTERED', 'IN_CONSULTATION')";
    $data['active_patients'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Pending procedures
    $sql = "SELECT COUNT(*) as total FROM patient_procedures WHERE status IN ('SCHEDULED', 'PREPARING')";
    $data['pending_procedures'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Today's procedures
    $sql = "SELECT COUNT(*) as total FROM patient_procedures WHERE DATE(procedure_date) = CURDATE()";
    $data['today_procedures'] = $conn->query($sql)->fetch_assoc()['total'];
    
    return $data;
}

function getAudiologistDashboardData($conn, $user_id) {
    $data = [];
    
    // Get tech_id
    $sql = "SELECT tech_id FROM lab_technicians WHERE user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    $tech_id = $result ? $result['tech_id'] : null;
    
    // Pending tests
    $sql = "SELECT COUNT(*) as total FROM lab_order_tests 
            WHERE status IN ('PENDING', 'SCHEDULED')";
    $data['pending_tests'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Today's tests
    if ($tech_id) {
        $sql = "SELECT COUNT(*) as total FROM lab_order_tests 
                WHERE tested_by = ? AND DATE(completed_at) = CURDATE()";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $tech_id);
        $stmt->execute();
        $data['today_tests'] = $stmt->get_result()->fetch_assoc()['total'];
    } else {
        $data['today_tests'] = 0;
    }
    
    // Total tests completed
    if ($tech_id) {
        $sql = "SELECT COUNT(*) as total FROM lab_order_tests WHERE tested_by = ? AND status = 'COMPLETED'";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $tech_id);
        $stmt->execute();
        $data['total_tests'] = $stmt->get_result()->fetch_assoc()['total'];
    } else {
        $data['total_tests'] = 0;
    }
    
    return $data;
}

function getLabTechnicianDashboardData($conn, $user_id) {
    return getAudiologistDashboardData($conn, $user_id);
}

function getReceptionistDashboardData($conn) {
    $data = [];
    
    // Today's registrations
    $sql = "SELECT COUNT(*) as total FROM patient_visits WHERE DATE(registration_date) = CURDATE()";
    $data['today_registrations'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Today's appointments
    $sql = "SELECT COUNT(*) as total FROM appointments WHERE DATE(appointment_date) = CURDATE()";
    $data['today_appointments'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Waiting patients
    $sql = "SELECT COUNT(*) as total FROM patient_visits WHERE status = 'WAITING'";
    $data['waiting_patients'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Checked-in patients
    $sql = "SELECT COUNT(*) as total FROM appointments WHERE status = 'CHECKED_IN' AND DATE(appointment_date) = CURDATE()";
    $data['checked_in'] = $conn->query($sql)->fetch_assoc()['total'];
    
    return $data;
}

function getBillingClerkDashboardData($conn) {
    $data = [];
    
    // Today's revenue
    $sql = "SELECT COALESCE(SUM(amount), 0) as total FROM payments WHERE DATE(payment_date) = CURDATE() AND status = 'COMPLETED'";
    $data['today_revenue'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Pending invoices
    $sql = "SELECT COUNT(*) as total FROM invoices WHERE status IN ('SENT', 'PARTIAL_PAYMENT', 'OVERDUE')";
    $data['pending_invoices'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Outstanding balance
    $sql = "SELECT COALESCE(SUM(balance), 0) as total FROM invoices WHERE status != 'PAID'";
    $data['outstanding_balance'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Today's payments
    $sql = "SELECT COUNT(*) as total FROM payments WHERE DATE(payment_date) = CURDATE()";
    $data['today_payments'] = $conn->query($sql)->fetch_assoc()['total'];
    
    return $data;
}

function getMedicalRecordsDashboardData($conn) {
    $data = [];
    
    // Total documents
    $sql = "SELECT COUNT(*) as total FROM medical_documents";
    $data['total_documents'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Documents shared today
    $sql = "SELECT COUNT(*) as total FROM document_shares WHERE DATE(created_at) = CURDATE()";
    $data['today_shares'] = $conn->query($sql)->fetch_assoc()['total'];
    
    // Active shares
    $sql = "SELECT COUNT(*) as total FROM document_shares WHERE is_active = 1";
    $data['active_shares'] = $conn->query($sql)->fetch_assoc()['total'];
    
    return $data;
}

function getPatientDashboardData($conn, $user_id) {
    $data = [];
    
    // Get patient_id
    $sql = "SELECT patient_id FROM patients WHERE user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $patient_id = $stmt->get_result()->fetch_assoc()['patient_id'];
    
    // Upcoming appointments
    $sql = "SELECT COUNT(*) as total FROM appointments 
            WHERE patient_id = ? AND appointment_date >= CURDATE() AND status IN ('SCHEDULED', 'CONFIRMED')";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $data['upcoming_appointments'] = $stmt->get_result()->fetch_assoc()['total'];
    
    // Total visits
    $sql = "SELECT COUNT(*) as total FROM patient_visits WHERE patient_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $data['total_visits'] = $stmt->get_result()->fetch_assoc()['total'];
    
    // Pending invoices
    $sql = "SELECT COUNT(*) as total FROM invoices WHERE patient_id = ? AND status != 'PAID'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $data['pending_invoices'] = $stmt->get_result()->fetch_assoc()['total'];
    
    // Outstanding balance
    $sql = "SELECT COALESCE(SUM(balance), 0) as total FROM invoices WHERE patient_id = ? AND status != 'PAID'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $data['outstanding_balance'] = $stmt->get_result()->fetch_assoc()['total'];
    
    return $data;
}

function getDefaultDashboardData($conn) {
    $data = [];
    $data['message'] = 'Welcome to ENT Hospital Management System';
    return $data;
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Dashboard - ' . $role_name)); ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.css">
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .welcome-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .welcome-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .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.1);
            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-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 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;
        }
        
        .metric-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .metric-icon {
            width: 48px;
            height: 48px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            margin-bottom: 1rem;
        }
        
        .metric-title {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 0.5rem;
        }
        
        .metric-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .metric-change {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
        }
        
        .quick-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 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: #059669;
            border-color: #059669;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .quick-action-icon {
            font-size: 2rem;
            margin-bottom: 0.5rem;
            color: #059669;
        }
        
        .quick-action-title {
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .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-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-completed { background: #dcfce7; color: #166534; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        .status-pending { background: #fef3c7; color: #92400e; }
        
        .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;
        }
        
        @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.5rem;
            }
        }
    </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 . ', ' . $full_name;
                                    ?>
                                </h2>
                                <p><?php echo $role_name; ?> Dashboard
                                    <?php if($phone_number): ?> | <?php echo $phone_number; ?><?php endif; ?>
                                </p>
                            </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>

                    <?php
                    // Display role-specific dashboard content
                    switch ($role_code) {
                        case 'SUPER_ADMIN':
                        case 'HOSPITAL_ADMIN':
                            include 'dashboard_templates/admin_dashboard.php';
                            break;
                            
                        case 'ENT_CONSULTANT':
                        case 'ENT_DOCTOR':
                        case 'RESIDENT_DOCTOR':
                            include 'dashboard_templates/doctor_dashboard.php';
                            break;
                            
                        case 'HEAD_NURSE':
                        case 'ENT_NURSE':
                            include 'dashboard_templates/nurse_dashboard.php';
                            break;
                            
                        case 'AUDIOLOGIST':
                        case 'LAB_TECHNICIAN':
                            include 'dashboard_templates/technician_dashboard.php';
                            break;
                            
                        case 'RECEPTIONIST':
                            include 'dashboard_templates/receptionist_dashboard.php';
                            break;
                            
                        case 'BILLING_CLERK':
                            include 'dashboard_templates/billing_dashboard.php';
                            break;
                            
                        case 'MEDICAL_RECORDS':
                            include 'dashboard_templates/medical_records_dashboard.php';
                            break;
                            
                        case 'PATIENT':
                            include 'dashboard_templates/patient_dashboard.php';
                            break;
                            
                        default:
                            include 'dashboard_templates/default_dashboard.php';
                            break;
                    }
                    ?>
                </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>
    document.addEventListener('DOMContentLoaded', function() {
        // Update time and date
        function updateDateTime() {
            const now = new Date();
            
            document.getElementById('currentTime').textContent = now.toLocaleTimeString('en-US', {
                hour: '2-digit',
                minute: '2-digit',
                hour12: true
            });
            
            document.getElementById('currentDate').textContent = now.toLocaleDateString('en-US', {
                weekday: 'long',
                month: 'short',
                day: 'numeric',
                year: 'numeric'
            });
        }
        
        // Update every minute
        setInterval(updateDateTime, 60000);
        updateDateTime();
    });
    </script>

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