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

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

// Fetch appointments for calendar
// Assuming appointments table: appointment_id, patient_id, doctor_id, appointment_date, status, reason
// Assuming users table join for doctor and patient names
$sql = "SELECT a.*, 
               p.first_name AS pat_fname, p.last_name AS pat_lname,
               u.full_name AS doc_name
        FROM appointments a
        JOIN patients p ON a.patient_id = p.patient_id
        JOIN users u ON a.doctor_id = u.user_id
        WHERE a.status != 'CANCELLED'";

$result = $conn->query($sql);
$events = [];

while ($row = $result->fetch_assoc()) {
    $start = $row['appointment_date']; // Format YYYY-MM-DD HH:MM:SS
    // Assume 30 min duration if not set
    $duration = $row['duration_minutes'] ?? 30;
    $end = date('Y-m-d H:i:s', strtotime($start . " +$duration minutes"));

    $color = '#3788d8'; // Default blue
    if ($row['status'] == 'COMPLETED')
        $color = '#28a745';
    if ($row['status'] == 'NOSHOW')
        $color = '#dc3545';
    if ($row['status'] == 'CHECKED_IN')
        $color = '#ffc107';

    $events[] = [
        'id' => $row['appointment_id'],
        'title' => $row['pat_fname'] . ' ' . $row['pat_lname'] . ' (' . $row['doc_name'] . ')',
        'start' => $start,
        'end' => $end,
        'backgroundColor' => $color,
        'borderColor' => $color,
        'extendedProps' => [
            'doctor' => $row['doc_name'],
            'reason' => $row['reason'],
            'status' => $row['status']
        ]
    ];
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Appointment Calendar')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/fullcalendar/main.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">
                    <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 Calendar</h4>
                                <div class="page-title-right">
                                    <a href="book_appointment.php" class="btn btn-primary"><i class="ri-add-line"></i>
                                        New Appointment</a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-body">
                                    <div id="calendar"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/fullcalendar/main.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var calendarEl = document.getElementById('calendar');
            var calendar = new FullCalendar.Calendar(calendarEl, {
                initialView: 'timeGridWeek',
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay'
                },
                themeSystem: 'bootstrap',
                events: <?php echo json_encode($events); ?>,
                eventClick: function (info) {
                    // Simple alert for now, could be a modal
                    var props = info.event.extendedProps;
                    alert('Patient: ' + info.event.title + '\nReason: ' + props.reason + '\nStatus: ' + props.status);
                }
            });
            calendar.render();
        });
    </script>
</body>

</html>