<?php
/**
 * Hearing Aid Follow-up Care Page
 * Audiologist Role - Post-fitting Follow-up and Adjustments
 */

require_once 'layouts/session.php';
require_once 'layouts/dbconn.php';

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

$page_title = "Hearing Aid Follow-up";
$user_id = $_SESSION['user_id'];

// Get patients with hearing aids who need follow-up
$followup_sql = "SELECT c.consultation_id, c.consultation_number, c.patient_id, c.created_at, c.treatment_plan,
                       p.patient_number, u.full_name as patient_name, u.phone, u.email,
                       du.full_name as doctor_name,
                       COUNT(fc.consultation_id) as followup_count,
                       MAX(fc.created_at) as last_followup
                FROM consultations c
                INNER JOIN patients p ON c.patient_id = p.patient_id
                INNER JOIN users u ON p.user_id = u.user_id
                LEFT JOIN doctors d ON c.doctor_id = d.doctor_id
                LEFT JOIN users du ON d.user_id = du.user_id
                LEFT JOIN consultations fc ON c.patient_id = fc.patient_id 
                    AND fc.consultation_type = 'FOLLOW_UP'
                    AND fc.created_at > c.created_at
                WHERE (c.treatment_plan LIKE '%hearing aid%' OR c.chief_complaint LIKE '%hearing aid%')
                AND c.status = 'COMPLETED'
                GROUP BY c.consultation_id
                ORDER BY last_followup IS NULL DESC, last_followup ASC, c.created_at DESC
                LIMIT 50";
$followup_result = $conn->query($followup_sql);

$stats_sql = "SELECT 
                COUNT(DISTINCT c.patient_id) as total_patients,
                COUNT(CASE WHEN fc.created_at IS NULL THEN 1 END) as needs_followup,
                COUNT(CASE WHEN DATE(fc.created_at) = CURDATE() THEN 1 END) as today_followup
              FROM consultations c
              LEFT JOIN consultations fc ON c.patient_id = fc.patient_id 
                  AND fc.consultation_type = 'FOLLOW_UP'
                  AND fc.created_at > c.created_at
              WHERE (c.treatment_plan LIKE '%hearing aid%' OR c.chief_complaint LIKE '%hearing aid%')
              AND c.status = 'COMPLETED'";
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .page-header { background: white; padding: 1.5rem; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 1.5rem; }
        .stat-card { background: white; border-radius: 12px; padding: 1.5rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1); text-align: center; }
        .stat-value { font-size: 2rem; font-weight: 700; margin-bottom: 0.5rem; }
        .info-card { background: white; border-radius: 12px; padding: 1.5rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 1.5rem; }
        .info-card h5 { font-size: 1.125rem; font-weight: 600; margin-bottom: 1.25rem; padding-bottom: 0.75rem; border-bottom: 2px solid #e2e8f0; }
    </style>
</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"><?php echo $page_title; ?></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">Hearing Aid Services</li>
                                        <li class="breadcrumb-item active"><?php echo $page_title; ?></li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="page-header">
                        <h4><i class="ri-calendar-check-line me-2" style="color: #2d7a2d;"></i>Hearing Aid Follow-up Care</h4>
                        <p class="mb-0">Monitor patient progress, make adjustments, and provide ongoing support</p>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-xl-4 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #f59e0b;"><?php echo $stats['needs_followup']; ?></div>
                                <div class="stat-label">Needs Follow-up</div>
                            </div>
                        </div>
                        <div class="col-xl-4 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #3b82f6;"><?php echo $stats['today_followup']; ?></div>
                                <div class="stat-label">Seen Today</div>
                            </div>
                        </div>
                        <div class="col-xl-4 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #2d7a2d;"><?php echo $stats['total_patients']; ?></div>
                                <div class="stat-label">Total HA Patients</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-12">
                            <div class="info-card">
                                <h5><i class="ri-file-list-3-line me-2"></i>Follow-up Schedule</h5>
                                <div class="table-responsive">
                                    <table id="followupTable" class="table table-striped nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Patient</th>
                                                <th>Contact</th>
                                                <th>Initial Fitting</th>
                                                <th>Last Follow-up</th>
                                                <th>Follow-up Count</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($followup_result->num_rows > 0): ?>
                                                <?php while ($followup = $followup_result->fetch_assoc()): 
                                                    $days_since_fitting = null;
                                                    $needs_urgency = false;
                                                    if ($followup['created_at']) {
                                                        $fitting_date = new DateTime($followup['created_at']);
                                                        $now = new DateTime();
                                                        $days_since_fitting = $now->diff($fitting_date)->days;
                                                        // Flag if more than 30 days and no follow-up
                                                        $needs_urgency = ($days_since_fitting > 30 && !$followup['last_followup']);
                                                    }
                                                ?>
                                                    <tr class="<?php echo $needs_urgency ? 'table-warning' : ''; ?>">
                                                        <td>
                                                            <div><strong><?php echo htmlspecialchars($followup['patient_name']); ?></strong></div>
                                                            <small class="text-muted"><?php echo htmlspecialchars($followup['patient_number']); ?></small>
                                                        </td>
                                                        <td><small class="text-muted"><?php echo htmlspecialchars($followup['phone'] ?? 'N/A'); ?></small></td>
                                                        <td>
                                                            <?php echo date('M j, Y', strtotime($followup['created_at'])); ?>
                                                            <?php if ($days_since_fitting): ?>
                                                                <br><small class="text-muted"><?php echo $days_since_fitting; ?> days ago</small>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <?php if ($followup['last_followup']): ?>
                                                                <?php echo date('M j, Y', strtotime($followup['last_followup'])); ?>
                                                            <?php else: ?>
                                                                <span class="badge bg-warning">No Follow-up</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><?php echo $followup['followup_count']; ?> visits</td>
                                                        <td>
                                                            <?php if ($needs_urgency): ?>
                                                                <span class="badge bg-warning">Overdue</span>
                                                            <?php elseif (!$followup['last_followup']): ?>
                                                                <span class="badge bg-info">Pending</span>
                                                            <?php else: ?>
                                                                <span class="badge bg-success">Active</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group">
                                                                <button class="btn btn-sm btn-primary" onclick="scheduleFollowup(<?php echo $followup['patient_id']; ?>)">
                                                                    <i class="ri-calendar-line"></i> Schedule
                                                                </button>
                                                                <button class="btn btn-sm btn-info" onclick="viewHistory(<?php echo $followup['patient_id']; ?>)">
                                                                    <i class="ri-history-line"></i> History
                                                                </button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr><td colspan="7" class="text-center">No follow-up patients found</td></tr>
                                            <?php endif; ?>
                                        </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>
        $(document).ready(function() { $('#followupTable').DataTable({ responsive: true, order: [[5, 'desc']], pageLength: 25 }); });
        
        function scheduleFollowup(patientId) {
            window.location.href = 'schedule_appointment.php?patient_id=' + patientId + '&type=hearing_aid_followup';
        }
        
        function viewHistory(patientId) {
            window.location.href = 'patient_profile.php?patient_id=' + patientId + '&tab=hearing_aid_history';
        }
    </script>
    <script src="assets/js/app.js"></script>
</body>
</html>