<?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
$stats_query = "SELECT 
    COUNT(*) as total_appointments,
    COUNT(CASE WHEN appointment_status = 'COMPLETED' THEN 1 END) as completed,
    COUNT(CASE WHEN appointment_status = 'CANCELLED' THEN 1 END) as cancelled,
    COUNT(CASE WHEN appointment_status = 'NO_SHOW' THEN 1 END) as no_show
FROM appointments
WHERE doctor_id = ?";

$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' => 'Appointment History')); ?>
    <?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">Appointment History</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">Appointment History</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 number_format($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">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 number_format($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 number_format($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 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">No Show</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 number_format($stats['no_show']); ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-warning rounded fs-3">
                                                <i class="bx bx-error text-warning"></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-2">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" id="filterStatus">
                                                <option value="">All Status</option>
                                                <option value="COMPLETED">Completed</option>
                                                <option value="CANCELLED">Cancelled</option>
                                                <option value="NO_SHOW">No Show</option>
                                                <option value="RESCHEDULED">Rescheduled</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Type</label>
                                            <select class="form-select" id="filterType">
                                                <option value="">All Types</option>
                                                <option value="NEW_CONSULTATION">New</option>
                                                <option value="FOLLOW_UP">Follow-up</option>
                                                <option value="EMERGENCY">Emergency</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-3">
                                            <button class="btn btn-primary me-2" id="applyFilter">
                                                <i class="ri-filter-line me-1"></i> Filter
                                            </button>
                                            <button class="btn btn-soft-secondary" id="resetFilter">
                                                <i class="ri-refresh-line me-1"></i> Reset
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- History 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">Appointment History</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="historyTable" 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>

    <!-- View Details Modal -->
    <div class="modal fade" id="detailsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Appointment Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="detailsModalBody">
                    <!-- Content loaded via AJAX -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</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"
            });

            var table = $('#historyTable').DataTable({
                processing: true,
                serverSide: false,
                ajax: {
                    url: 'ajax/get_appointment_history.php',
                    type: 'POST',
                    data: function(d) {
                        d.date_range = $('#dateRange').val();
                        d.status = $('#filterStatus').val();
                        d.type = $('#filterType').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, 'desc']],
                pageLength: 25
            });

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

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

            // View details
            $(document).on('click', '.btn-view-details', function() {
                var appointmentId = $(this).data('id');
                $('#detailsModalBody').html('<div class="text-center py-5"><div class="spinner-border text-primary"></div></div>');
                $('#detailsModal').modal('show');
                
                $.ajax({
                    url: 'ajax/get_appointment_details.php',
                    type: 'POST',
                    data: { appointment_id: appointmentId },
                    success: function(response) {
                        $('#detailsModalBody').html(response);
                    }
                });
            });

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

            $('#exportBtn').on('click', function() {
                var dateRange = $('#dateRange').val();
                var status = $('#filterStatus').val();
                var type = $('#filterType').val();
                var patient = $('#filterPatient').val();
                
                window.location.href = 'export/export_appointment_history.php?date_range=' + dateRange + 
                                      '&status=' + status + '&type=' + type + '&patient=' + patient;
            });
        });
    </script>
</body>
</html>