<?php
session_start();
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 proper schema alignment
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name, b.branch_name, b.branch_code 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     LEFT JOIN branches b ON u.branch_id = b.branch_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'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
    $branch_name = $user_details['branch_name'];
    $staff_number = $user_details['staff_number'];
}

// Get total active patients
$sql_patients = "SELECT COUNT(*) as total_patients FROM patients WHERE is_active = 1";
$result_patients = $conn->query($sql_patients);
$total_patients = $result_patients->fetch_assoc()['total_patients'];

// Get today's visits
$sql_visits_today = "SELECT COUNT(*) as visits_today FROM patient_visits 
                     WHERE DATE(registration_date) = CURDATE()";
$result_visits_today = $conn->query($sql_visits_today);
$visits_today = $result_visits_today->fetch_assoc()['visits_today'];

// Get active consultations
$sql_active_consultations = "SELECT COUNT(*) as active_consultations FROM consultations 
                             WHERE status = 'IN_PROGRESS'";
$result_active_consultations = $conn->query($sql_active_consultations);
$active_consultations = $result_active_consultations->fetch_assoc()['active_consultations'];

// Get pending lab orders
$sql_pending_labs = "SELECT COUNT(*) as pending_labs FROM lab_orders 
                     WHERE status IN ('PENDING', 'SAMPLE_COLLECTED', 'IN_PROGRESS')";
$result_pending_labs = $conn->query($sql_pending_labs);
$pending_labs = $result_pending_labs->fetch_assoc()['pending_labs'];

// Get today's revenue
$sql_today_revenue = "SELECT COALESCE(SUM(amount), 0) as today_revenue 
                      FROM payments 
                      WHERE DATE(payment_date) = CURDATE() AND status = 'COMPLETED'";
$result_today_revenue = $conn->query($sql_today_revenue);
$today_revenue = $result_today_revenue->fetch_assoc()['today_revenue'];

// Get monthly revenue
$sql_monthly_revenue = "SELECT COALESCE(SUM(amount), 0) as monthly_revenue 
                        FROM payments 
                        WHERE MONTH(payment_date) = MONTH(CURRENT_DATE()) 
                        AND YEAR(payment_date) = YEAR(CURRENT_DATE()) 
                        AND status = 'COMPLETED'";
$result_monthly_revenue = $conn->query($sql_monthly_revenue);
$monthly_revenue = $result_monthly_revenue->fetch_assoc()['monthly_revenue'];

// Get outstanding balances
$sql_outstanding = "SELECT COALESCE(SUM(balance), 0) as outstanding_balance 
                    FROM patient_visits WHERE balance > 0";
$result_outstanding = $conn->query($sql_outstanding);
$outstanding_balance = $result_outstanding->fetch_assoc()['outstanding_balance'];

// Get current facility credit score
$sql_credit_score = "SELECT credit_score, max_loan_eligible, risk_category 
                     FROM facility_credit_scores 
                     WHERE facility_id = 1 
                     ORDER BY score_date DESC LIMIT 1";
$result_credit_score = $conn->query($sql_credit_score);
$credit_data = $result_credit_score->fetch_assoc();
$credit_score = $credit_data['credit_score'] ?? 0;
$max_loan_eligible = $credit_data['max_loan_eligible'] ?? 0;
$risk_category = $credit_data['risk_category'] ?? 'MEDIUM';

// Get daily revenue trends for the last 7 days
$sql_daily_revenue = "SELECT 
    DATE(payment_date) as revenue_date,
    SUM(amount) as daily_revenue,
    COUNT(DISTINCT visit_id) as visit_count,
    COUNT(DISTINCT patient_id) as patient_count
FROM payments 
WHERE payment_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) 
AND status = 'COMPLETED'
GROUP BY DATE(payment_date)
ORDER BY revenue_date";
$result_daily_revenue = $conn->query($sql_daily_revenue);
$daily_revenue_data = [];
while ($row = $result_daily_revenue->fetch_assoc()) {
    $daily_revenue_data[] = $row;
}

// Get service utilization (consultations, procedures, lab tests)
$sql_service_utilization = "SELECT 
    'Consultations' as service_type,
    COUNT(*) as count,
    COALESCE(SUM(consultation_fee), 0) as revenue
FROM consultations 
WHERE DATE(started_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
UNION ALL
SELECT 
    'Procedures' as service_type,
    COUNT(*) as count,
    COALESCE(SUM(cost), 0) as revenue
FROM patient_procedures 
WHERE DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
UNION ALL
SELECT 
    'Lab Tests' as service_type,
    COUNT(*) as count,
    COALESCE(SUM(total_cost), 0) as revenue
FROM lab_orders 
WHERE DATE(ordered_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
$result_service_utilization = $conn->query($sql_service_utilization);
$service_utilization_data = [];
while ($row = $result_service_utilization->fetch_assoc()) {
    $service_utilization_data[] = $row;
}

// Get recent patient visits
$sql_recent_visits = "SELECT 
    pv.visit_number,
    pv.registration_date,
    pv.visit_type,
    pv.payment_mode,
    pv.total_amount,
    pv.status,
    p.first_name,
    p.last_name,
    p.patient_number,
    u.full_name as registered_by
FROM patient_visits pv
LEFT JOIN patients p ON pv.patient_id = p.patient_id
LEFT JOIN users u ON pv.registered_by = u.user_id
ORDER BY pv.registration_date DESC
LIMIT 5";
$result_recent_visits = $conn->query($sql_recent_visits);

// Get doctor performance for current month
$sql_doctor_performance = "SELECT 
    d.doctor_id,
    u.full_name as doctor_name,
    d.specialization,
    d.consultation_fee,
    d.commission_rate,
    COUNT(c.consultation_id) as consultations_count,
    COALESCE(SUM(c.consultation_fee), 0) as consultation_revenue,
    COALESCE(SUM(c.doctor_commission), 0) as total_commission,
    COUNT(DISTINCT c.patient_id) as unique_patients
FROM doctors d
LEFT JOIN users u ON d.user_id = u.user_id
LEFT JOIN consultations c ON d.doctor_id = c.doctor_id 
    AND MONTH(c.started_at) = MONTH(CURRENT_DATE())
    AND YEAR(c.started_at) = YEAR(CURRENT_DATE())
    AND c.status = 'COMPLETED'
WHERE d.is_active = 1
GROUP BY d.doctor_id, u.full_name, d.specialization, d.consultation_fee, d.commission_rate
ORDER BY consultation_revenue DESC
LIMIT 5";
$result_doctor_performance = $conn->query($sql_doctor_performance);

// Get payment method distribution for current month
$sql_payment_methods = "SELECT 
    payment_method,
    COUNT(*) as transaction_count,
    SUM(amount) as total_amount
FROM payments 
WHERE MONTH(payment_date) = MONTH(CURRENT_DATE()) 
AND YEAR(payment_date) = YEAR(CURRENT_DATE())
AND status = 'COMPLETED'
GROUP BY payment_method
ORDER BY total_amount DESC";
$result_payment_methods = $conn->query($sql_payment_methods);
$payment_methods_data = [];
while ($row = $result_payment_methods->fetch_assoc()) {
    $payment_methods_data[] = $row;
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Dashboard - Healthcare EMR System')); ?>
    <!-- apexcharts css -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.css">
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        /* Professional Dashboard Styling - Cleaner Design */
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Welcome Header - Simplified */
        .welcome-header {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 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 Cards - Clean and Minimal */
        .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-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;
        }
        
        .metric-change.positive { color: #059669; }
        .metric-change.negative { color: #dc2626; }
        .metric-change.neutral { color: #64748b; }
        
        .metric-link {
            display: inline-block;
            margin-top: 0.5rem;
            color: #3b82f6;
            text-decoration: none;
            font-size: 0.875rem;
            font-weight: 500;
        }
        
        .metric-link:hover {
            color: #1d4ed8;
            text-decoration: underline;
        }
        
        /* Chart Cards */
        .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 #e2e8f0;
        }
        
        .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 - Clean Design */
        .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-primary { background: #dbeafe; color: #1d4ed8; }
        .status-success { background: #dcfce7; color: #166534; }
        .status-warning { background: #fef3c7; color: #92400e; }
        .status-danger { background: #fee2e2; color: #991b1b; }
        .status-info { background: #e0f2fe; color: #0369a1; }
        .status-secondary { background: #f1f5f9; color: #475569; }
        
        /* Quick Actions */
        .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: #3b82f6;
            border-color: #3b82f6;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .quick-action-title {
            font-weight: 600;
            font-size: 0.875rem;
            margin-top: 0.5rem;
        }
        
        /* Credit Score Section */
        .credit-display {
            text-align: center;
            padding: 2rem;
        }
        
        .credit-score-value {
            font-size: 3rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .credit-excellent { color: #059669; }
        .credit-good { color: #0891b2; }
        .credit-fair { color: #d97706; }
        .credit-poor { color: #dc2626; }
        
        .credit-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 1rem;
            margin-top: 1.5rem;
        }
        
        .credit-detail {
            text-align: center;
        }
        
        .credit-detail-value {
            font-weight: 700;
            font-size: 1.125rem;
            display: block;
        }
        
        .credit-detail-label {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        /* Financial Summary */
        .financial-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
        }
        
        .financial-item {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            text-align: center;
        }
        
        .financial-label {
            font-size: 0.875rem;
            color: #64748b;
            margin-bottom: 0.5rem;
        }
        
        .financial-value {
            font-size: 1.5rem;
            font-weight: 700;
        }
        
        /* 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.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>Healthcare EMR System Dashboard - <?php echo $role_name; ?>
                                    <?php if($branch_name): ?> | <?php echo $branch_name; ?><?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>

                    <!-- Key Metrics -->
                    <div class="metrics-row">
                        <div class="metric-card">
                            <div class="metric-title">Total Patients</div>
                            <div class="metric-value"><?php echo number_format($total_patients); ?></div>
                            <div class="metric-change neutral">Registered patients</div>
                            <a href="list_patients.php" class="metric-link">View All →</a>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-title">Today's Visits</div>
                            <div class="metric-value"><?php echo number_format($visits_today); ?></div>
                            <div class="metric-change neutral">Patient visits today</div>
                            <a href="todays_visits.php" class="metric-link">View Queue →</a>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-title">Active Consultations</div>
                            <div class="metric-value"><?php echo number_format($active_consultations); ?></div>
                            <div class="metric-change neutral">Currently in progress</div>
                            <a href="active_consultations.php" class="metric-link">View Active →</a>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-title">Pending Labs</div>
                            <div class="metric-value"><?php echo number_format($pending_labs); ?></div>
                            <div class="metric-change neutral">Awaiting results</div>
                            <a href="pending_lab_orders.php" class="metric-link">Lab Queue →</a>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-title">Today's Revenue</div>
                            <div class="metric-value">KES <?php echo number_format($today_revenue); ?></div>
                            <div class="metric-change positive">Daily collections</div>
                            <a href="daily_collections.php" class="metric-link">View Details →</a>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-title">Credit Score</div>
                            <div class="metric-value"><?php echo $credit_score; ?></div>
                            <div class="metric-change neutral"><?php echo $risk_category; ?> Risk</div>
                            <a href="facility_credit_score.php" class="metric-link">View Report →</a>
                        </div>
                    </div>

                    <!-- Charts Section -->
                    <div class="row">
                        <div class="col-xl-8">
                            <div class="chart-card">
                                <div class="chart-header">
                                    <h3 class="chart-title">Revenue Trends (Last 7 Days)</h3>
                                </div>
                                <div class="chart-body">
                                    <div id="revenue-trends" style="height: 350px;"></div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-4">
                            <div class="chart-card">
                                <div class="chart-header">
                                    <h3 class="chart-title">Service Distribution</h3>
                                </div>
                                <div class="chart-body">
                                    <div id="service-utilization" style="height: 350px;"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="quick-actions">
                        <a href="register_patient.php" class="quick-action">
                            <div class="quick-action-title">Register Patient</div>
                        </a>
                        <a href="register_visit.php" class="quick-action">
                            <div class="quick-action-title">New Visit</div>
                        </a>
                        <a href="active_consultations.php" class="quick-action">
                            <div class="quick-action-title">Consultations</div>
                        </a>
                        <a href="pending_lab_orders.php" class="quick-action">
                            <div class="quick-action-title">Lab Orders</div>
                        </a>
                        <a href="record_payment.php" class="quick-action">
                            <div class="quick-action-title">Record Payment</div>
                        </a>
                        <a href="daily_revenue.php" class="quick-action">
                            <div class="quick-action-title">Reports</div>
                        </a>
                    </div>

                    <!-- Data Tables -->
                    <div class="row">
                        <div class="col-xl-8">
                            <div class="table-card">
                                <div class="table-header">
                                    <h3 class="table-title">Recent Patient Visits</h3>
                                </div>
                                <table class="data-table">
                                    <thead>
                                        <tr>
                                            <th>Visit #</th>
                                            <th>Patient</th>
                                            <th>Type</th>
                                            <th>Status</th>
                                            <th>Amount</th>
                                            <th>Date</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while($row = $result_recent_visits->fetch_assoc()): ?>
                                        <tr>
                                            <td>
                                                <a href="view_visit.php?id=<?php echo $row['visit_number']; ?>" style="color: #3b82f6; text-decoration: none; font-weight: 600;">
                                                    <?php echo $row['visit_number']; ?>
                                                </a>
                                            </td>
                                            <td>
                                                <div style="font-weight: 600;"><?php echo $row['first_name'] . ' ' . $row['last_name']; ?></div>
                                                <div style="color: #64748b; font-size: 0.75rem;"><?php echo $row['patient_number']; ?></div>
                                            </td>
                                            <td>
                                                <?php 
                                                $type_class = match($row['visit_type']) {
                                                    'CONSULTATION' => 'status-primary',
                                                    'FOLLOW_UP' => 'status-info',
                                                    'EMERGENCY' => 'status-danger',
                                                    'PROCEDURE' => 'status-warning',
                                                    'LAB_ONLY' => 'status-secondary',
                                                    default => 'status-secondary'
                                                };
                                                ?>
                                                <span class="status-badge <?php echo $type_class; ?>">
                                                    <?php echo ucfirst(strtolower(str_replace('_', ' ', $row['visit_type']))); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php 
                                                $status_class = match($row['status']) {
                                                    'REGISTERED' => 'status-primary',
                                                    'IN_CONSULTATION' => 'status-warning',
                                                    'COMPLETED' => 'status-success',
                                                    'CANCELLED' => 'status-danger',
                                                    default => 'status-secondary'
                                                };
                                                ?>
                                                <span class="status-badge <?php echo $status_class; ?>">
                                                    <?php echo ucfirst(strtolower(str_replace('_', ' ', $row['status']))); ?>
                                                </span>
                                            </td>
                                            <td style="font-weight: 600;">KES <?php echo number_format($row['total_amount'], 2); ?></td>
                                            <td style="color: #64748b;"><?php echo date('M j, g:i A', strtotime($row['registration_date'])); ?></td>
                                        </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <div class="col-xl-4">
                            <div class="chart-card">
                                <div class="chart-header">
                                    <h3 class="chart-title">Credit Score & Loan Eligibility</h3>
                                </div>
                                <div class="chart-body">
                                    <div class="credit-display">
                                        <div class="credit-score-value credit-<?php echo $credit_score >= 700 ? 'excellent' : ($credit_score >= 600 ? 'good' : ($credit_score >= 500 ? 'fair' : 'poor')); ?>">
                                            <?php echo $credit_score; ?>
                                        </div>
                                        <div style="color: #64748b; margin-bottom: 1rem;"><?php echo $risk_category; ?> Risk Rating</div>
                                        <div class="credit-details">
                                            <div class="credit-detail">
                                                <span class="credit-detail-value">KES <?php echo number_format($max_loan_eligible); ?></span>
                                                <span class="credit-detail-label">Max Loan</span>
                                            </div>
                                            <div class="credit-detail">
                                                <span class="credit-detail-value"><?php echo $risk_category; ?></span>
                                                <span class="credit-detail-label">Risk Level</span>
                                            </div>
                                        </div>
                                        <div style="margin-top: 1.5rem;">
                                            <a href="apply_facility_loan.php" style="background: #3b82f6; color: white; padding: 0.75rem 1.5rem; border-radius: 8px; text-decoration: none; font-weight: 600;">
                                                Apply for Loan
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Financial Summary -->
                    <div class="chart-card">
                        <div class="chart-header">
                            <h3 class="chart-title">Financial Summary</h3>
                        </div>
                        <div class="chart-body">
                            <div class="financial-grid">
                                <div class="financial-item">
                                    <div class="financial-label">Monthly Revenue</div>
                                    <div class="financial-value" style="color: #059669;">KES <?php echo number_format($monthly_revenue); ?></div>
                                </div>
                                <div class="financial-item">
                                    <div class="financial-label">Outstanding Balance</div>
                                    <div class="financial-value" style="color: #dc2626;">KES <?php echo number_format($outstanding_balance); ?></div>
                                </div>
                                <div class="financial-item">
                                    <div class="financial-label">Today's Collection</div>
                                    <div class="financial-value" style="color: #3b82f6;">KES <?php echo number_format($today_revenue); ?></div>
                                </div>
                                <div class="financial-item">
                                    <div class="financial-label">Collection Rate</div>
                                    <?php 
                                    $collection_rate = $monthly_revenue > 0 ? 
                                        round((($monthly_revenue - $outstanding_balance) / $monthly_revenue) * 100, 1) : 0;
                                    ?>
                                    <div class="financial-value" style="color: #059669;"><?php echo $collection_rate; ?>%</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Doctor Performance -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Doctor Performance (Current Month)</h3>
                        </div>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Doctor</th>
                                    <th>Specialization</th>
                                    <th>Consultations</th>
                                    <th>Revenue</th>
                                    <th>Commission</th>
                                    <th>Patients</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while($row = $result_doctor_performance->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div style="font-weight: 600;">Dr. <?php echo $row['doctor_name']; ?></div>
                                        <div style="color: #64748b; font-size: 0.75rem;">Fee: KES <?php echo number_format($row['consultation_fee']); ?></div>
                                    </td>
                                    <td>
                                        <span class="status-badge status-info">
                                            <?php echo $row['specialization'] ?: 'General Practice'; ?>
                                        </span>
                                    </td>
                                    <td style="font-weight: 600;"><?php echo number_format($row['consultations_count']); ?></td>
                                    <td style="font-weight: 600; color: #059669;">KES <?php echo number_format($row['consultation_revenue']); ?></td>
                                    <td style="font-weight: 600; color: #d97706;">
                                        KES <?php echo number_format($row['total_commission']); ?>
                                        <div style="color: #64748b; font-size: 0.75rem;"><?php echo $row['commission_rate']; ?>% rate</div>
                                    </td>
                                    <td style="font-weight: 600;"><?php echo $row['unique_patients']; ?></td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </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();
        
        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();

    // Revenue Trends Chart
    var revenueOptions = {
        series: [{
            name: 'Daily Revenue (KES)',
            type: 'area',
            data: <?php echo json_encode(array_column($daily_revenue_data, 'daily_revenue')); ?>
        }, {
            name: 'Patient Count',
            type: 'line',
            data: <?php echo json_encode(array_column($daily_revenue_data, 'patient_count')); ?>
        }],
        chart: {
            height: 350,
            type: 'line',
            toolbar: { show: false },
            animations: { enabled: false }
        },
        stroke: {
            curve: 'smooth',
            width: [0, 3]
        },
        fill: {
            type: ['gradient', 'solid'],
            gradient: {
                shadeIntensity: 1,
                type: 'vertical',
                colorStops: [
                    { offset: 0, color: '#3b82f6', opacity: 0.7 },
                    { offset: 100, color: '#3b82f6', opacity: 0.1 }
                ]
            }
        },
        colors: ['#3b82f6', '#059669'],
        labels: <?php echo json_encode(array_map(function($item) { 
            return date('M j', strtotime($item['revenue_date'])); 
        }, $daily_revenue_data)); ?>,
        markers: { size: 4 },
        xaxis: { type: 'category' },
        yaxis: [{
            title: { text: 'Revenue (KES)' },
        }, {
            opposite: true,
            title: { text: 'Patient Count' }
        }],
        tooltip: {
            shared: true,
            intersect: false,
            y: [{
                formatter: function (y) {
                    return typeof y !== "undefined" ? "KES " + y.toFixed(2) : y;
                }
            }, {
                formatter: function (y) {
                    return typeof y !== "undefined" ? y.toFixed(0) + " patients" : y;
                }
            }]
        },
        grid: {
            borderColor: '#e2e8f0',
            strokeDashArray: 3
        }
    };

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

    // Service Utilization Chart
    var serviceOptions = {
        series: <?php echo json_encode(array_column($service_utilization_data, 'count')); ?>,
        chart: {
            type: 'donut',
            height: 350,
            animations: { enabled: false }
        },
        labels: <?php echo json_encode(array_column($service_utilization_data, 'service_type')); ?>,
        plotOptions: {
            pie: {
                donut: { size: '70%' }
            }
        },
        legend: { position: 'bottom' },
        colors: ['#3b82f6', '#059669', '#d97706'],
        tooltip: {
            y: {
                formatter: function(value) {
                    return value + " services";
                }
            }
        }
    };

    try {
        var serviceChart = new ApexCharts(document.querySelector("#service-utilization"), serviceOptions);
        serviceChart.render();
    } catch(e) {
        console.error("Error rendering service chart:", e);
        document.querySelector("#service-utilization").innerHTML = '<div class="text-center p-4"><p style="color: #64748b;">Unable to load chart data</p></div>';
    }
});
</script>

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