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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$doctor_id = $_SESSION['user_id'];
$today = date('Y-m-d');

// Get statistics
$stats_query = "SELECT 
    COUNT(*) as total_appointments,
    COUNT(CASE WHEN appointment_status = 'SCHEDULED' THEN 1 END) as scheduled,
    COUNT(CASE WHEN appointment_status = 'CHECKED_IN' THEN 1 END) as checked_in,
    COUNT(CASE WHEN appointment_status = 'COMPLETED' THEN 1 END) as completed
FROM appointments
WHERE doctor_id = ? AND DATE(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 Appointments")); ?>
    <?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">
</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 Appointments</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 Appointments</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Total Appointments</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4"><?php echo $stats['total_appointments']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-success rounded fs-3">
                                                <i class="bx bx-calendar text-success"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Scheduled</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4"><?php echo $stats['scheduled']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-info rounded fs-3">
                                                <i class="bx bx-time text-info"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Checked In</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4"><?php echo $stats['checked_in']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-warning rounded fs-3">
                                                <i class="bx bx-user-check text-warning"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Completed</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4"><?php echo $stats['completed']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-primary rounded fs-3">
                                                <i class="bx bx-check-circle text-primary"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Appointments Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="card-title mb-0">Today's Schedule</h5>
                                        <button class="btn btn-soft-primary" id="refreshBtn">
                                            <i class="ri-refresh-line"></i> Refresh
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <table id="appointmentsTable" 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() {
            var table = $('#appointmentsTable').DataTable({
                processing: true,
                serverSide: false,
                ajax: {
                    url: 'ajax/get_todays_appointments.php',
                    type: 'POST'
                },
                columns: [
                    { data: 'appointment_time' },
                    { data: 'patient_info' },
                    { data: 'contact' },
                    { data: 'appointment_type' },
                    { data: 'reason' },
                    { data: 'status' },
                    { data: 'actions' }
                ],
                order: [[0, 'asc']],
                pageLength: 25
            });

            $('#refreshBtn').on('click', function() {
                table.ajax.reload();
            });

            // Auto-refresh every 60 seconds
            setInterval(function() {
                table.ajax.reload(null, false);
            }, 60000);

            // Start consultation
            $(document).on('click', '.btn-start-consultation', function() {
                var appointmentId = $(this).data('id');
                window.location.href = 'new_consultation.php?appointment_id=' + appointmentId;
            });

            // Reschedule appointment
            $(document).on('click', '.btn-reschedule', function() {
                var appointmentId = $(this).data('id');
                // Open reschedule modal or redirect
                window.location.href = 'my_appointments.php?reschedule=' + appointmentId;
            });

            // Cancel appointment
            $(document).on('click', '.btn-cancel', function() {
                var appointmentId = $(this).data('id');
                
                Swal.fire({
                    title: 'Cancel Appointment',
                    text: 'Are you sure you want to cancel this appointment?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Cancel',
                    cancelButtonText: 'No'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: 'ajax/cancel_appointment.php',
                            type: 'POST',
                            data: { appointment_id: appointmentId },
                            success: function(response) {
                                var result = JSON.parse(response);
                                if (result.success) {
                                    Swal.fire('Cancelled!', 'Appointment has been cancelled', 'success');
                                    table.ajax.reload(null, false);
                                } else {
                                    Swal.fire('Error!', result.message, 'error');
                                }
                            }
                        });
                    }
                });
            });
        });
    </script>
</body>
</html>