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

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

// Fetch all doctors with their user information
$sql_doctors = "SELECT 
    d.*,
    u.full_name,
    u.email,
    u.phone_primary,
    u.staff_number,
    u.status,
    u.hire_date,
    u.last_login,
    b.branch_name,
    (SELECT COUNT(*) FROM appointments WHERE doctor_id = d.doctor_id AND status IN ('SCHEDULED', 'CONFIRMED')) as pending_appointments,
    (SELECT COUNT(*) FROM consultations WHERE doctor_id = d.doctor_id AND status = 'COMPLETED' AND DATE(completed_at) = CURDATE()) as today_consultations
FROM doctors d
INNER JOIN users u ON d.user_id = u.user_id
LEFT JOIN hospital_branches b ON u.branch_id = b.branch_id
WHERE u.user_type = 'STAFF'
ORDER BY d.is_consultant DESC, u.full_name ASC";

$result_doctors = $conn->query($sql_doctors);

// Get statistics
$sql_stats = "SELECT 
    COUNT(*) as total_doctors,
    SUM(CASE WHEN d.is_consultant = 1 THEN 1 ELSE 0 END) as consultants,
    SUM(CASE WHEN d.is_surgeon = 1 THEN 1 ELSE 0 END) as surgeons,
    SUM(CASE WHEN u.status = 'ACTIVE' THEN 1 ELSE 0 END) as active_doctors,
    SUM(CASE WHEN u.last_login >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 ELSE 0 END) as recent_logins
FROM doctors d
INNER JOIN users u ON d.user_id = u.user_id";
$result_stats = $conn->query($sql_stats);
$stats = $result_stats->fetch_assoc();
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'ENT Doctors Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- DataTables CSS -->
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="assets/libs/datatables.net-responsive-bs5/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .doctor-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--vz-primary);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .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-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-suspended { background: #fecaca; color: #b91c1c; }
        
        .stats-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;
        }
        
        .stats-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .stats-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .action-buttons .btn {
            padding: 0.375rem 0.75rem;
            margin: 0.125rem;
        }

        .badge-consultant {
            background: #fef3c7;
            color: #92400e;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .badge-surgeon {
            background: #dbeafe;
            color: #1e40af;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 600;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">ENT Doctors Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="#">Medical Staff</a></li>
                                        <li class="breadcrumb-item active">ENT Doctors</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card text-center">
                                <div class="stats-value text-primary"><?php echo number_format($stats['total_doctors']); ?></div>
                                <div class="stats-label">Total Doctors</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card text-center">
                                <div class="stats-value text-success"><?php echo number_format($stats['active_doctors']); ?></div>
                                <div class="stats-label">Active Doctors</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card text-center">
                                <div class="stats-value text-warning"><?php echo number_format($stats['consultants']); ?></div>
                                <div class="stats-label">Consultants</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card text-center">
                                <div class="stats-value text-info"><?php echo number_format($stats['surgeons']); ?></div>
                                <div class="stats-label">Surgeons</div>
                            </div>
                        </div>
                    </div>

                    <!-- Doctors Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-stethoscope-line align-middle me-2"></i>ENT Doctors
                                    </h5>
                                    <div class="d-flex gap-2">
                                        <a href="add_doctor.php" class="btn btn-primary">
                                            <i class="ri-user-add-line align-middle me-1"></i> Add Doctor
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="doctorsTable" class="table table-striped table-hover align-middle">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Doctor</th>
                                                    <th>License</th>
                                                    <th>Specialization</th>
                                                    <th>Contact</th>
                                                    <th>Fees</th>
                                                    <th>Branch</th>
                                                    <th>Status</th>
                                                    <th>Last Login</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while($doctor = $result_doctors->fetch_assoc()): ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="doctor-avatar me-3">
                                                                <?php echo strtoupper(substr($doctor['full_name'], 0, 2)); ?>
                                                            </div>
                                                            <div>
                                                                <div class="fw-bold">Dr. <?php echo htmlspecialchars($doctor['full_name']); ?></div>
                                                                <div class="text-muted small">
                                                                    ID: <?php echo $doctor['staff_number']; ?>
                                                                </div>
                                                                <div>
                                                                    <?php if($doctor['is_consultant']): ?>
                                                                        <span class="badge-consultant">Consultant</span>
                                                                    <?php endif; ?>
                                                                    <?php if($doctor['is_surgeon']): ?>
                                                                        <span class="badge-surgeon">Surgeon</span>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="fw-semibold"><?php echo htmlspecialchars($doctor['medical_license']); ?></span>
                                                        <div class="text-muted small">
                                                            <?php echo $doctor['experience_years']; ?> years exp.
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="fw-semibold"><?php echo htmlspecialchars($doctor['specialization']); ?></div>
                                                        <?php if($doctor['sub_specialization']): ?>
                                                        <div class="text-muted small"><?php echo htmlspecialchars($doctor['sub_specialization']); ?></div>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <i class="ri-mail-line me-1"></i>
                                                            <small><?php echo htmlspecialchars($doctor['email']); ?></small>
                                                        </div>
                                                        <div class="text-muted">
                                                            <i class="ri-phone-line me-1"></i>
                                                            <small><?php echo htmlspecialchars($doctor['phone_primary']); ?></small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="fw-semibold">KES <?php echo number_format($doctor['consultation_fee']); ?></div>
                                                        <div class="text-muted small">Follow-up: KES <?php echo number_format($doctor['follow_up_fee']); ?></div>
                                                    </td>
                                                    <td>
                                                        <?php echo htmlspecialchars($doctor['branch_name'] ?: 'Not Assigned'); ?>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        $status_class = match($doctor['status']) {
                                                            'ACTIVE' => 'status-active',
                                                            'INACTIVE' => 'status-inactive',
                                                            'PENDING' => 'status-pending',
                                                            'SUSPENDED' => 'status-suspended',
                                                            default => 'status-inactive'
                                                        };
                                                        ?>
                                                        <span class="status-badge <?php echo $status_class; ?>">
                                                            <?php echo ucfirst(strtolower($doctor['status'])); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php if($doctor['last_login']): ?>
                                                            <span class="text-success small">
                                                                <?php echo date('M j, g:i A', strtotime($doctor['last_login'])); ?>
                                                            </span>
                                                        <?php else: ?>
                                                            <span class="text-muted small">Never</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="action-buttons">
                                                            <button type="button" class="btn btn-sm btn-outline-primary" 
                                                                    onclick="viewDoctor(<?php echo $doctor['doctor_id']; ?>)"
                                                                    title="View Details">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                            <button type="button" class="btn btn-sm btn-outline-success" 
                                                                    onclick="editDoctor(<?php echo $doctor['doctor_id']; ?>)"
                                                                    title="Edit Doctor">
                                                                <i class="ri-edit-line"></i>
                                                            </button>
                                                            <button type="button" class="btn btn-sm btn-outline-info" 
                                                                    onclick="viewSchedule(<?php echo $doctor['doctor_id']; ?>)"
                                                                    title="View Schedule">
                                                                <i class="ri-calendar-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <!-- DataTables JS -->
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script src="assets/libs/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
    <script src="assets/libs/datatables.net-responsive-bs5/js/responsive.bootstrap5.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

    <script>
        let doctorsTable;
        
        $(document).ready(function() {
            // Initialize DataTable
            doctorsTable = $('#doctorsTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[0, 'asc']],
                columnDefs: [
                    { orderable: false, targets: [8] }
                ]
            });
        });

        function viewDoctor(doctorId) {
            window.location.href = 'view_doctor.php?id=' + doctorId;
        }

        function editDoctor(doctorId) {
            window.location.href = 'edit_doctor.php?id=' + doctorId;
        }

        function viewSchedule(doctorId) {
            window.location.href = 'doctor_schedules.php?doctor_id=' + doctorId;
        }

        <?php if(isset($_SESSION['success_message'])): ?>
            Swal.fire({
                icon: 'success',
                title: 'Success',
                text: '<?php echo $_SESSION['success_message']; ?>',
                timer: 3000
            });
            <?php unset($_SESSION['success_message']); ?>
        <?php endif; ?>
    </script>
</body>
</html>

<?php $conn->close(); ?>