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

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

$doctor_id = $_SESSION['user_id'];

// Get today's date
$today = date('Y-m-d');

// Get statistics for today
$stats_query = "SELECT 
    COUNT(DISTINCT a.patient_id) as total_patients,
    COUNT(DISTINCT CASE WHEN a.appointment_status = 'SCHEDULED' THEN a.appointment_id END) as scheduled,
    COUNT(DISTINCT CASE WHEN a.appointment_status = 'CHECKED_IN' THEN a.appointment_id END) as checked_in,
    COUNT(DISTINCT CASE WHEN a.appointment_status = 'IN_CONSULTATION' THEN a.appointment_id END) as in_consultation,
    COUNT(DISTINCT CASE WHEN a.appointment_status = 'COMPLETED' THEN a.appointment_id END) as completed
FROM appointments a
WHERE a.doctor_id = ? AND DATE(a.appointment_date) = ?";

$stats_stmt = $conn->prepare($stats_query);
$stats_stmt->bind_param("is", $doctor_id, $today);
$stats_stmt->execute();
$stats = $stats_stmt->get_result()->fetch_assoc();
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => "Today's Patients")); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .stat-card {
            background: linear-gradient(135deg, #2d7a2d, #26a69a);
            border-radius: 10px;
            padding: 1.5rem;
            color: white;
            transition: transform 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
        }
        
        .stat-icon {
            font-size: 2.5rem;
            opacity: 0.8;
        }
        
        .patient-card {
            border-left: 4px solid #2d7a2d;
            transition: all 0.3s ease;
        }
        
        .patient-card:hover {
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
            transform: translateX(5px);
        }
        
        .status-badge {
            padding: 0.35rem 0.75rem;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        
        .status-scheduled {
            background: #e3f2fd;
            color: #1976d2;
        }
        
        .status-checked-in {
            background: #fff3e0;
            color: #f57c00;
        }
        
        .status-in-consultation {
            background: #f3e5f5;
            color: #7b1fa2;
        }
        
        .status-completed {
            background: #e8f5e9;
            color: #388e3c;
        }
        
        .patient-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, #2d7a2d, #26a69a);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 1.2rem;
        }
        
        .urgent-flag {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 0.5rem;
            margin-bottom: 0.5rem;
            border-radius: 4px;
        }
    </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">Today's Patients</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="ent_consultant_dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Today's Patients</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="card stat-card">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <h4 class="mb-1 text-white"><?php echo $stats['total_patients']; ?></h4>
                                            <p class="mb-0 text-white-50">Total Patients</p>
                                        </div>
                                        <div class="stat-icon">
                                            <i class="ri-user-line"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card" style="background: linear-gradient(135deg, #1976d2, #1565c0); color: white;">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <h4 class="mb-1 text-white"><?php echo $stats['scheduled']; ?></h4>
                                            <p class="mb-0 text-white-50">Scheduled</p>
                                        </div>
                                        <div class="stat-icon">
                                            <i class="ri-calendar-line"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card" style="background: linear-gradient(135deg, #f57c00, #ef6c00); color: white;">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <h4 class="mb-1 text-white"><?php echo $stats['checked_in']; ?></h4>
                                            <p class="mb-0 text-white-50">Checked In</p>
                                        </div>
                                        <div class="stat-icon">
                                            <i class="ri-user-follow-line"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card" style="background: linear-gradient(135deg, #7b1fa2, #6a1b9a); color: white;">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <h4 class="mb-1 text-white"><?php echo $stats['in_consultation']; ?></h4>
                                            <p class="mb-0 text-white-50">In Consultation</p>
                                        </div>
                                        <div class="stat-icon">
                                            <i class="ri-stethoscope-line"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Patients Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Today's Appointments</h5>
                                </div>
                                <div class="card-body">
                                    <table id="patientsTable" class="table table-bordered dt-responsive nowrap table-striped align-middle" style="width:100%">
                                        <thead>
                                            <tr>
                                                <th>Time</th>
                                                <th>Patient</th>
                                                <th>Contact</th>
                                                <th>Type</th>
                                                <th>Reason</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- Data loaded via AJAX -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <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/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize DataTable
            var table = $('#patientsTable').DataTable({
                processing: true,
                serverSide: false,
                ajax: {
                    url: 'ajax/get_todays_patients.php',
                    type: 'POST',
                    error: function(xhr, error, thrown) {
                        console.error('DataTable error:', error);
                    }
                },
                columns: [
                    { data: 'appointment_time' },
                    { data: 'patient_info' },
                    { data: 'contact' },
                    { data: 'appointment_type' },
                    { data: 'reason' },
                    { data: 'status' },
                    { data: 'actions' }
                ],
                order: [[0, 'asc']],
                pageLength: 25,
                dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>rtip'
            });

            // Refresh table every 30 seconds
            setInterval(function() {
                table.ajax.reload(null, false);
            }, 30000);

            // Start consultation
            $(document).on('click', '.btn-start-consultation', function() {
                var appointmentId = $(this).data('id');
                var patientName = $(this).data('patient');
                
                Swal.fire({
                    title: 'Start Consultation',
                    html: `Start consultation for <strong>${patientName}</strong>?`,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Start',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = `new_consultation.php?appointment_id=${appointmentId}`;
                    }
                });
            });

            // View patient history
            $(document).on('click', '.btn-view-history', function() {
                var patientId = $(this).data('patient-id');
                window.location.href = `patient_medical_history.php?patient_id=${patientId}`;
            });

            // Mark as completed
            $(document).on('click', '.btn-mark-completed', function() {
                var appointmentId = $(this).data('id');
                
                Swal.fire({
                    title: 'Mark as Completed',
                    text: 'Mark this appointment as completed?',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Complete',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: 'ajax/update_appointment_status.php',
                            type: 'POST',
                            data: {
                                appointment_id: appointmentId,
                                status: 'COMPLETED'
                            },
                            success: function(response) {
                                var result = JSON.parse(response);
                                if (result.success) {
                                    Swal.fire('Success!', 'Appointment marked as completed', 'success');
                                    table.ajax.reload(null, false);
                                } else {
                                    Swal.fire('Error!', result.message, 'error');
                                }
                            }
                        });
                    }
                });
            });
        });
    </script>
</body>
</html>