<?php
/**
 * Hearing Aid Fitting Page
 * Audiologist Role - Initial Hearing Aid Fitting Services
 */

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 Fitting";
$user_id = $_SESSION['user_id'];

// Note: hearing_aid_services table may need to be created if not exists
// Get hearing aid fitting appointments from consultations
$fittings_sql = "SELECT c.consultation_id, c.consultation_number, c.patient_id, c.doctor_id, c.chief_complaint,
                       c.treatment_plan, c.created_at, c.status,
                       p.patient_number, u.full_name as patient_name, u.phone_primary, u.email, u.date_of_birth,
                       du.full_name as doctor_name
                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
                WHERE (c.treatment_plan LIKE '%hearing aid%' OR c.chief_complaint LIKE '%hearing aid%')
                AND c.status = 'COMPLETED'
                ORDER BY c.created_at DESC
                LIMIT 50";
$fittings_result = $conn->query($fittings_sql);

// Get statistics
$stats_sql = "SELECT 
                COUNT(CASE WHEN DATE(c.created_at) = CURDATE() THEN 1 END) as today_count,
                COUNT(CASE WHEN YEARWEEK(c.created_at) = YEARWEEK(CURDATE()) THEN 1 END) as week_count,
                COUNT(*) as total_count
              FROM consultations c
              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; }
        .info-box { background: #eff6ff; border-radius: 8px; padding: 1rem; margin-bottom: 1rem; border-left: 4px solid #3b82f6; }
    </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">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-speaker-3-line me-2" style="color: #2d7a2d;"></i>Hearing Aid Fitting Services</h4>
                                <p class="mb-0">Initial hearing aid selection, fitting, and programming</p>
                            </div>
                            <button class="btn btn-primary" onclick="newFitting()">
                                <i class="ri-add-line"></i> New Fitting
                            </button>
                        </div>
                    </div>
                    
                    <div class="info-box">
                        <h6 class="mb-2"><i class="ri-information-line me-1"></i> Fitting Protocol</h6>
                        <small class="text-muted">
                            1. Review audiogram and test results 2. Assess patient needs and lifestyle 
                            3. Select appropriate device 4. Program to prescription 5. Verify with real-ear measurements 
                            6. Patient education and counseling 7. Schedule follow-up
                        </small>
                    </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: #3b82f6;"><?php echo $stats['today_count']; ?></div>
                                <div class="stat-label">Fittings Today</div>
                            </div>
                        </div>
                        <div class="col-xl-4 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value" style="color: #8b5cf6;"><?php echo $stats['week_count']; ?></div>
                                <div class="stat-label">This Week</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_count']; ?></div>
                                <div class="stat-label">Total Fittings</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>Hearing Aid Fitting Candidates</h5>
                                <div class="table-responsive">
                                    <table id="fittingsTable" class="table table-striped nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Date</th>
                                                <th>Consultation #</th>
                                                <th>Patient</th>
                                                <th>Age</th>
                                                <th>Contact</th>
                                                <th>Referred By</th>
                                                <th>Chief Complaint</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($fittings_result->num_rows > 0): ?>
                                                <?php while ($fitting = $fittings_result->fetch_assoc()): 
                                                    $age = null;
                                                    if ($fitting['date_of_birth']) {
                                                        $dob = new DateTime($fitting['date_of_birth']);
                                                        $now = new DateTime();
                                                        $age = $now->diff($dob)->y;
                                                    }
                                                ?>
                                                    <tr>
                                                        <td><?php echo date('M j, Y', strtotime($fitting['created_at'])); ?></td>
                                                        <td><strong><?php echo htmlspecialchars($fitting['consultation_number']); ?></strong></td>
                                                        <td>
                                                            <div><strong><?php echo htmlspecialchars($fitting['patient_name']); ?></strong></div>
                                                            <small class="text-muted"><?php echo htmlspecialchars($fitting['patient_number']); ?></small>
                                                        </td>
                                                        <td><?php echo $age !== null ? $age . ' yrs' : 'N/A'; ?></td>
                                                        <td><small class="text-muted"><?php echo htmlspecialchars($fitting['phone'] ?? 'N/A'); ?></small></td>
                                                        <td><?php echo htmlspecialchars($fitting['doctor_name'] ?? 'Self'); ?></td>
                                                        <td><small><?php echo htmlspecialchars(substr($fitting['chief_complaint'], 0, 50)) . '...'; ?></small></td>
                                                        <td>
                                                            <div class="btn-group">
                                                                <button class="btn btn-sm btn-success" onclick="startFitting(<?php echo $fitting['patient_id']; ?>, <?php echo $fitting['consultation_id']; ?>)">
                                                                    <i class="ri-play-line"></i> Start Fitting
                                                                </button>
                                                                <button class="btn btn-sm btn-info" onclick="viewPatient(<?php echo $fitting['patient_id']; ?>)">
                                                                    <i class="ri-eye-line"></i> View
                                                                </button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr><td colspan="8" class="text-center">No hearing aid fitting candidates 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() { $('#fittingsTable').DataTable({ responsive: true, order: [[0, 'desc']], pageLength: 25 }); });
        
        function newFitting() {
            window.location.href = 'search_patient.php?action=hearing_aid_fitting';
        }
        
        function startFitting(patientId, consultationId) {
            window.location.href = 'hearing_aid_fitting_form.php?patient_id=' + patientId + '&consultation_id=' + consultationId;
        }
        
        function viewPatient(patientId) {
            window.location.href = 'patient_profile.php?patient_id=' + patientId;
        }
    </script>
    <script src="assets/js/app.js"></script>
</body>
</html>