<?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'];

// Get statistics - CORRECTED: Using 'status' instead of 'appointment_status'
$stats_query = "SELECT 
    COUNT(*) as total_appointments,
    COUNT(CASE WHEN status = 'SCHEDULED' THEN 1 END) as scheduled,
    COUNT(CASE WHEN status = 'COMPLETED' THEN 1 END) as completed,
    COUNT(CASE WHEN status = 'CANCELLED' THEN 1 END) as cancelled
FROM appointments
WHERE doctor_id = ? AND appointment_date >= CURDATE()";

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

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My 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">
    <link href="assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet" type="text/css" />
</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">My 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">My 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 Upcoming</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">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 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">Cancelled</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['cancelled']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-danger rounded fs-3">
                                                <i class="bx bx-x-circle text-danger"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="row align-items-end">
                                        <div class="col-md-3">
                                            <label class="form-label">Date Range</label>
                                            <input type="text" class="form-control" id="dateRange" placeholder="Select date range">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" id="filterStatus">
                                                <option value="">All Status</option>
                                                <option value="SCHEDULED">Scheduled</option>
                                                <option value="CONFIRMED">Confirmed</option>
                                                <option value="CHECKED_IN">Checked In</option>
                                                <option value="IN_PROGRESS">In Progress</option>
                                                <option value="COMPLETED">Completed</option>
                                                <option value="CANCELLED">Cancelled</option>
                                                <option value="NO_SHOW">No Show</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Patient</label>
                                            <input type="text" class="form-control" id="filterPatient" placeholder="Search...">
                                        </div>
                                        <div class="col-md-2">
                                            <button class="btn btn-primary w-100" id="applyFilter">
                                                <i class="ri-filter-line me-1"></i> Filter
                                            </button>
                                        </div>
                                        <div class="col-md-2">
                                            <button class="btn btn-soft-secondary w-100" id="resetFilter">
                                                <i class="ri-refresh-line me-1"></i> Reset
                                            </button>
                                        </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">All Appointments</h5>
                                        <button class="btn btn-soft-success" id="exportBtn">
                                            <i class="ri-file-excel-line"></i> Export
                                        </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>Appointment ID</th>
                                                <th>Date & 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>

    <!-- Reschedule Modal -->
    <div class="modal fade" id="rescheduleModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Reschedule Appointment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="rescheduleForm">
                        <input type="hidden" id="rescheduleAppointmentId">
                        <div class="mb-3">
                            <label class="form-label">New Date</label>
                            <input type="date" class="form-control" id="newDate" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">New Time</label>
                            <input type="time" class="form-control" id="newTime" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Reason for Reschedule</label>
                            <textarea class="form-control" id="rescheduleReason" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="confirmReschedule">Reschedule</button>
                </div>
            </div>
        </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/libs/flatpickr/flatpickr.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            flatpickr("#dateRange", {
                mode: "range",
                dateFormat: "Y-m-d"
            });

            flatpickr("#newDate", {
                minDate: "today",
                dateFormat: "Y-m-d"
            });

            var table = $('#appointmentsTable').DataTable({
                processing: true,
                serverSide: false,
                ajax: {
                    url: 'ajax/get_my_appointments.php',
                    type: 'POST',
                    data: function(d) {
                        d.date_range = $('#dateRange').val();
                        d.status = $('#filterStatus').val();
                        d.patient = $('#filterPatient').val();
                    }
                },
                columns: [
                    { data: 'appointment_id' },
                    { data: 'datetime' },
                    { data: 'patient_name' },
                    { data: 'contact' },
                    { data: 'type' },
                    { data: 'reason' },
                    { data: 'status' },
                    { data: 'actions' }
                ],
                order: [[1, 'asc']],
                pageLength: 25
            });

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

            $('#resetFilter').on('click', function() {
                $('#dateRange, #filterStatus, #filterPatient').val('');
                table.ajax.reload();
            });

            // Reschedule appointment
            $(document).on('click', '.btn-reschedule', function() {
                var appointmentId = $(this).data('id');
                $('#rescheduleAppointmentId').val(appointmentId);
                $('#rescheduleModal').modal('show');
            });

            $('#confirmReschedule').on('click', function() {
                var appointmentId = $('#rescheduleAppointmentId').val();
                var newDate = $('#newDate').val();
                var newTime = $('#newTime').val();
                var reason = $('#rescheduleReason').val();

                if (!newDate || !newTime) {
                    Swal.fire('Error', 'Please select date and time', 'error');
                    return;
                }

                $.ajax({
                    url: 'ajax/reschedule_appointment.php',
                    type: 'POST',
                    data: {
                        appointment_id: appointmentId,
                        new_date: newDate,
                        new_time: newTime,
                        reason: reason
                    },
                    success: function(response) {
                        var result = JSON.parse(response);
                        if (result.success) {
                            Swal.fire('Success!', 'Appointment rescheduled successfully', 'success');
                            $('#rescheduleModal').modal('hide');
                            table.ajax.reload();
                        } else {
                            Swal.fire('Error!', result.message, 'error');
                        }
                    }
                });
            });

            // 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();
                                } else {
                                    Swal.fire('Error!', result.message, 'error');
                                }
                            }
                        });
                    }
                });
            });

            $('#exportBtn').on('click', function() {
                window.location.href = 'export/export_my_appointments.php';
            });
        });
    </script>
</body>
</html>