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

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

$user_id = $_SESSION['user_id'];

// Get filters
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-d', strtotime('-30 days'));
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-d');
$doctor_filter = isset($_GET['doctor_id']) ? intval($_GET['doctor_id']) : 0;
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';

// Build query
$sql = "SELECT 
    a.appointment_id,
    a.appointment_number,
    a.appointment_date,
    a.appointment_time,
    a.appointment_type,
    a.status,
    a.chief_complaint,
    p.patient_id,
    p.patient_number,
    p.full_name as patient_name,
    p.phone_primary,
    p.date_of_birth,
    u.full_name as doctor_name,
    pv.visit_number,
    pv.registration_type,
    pv.smart_session_id,
    c.consultation_id,
    c.diagnosis
FROM appointments a
JOIN patients p ON a.patient_id = p.patient_id
JOIN users u ON a.doctor_id = u.user_id
LEFT JOIN patient_visits pv ON a.visit_id = pv.visit_id
LEFT JOIN consultations c ON a.consultation_id = c.consultation_id
WHERE a.appointment_type = 'FOLLOW_UP'
AND a.appointment_date BETWEEN ? AND ?";

$params = [$date_from, $date_to];
$types = "ss";

if ($doctor_filter > 0) {
    $sql .= " AND a.doctor_id = ?";
    $params[] = $doctor_filter;
    $types .= "i";
}

if ($status_filter) {
    $sql .= " AND a.status = ?";
    $params[] = $status_filter;
    $types .= "s";
}

$sql .= " ORDER BY a.appointment_date DESC, a.appointment_time DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$followups = $stmt->get_result();

// Get doctors for filter
$doctors_sql = "SELECT user_id, full_name FROM users WHERE user_type = 'DOCTOR' AND status = 'ACTIVE' ORDER BY full_name";
$doctors_result = $conn->query($doctors_sql);

// Get statistics
$stats_sql = "SELECT 
    COUNT(*) as total_followups,
    SUM(CASE WHEN status = 'SCHEDULED' THEN 1 ELSE 0 END) as scheduled,
    SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) as completed,
    SUM(CASE WHEN status = 'MISSED' THEN 1 ELSE 0 END) as missed
FROM appointments 
WHERE appointment_type = 'FOLLOW_UP'
AND appointment_date BETWEEN ? AND ?";

$stats_stmt = $conn->prepare($stats_sql);
$stats_stmt->bind_param("ss", $date_from, $date_to);
$stats_stmt->execute();
$stats = $stats_stmt->get_result()->fetch_assoc();
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Follow-up Visits')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="assets/libs/flatpickr/flatpickr.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">
                                    <i class="ri-calendar-check-line me-2"></i>Follow-up Visits
                                </h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Follow-up Visits</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-muted fw-medium text-uppercase mb-3">Total Follow-ups</p>
                                            <h4 class="fs-22 fw-semibold mb-3">
                                                <span class="counter-value" data-target="<?php echo $stats['total_followups']; ?>">0</span>
                                            </h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-primary-subtle text-primary rounded fs-3">
                                                <i class="ri-calendar-line"></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-muted fw-medium text-uppercase mb-3">Scheduled</p>
                                            <h4 class="fs-22 fw-semibold mb-3">
                                                <span class="counter-value" data-target="<?php echo $stats['scheduled']; ?>">0</span>
                                            </h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-warning-subtle text-warning rounded fs-3">
                                                <i class="ri-time-line"></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-muted fw-medium text-uppercase mb-3">Completed</p>
                                            <h4 class="fs-22 fw-semibold mb-3">
                                                <span class="counter-value" data-target="<?php echo $stats['completed']; ?>">0</span>
                                            </h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-success-subtle text-success rounded fs-3">
                                                <i class="ri-checkbox-circle-line"></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-muted fw-medium text-uppercase mb-3">Missed</p>
                                            <h4 class="fs-22 fw-semibold mb-3">
                                                <span class="counter-value" data-target="<?php echo $stats['missed']; ?>">0</span>
                                            </h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-danger-subtle text-danger rounded fs-3">
                                                <i class="ri-close-circle-line"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="card">
                        <div class="card-body">
                            <form method="GET" class="row g-3">
                                <div class="col-md-3">
                                    <label class="form-label">From Date</label>
                                    <input type="text" class="form-control flatpickr-date" name="date_from" 
                                           value="<?php echo $date_from; ?>">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">To Date</label>
                                    <input type="text" class="form-control flatpickr-date" name="date_to" 
                                           value="<?php echo $date_to; ?>">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Doctor</label>
                                    <select class="form-select" name="doctor_id">
                                        <option value="0">All Doctors</option>
                                        <?php while($doctor = $doctors_result->fetch_assoc()): ?>
                                            <option value="<?php echo $doctor['user_id']; ?>" 
                                                <?php echo ($doctor_filter == $doctor['user_id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($doctor['full_name']); ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Status</label>
                                    <select class="form-select" name="status">
                                        <option value="">All Status</option>
                                        <option value="SCHEDULED" <?php echo ($status_filter == 'SCHEDULED') ? 'selected' : ''; ?>>Scheduled</option>
                                        <option value="COMPLETED" <?php echo ($status_filter == 'COMPLETED') ? 'selected' : ''; ?>>Completed</option>
                                        <option value="MISSED" <?php echo ($status_filter == 'MISSED') ? 'selected' : ''; ?>>Missed</option>
                                        <option value="CANCELLED" <?php echo ($status_filter == 'CANCELLED') ? 'selected' : ''; ?>>Cancelled</option>
                                    </select>
                                </div>
                                <div class="col-md-1">
                                    <label class="form-label">&nbsp;</label>
                                    <button type="submit" class="btn btn-primary w-100">
                                        <i class="ri-search-line me-1"></i>Filter
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Follow-ups Table -->
                    <div class="card">
                        <div class="card-header">
                            <div class="d-flex align-items-center">
                                <h5 class="card-title flex-grow-1 mb-0">Follow-up Appointments</h5>
                                <div class="flex-shrink-0">
                                    <button class="btn btn-success btn-sm" onclick="exportToExcel()">
                                        <i class="ri-file-excel-line me-1"></i>Export
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover align-middle mb-0">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Appointment #</th>
                                            <th>Patient</th>
                                            <th>Doctor</th>
                                            <th>Date & Time</th>
                                            <th>Registration</th>
                                            <th>Diagnosis</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if ($followups->num_rows > 0): ?>
                                            <?php while($row = $followups->fetch_assoc()): ?>
                                                <?php
                                                $status_badge = [
                                                    'SCHEDULED' => 'bg-warning',
                                                    'COMPLETED' => 'bg-success',
                                                    'MISSED' => 'bg-danger',
                                                    'CANCELLED' => 'bg-secondary'
                                                ];
                                                $badge_class = $status_badge[$row['status']] ?? 'bg-info';
                                                
                                                $age = '';
                                                if ($row['date_of_birth']) {
                                                    $dob = new DateTime($row['date_of_birth']);
                                                    $now = new DateTime();
                                                    $age = $now->diff($dob)->y . 'y';
                                                }
                                                ?>
                                                <tr>
                                                    <td>
                                                        <strong><?php echo $row['appointment_number']; ?></strong><br>
                                                        <small class="text-muted"><?php echo $row['visit_number'] ?? 'N/A'; ?></small>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <strong><?php echo htmlspecialchars($row['patient_name']); ?></strong>
                                                            <?php if ($row['smart_session_id']): ?>
                                                                <span class="badge bg-primary-subtle text-primary ms-1">SMART</span>
                                                            <?php endif; ?>
                                                        </div>
                                                        <small class="text-muted">
                                                            <?php echo $row['patient_number']; ?> | <?php echo $age; ?>
                                                        </small>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($row['doctor_name']); ?></td>
                                                    <td>
                                                        <div><?php echo date('M d, Y', strtotime($row['appointment_date'])); ?></div>
                                                        <small class="text-muted"><?php echo date('h:i A', strtotime($row['appointment_time'])); ?></small>
                                                    </td>
                                                    <td>
                                                        <span class="badge <?php echo ($row['registration_type'] == 'INSURANCE') ? 'bg-info' : 'bg-secondary'; ?>">
                                                            <?php echo $row['registration_type']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <small><?php echo $row['diagnosis'] ? substr($row['diagnosis'], 0, 40) . '...' : 'Pending'; ?></small>
                                                    </td>
                                                    <td>
                                                        <span class="badge <?php echo $badge_class; ?>">
                                                            <?php echo $row['status']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group btn-group-sm">
                                                            <a href="patient_profile.php?id=<?php echo $row['patient_id']; ?>" 
                                                               class="btn btn-outline-primary" title="View Patient">
                                                                <i class="ri-user-line"></i>
                                                            </a>
                                                            <?php if ($row['consultation_id']): ?>
                                                                <a href="view_consultation.php?id=<?php echo $row['consultation_id']; ?>" 
                                                                   class="btn btn-outline-info" title="View Consultation">
                                                                    <i class="ri-file-list-3-line"></i>
                                                                </a>
                                                            <?php endif; ?>
                                                            <?php if ($row['status'] == 'SCHEDULED'): ?>
                                                                <button onclick="rescheduleAppointment(<?php echo $row['appointment_id']; ?>)" 
                                                                        class="btn btn-outline-warning" title="Reschedule">
                                                                    <i class="ri-calendar-event-line"></i>
                                                                </button>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endwhile; ?>
                                        <?php else: ?>
                                            <tr>
                                                <td colspan="8" class="text-center py-4">
                                                    <i class="ri-calendar-close-line fs-1 text-muted"></i>
                                                    <p class="text-muted mt-2">No follow-up appointments found</p>
                                                </td>
                                            </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>

    <script>
        // Initialize flatpickr
        flatpickr('.flatpickr-date', {
            dateFormat: 'Y-m-d'
        });

        // Counter animation
        document.querySelectorAll('.counter-value').forEach(counter => {
            const target = parseInt(counter.getAttribute('data-target'));
            const duration = 1000;
            const step = target / (duration / 16);
            let current = 0;
            
            const timer = setInterval(() => {
                current += step;
                if (current >= target) {
                    counter.textContent = target;
                    clearInterval(timer);
                } else {
                    counter.textContent = Math.floor(current);
                }
            }, 16);
        });

        function rescheduleAppointment(appointmentId) {
            Swal.fire({
                title: 'Reschedule Appointment',
                text: 'Would you like to reschedule this follow-up appointment?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, reschedule',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = 'schedule_appointment.php?reschedule=' + appointmentId;
                }
            });
        }

        function exportToExcel() {
            const table = document.querySelector('table');
            const rows = Array.from(table.querySelectorAll('tr'));
            
            let csv = 'Follow-up Visits Report\n\n';
            rows.forEach(row => {
                const cells = Array.from(row.querySelectorAll('th, td'));
                const rowData = cells.map(cell => {
                    return '"' + cell.textContent.trim().replace(/"/g, '""') + '"';
                }).join(',');
                csv += rowData + '\n';
            });
            
            const blob = new Blob([csv], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'followup_visits_' + new Date().toISOString().split('T')[0] + '.csv';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
    </script>
</body>
</html>