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

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

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

$user_id = $_SESSION['user_id'];
$role_code = $_SESSION['role_code'];

// Verify Role Access
if ($role_code !== 'RESIDENT_DOCTOR') {
    // Determine redirect URL based on role if they accessed wrong dashboard
   $redirect_url = match($role_code) {
        'SUPER_ADMIN', 'HOSPITAL_ADMIN' => 'admin_dashboard.php',
        'ENT_CONSULTANT', 'ENT_DOCTOR' => 'doctor_dashboard.php',
        'HEAD_NURSE', 'ENT_NURSE' => 'nursing_dashboard.php',
        'AUDIOLOGIST' => 'audiologist_dashboard.php',
        'LAB_TECHNICIAN' => 'lab_dashboard.php',
        'RECEPTIONIST' => 'reception_dashboard.php',
        'BILLING_CLERK' => 'billing_dashboard.php',
        'MEDICAL_RECORDS' => 'records_dashboard.php',
        'PATIENT' => 'patient_portal.php',
        default => 'index.php'
    };
    header("Location: $redirect_url");
    exit();
}

// Fetch user details
$sql_user_details = "SELECT full_name, email, phone_primary FROM users WHERE user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$val = $stmt_user->get_result()->fetch_assoc();
$full_name = $val['full_name'];

$metrics = [];
$today = date('Y-m-d');
$current_month = date('Y-m');

// Get doctor ID (Residents are also doctors in the system usually)
$doctor_id_sql = "SELECT doctor_id FROM doctors WHERE user_id = ?";
$stmt = $conn->prepare($doctor_id_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$doctor_result = $stmt->get_result();

if ($doctor_result->num_rows > 0) {
    $doctor_data = $doctor_result->fetch_assoc();
    $doctor_id = $doctor_data['doctor_id'];

    // My appointments today
    $my_appointments_sql = "SELECT COUNT(*) as count FROM appointments 
                           WHERE doctor_id = ? AND appointment_date = ? 
                           AND status IN ('SCHEDULED', 'CONFIRMED', 'CHECKED_IN')";
    $stmt = $conn->prepare($my_appointments_sql);
    $stmt->bind_param("is", $doctor_id, $today);
    $stmt->execute();
    $metrics['my_appointments_today'] = $stmt->get_result()->fetch_assoc()['count'];

    // My completed consultations this month
    $my_consultations_sql = "SELECT COUNT(*) as count, COALESCE(SUM(consultation_fee), 0) as revenue 
                            FROM consultations 
                            WHERE doctor_id = ? AND DATE(started_at) LIKE ? AND status = 'COMPLETED'";
    $stmt = $conn->prepare($my_consultations_sql);
    $current_month_pattern = $current_month . '%';
    $stmt->bind_param("is", $doctor_id, $current_month_pattern);
    $stmt->execute();
    $consultation_data = $stmt->get_result()->fetch_assoc();
    $metrics['my_monthly_consultations'] = $consultation_data['count'];
    $metrics['my_monthly_revenue'] = $consultation_data['revenue'];

    // My pending lab results
    $my_pending_labs_sql = "SELECT COUNT(*) as count FROM lab_orders lo
                           JOIN consultations c ON lo.consultation_id = c.consultation_id
                           WHERE c.doctor_id = ? AND lo.status IN ('PENDING', 'IN_PROGRESS')";
    $stmt = $conn->prepare($my_pending_labs_sql);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $metrics['my_pending_labs'] = $stmt->get_result()->fetch_assoc()['count'];

    // My procedures today
    $my_procedures_sql = "SELECT COUNT(*) as count FROM patient_procedures 
                         WHERE performed_by = ? AND DATE(procedure_date) = ?";
    $stmt = $conn->prepare($my_procedures_sql);
    $stmt->bind_param("is", $doctor_id, $today);
    $stmt->execute();
    $metrics['my_procedures_today'] = $stmt->get_result()->fetch_assoc()['count'];
    
     // Recent consultations activity
    $recent_activities_sql = "SELECT c.consultation_number, p.patient_number, u.full_name as patient_name, c.started_at
                            FROM consultations c
                            JOIN patients p ON c.patient_id = p.patient_id
                            JOIN users u ON p.user_id = u.user_id
                            WHERE c.doctor_id = ? 
                            ORDER BY c.started_at DESC LIMIT 5";
    $stmt = $conn->prepare($recent_activities_sql);
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $recent_activities = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

?>
<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Resident Dashboard')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .welcome-header {
            background: linear-gradient(135deg, #20B2AA 0%, #008B8B 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        .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 {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        .metric-title { font-size: 0.875rem; font-weight: 600; color: #64748b; margin: 0; }
        .metric-icon { font-size: 1.5rem; float: right; }
        .metric-value { font-size: 2rem; font-weight: 700; color: #2d7a2d; margin-top: 0.5rem; }
        .metric-change { font-size: 0.875rem; color: #64748b; margin-top: 0.25rem; }
        .quick-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        .quick-action {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            text-align: center;
            border: 1px solid #e2e8f0;
            text-decoration: none;
            color: inherit;
            transition: all 0.2s;
        }
        .quick-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
            border-color: #2d7a2d;
        }
        .quick-action-icon { font-size: 2rem; margin-bottom: 0.5rem; display: block; }
        .quick-action-title { font-weight: 600; margin-bottom: 0.25rem; color: #334155; }
        .quick-action-desc { font-size: 0.875rem; color: #64748b; margin: 0; }
    </style>
</head>
<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <div class="welcome-header">
                        <h2>Dr. <?php echo htmlspecialchars($full_name); ?></h2>
                        <p>ENT Consultant Dashboard</p>
                    </div>

                    <!-- Metrics -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="metric-card">
                                <span class="metric-icon">👨‍⚕️</span>
                                <h6 class="metric-title">Appointments Today</h6>
                                <div class="metric-value"><?php echo number_format($metrics['my_appointments_today'] ?? 0); ?></div>
                                <div class="metric-change">Scheduled visits</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="metric-card">
                                <span class="metric-icon">📊</span>
                                <h6 class="metric-title">Consultations (Month)</h6>
                                <div class="metric-value"><?php echo number_format($metrics['my_monthly_consultations'] ?? 0); ?></div>
                                <div class="metric-change">Rev: KES <?php echo number_format($metrics['my_monthly_revenue'] ?? 0); ?></div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="metric-card">
                                <span class="metric-icon">📋</span>
                                <h6 class="metric-title">Pending Labs</h6>
                                <div class="metric-value"><?php echo number_format($metrics['my_pending_labs'] ?? 0); ?></div>
                                <div class="metric-change">Awaiting review</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="metric-card">
                                <span class="metric-icon">🔬</span>
                                <h6 class="metric-title">Procedures Today</h6>
                                <div class="metric-value"><?php echo number_format($metrics['my_procedures_today'] ?? 0); ?></div>
                                <div class="metric-change">Scheduled surgeries</div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                     <h5 class="mb-3">Quick Actions</h5>
                    <div class="quick-actions">
                        <a href="new_consultation.php" class="quick-action">
                            <span class="quick-action-icon">👨‍⚕️</span>
                            <div class="quick-action-title">New Consultation</div>
                            <p class="quick-action-desc">Start ENT consultation</p>
                        </a>
                        <a href="order_tests.php" class="quick-action">
                            <span class="quick-action-icon">🧪</span>
                            <div class="quick-action-title">Order Tests</div>
                            <p class="quick-action-desc">Audiometry, imaging, labs</p>
                        </a>
                        <a href="schedule_procedure.php" class="quick-action">
                            <span class="quick-action-icon">⚕️</span>
                            <div class="quick-action-title">Schedule Procedure</div>
                            <p class="quick-action-desc">ENT surgical procedures</p>
                        </a>
                        <a href="my_patients.php" class="quick-action">
                            <span class="quick-action-icon">📋</span>
                            <div class="quick-action-title">My Patients</div>
                            <p class="quick-action-desc">Patient medical records</p>
                        </a>
                    </div>
                    
                    <!-- Recent Activity -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Recent Consultations</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Date/Time</th>
                                                    <th>Consultation #</th>
                                                    <th>Patient</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (!empty($recent_activities)): ?>
                                                    <?php foreach ($recent_activities as $activity): ?>
                                                    <tr>
                                                        <td><?php echo date('M d, H:i', strtotime($activity['started_at'])); ?></td>
                                                        <td><?php echo htmlspecialchars($activity['consultation_number']); ?></td>
                                                        <td>
                                                            <?php echo htmlspecialchars($activity['patient_name']); ?>
                                                            <small class="text-muted d-block"><?php echo htmlspecialchars($activity['patient_number']); ?></small>
                                                        </td>
                                                        <td>
                                                            <a href="view_consultation.php?id=<?php echo $activity['consultation_number']; ?>" class="btn btn-sm btn-soft-primary">View</a>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <tr><td colspan="4" class="text-center">No recent consultations found.</td></tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
