<?php
$search_patient = $_GET['patient'] ?? '';
$search_doctor = $_GET['doctor'] ?? '';
$search_date = $_GET['date'] ?? '';
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$where = "WHERE 1=1";
$params = [];

if ($search_patient) {
    $where .= " AND p.name LIKE ?";
    $params[] = "%$search_patient%";
}
if ($search_doctor) {
    $where .= " AND (
        doc.name_en LIKE ? OR doc.name_ar LIKE ? OR 
        nur.name_en LIKE ? OR nur.name_ar LIKE ?
    )";
    $params[] = "%$search_doctor%";
    $params[] = "%$search_doctor%";
    $params[] = "%$search_doctor%";
    $params[] = "%$search_doctor%";
}
if ($search_date) {
    $where .= " AND DATE(v.visit_date) = ?";
    $params[] = $search_date;
}

// Count Total
$countQuery = "
    SELECT COUNT(*) 
    FROM visits v
    JOIN patients p ON v.patient_id = p.id 
    LEFT JOIN employees doc ON v.doctor_id = doc.id 
    LEFT JOIN employees nur ON v.nurse_id = nur.id
    $where";
$stmt = $db->prepare($countQuery);
$stmt->execute($params);
$totalVisits = $stmt->fetchColumn();
$totalPages = ceil($totalVisits / $limit);

// Fetch Data
$query = "
    SELECT v.*, 
           p.name as patient_name, p.dob as patient_dob, p.gender as patient_gender, 
           doc.name_$lang as doctor_name,
           nur.name_$lang as nurse_name
    FROM visits v
    JOIN patients p ON v.patient_id = p.id 
    LEFT JOIN employees doc ON v.doctor_id = doc.id 
    LEFT JOIN employees nur ON v.nurse_id = nur.id
    $where
    ORDER BY v.visit_date DESC
    LIMIT $limit OFFSET $offset";

$stmt = $db->prepare($query);
$stmt->execute($params);
$raw_visits = $stmt->fetchAll(); 
$visits = [];
foreach ($raw_visits as $v) { 
    // Fetch Lab Inquiries
    $v['lab_inquiries'] = $db->query("SELECT li.* FROM laboratory_inquiries li WHERE li.visit_id = " . (int)$v['id'])->fetchAll();
    foreach($v['lab_inquiries'] as &$li) {
        $li['items'] = $db->query("SELECT it.*, lt.name_$lang as test_name FROM inquiry_tests it JOIN laboratory_tests lt ON it.test_id = lt.id WHERE it.inquiry_id = " . (int)$li['id'])->fetchAll();
        $li['results'] = implode(', ', array_map(function($item) { return $item['test_name'] . ': ' . ($item['result'] ?: '-'); }, $li['items']));
    }
    
    // Fetch X-Ray Inquiries
    $v['xray_inquiries'] = $db->query("SELECT xi.* FROM xray_inquiries xi WHERE xi.visit_id = " . (int)$v['id'])->fetchAll(); 
    foreach($v['xray_inquiries'] as &$xi) { 
        $xi['items'] = $db->query("SELECT xit.*, xt.name_$lang as xray_name FROM xray_inquiry_items xit JOIN xray_tests xt ON xit.xray_id = xt.id WHERE xit.inquiry_id = " . (int)$xi['id'])->fetchAll(); 
    } 

    // Fetch Prescriptions
    $v['prescriptions'] = $db->query("SELECT * FROM visit_prescriptions WHERE visit_id = " . (int)$v['id'])->fetchAll();

    $visits[] = $v;
}

// --- AJAX HANDLER ---
if (isset($_GET['ajax_search'])) {
    ob_start();
    if (empty($visits)):
    ?>
    <tr>
        <td colspan="9" class="text-center py-5 text-muted">
            <i class="bi bi-clipboard2-pulse display-4 d-block mb-3"></i>
            <?php echo __('no_visits_found'); ?>
        </td>
    </tr>
    <?php else: ?>
    <?php foreach ($visits as $v): ?>
    <tr>
        <td class="px-4 text-muted small">
            <?php echo $v['id']; ?>
            <?php if (($v['visit_type'] ?? 'Clinic') === 'Home'): ?>
                <br><span class="badge bg-warning text-dark"><i class="bi bi-house"></i> Home</span>
            <?php endif; ?>
        </td>
        <td class="text-secondary"><?php echo date('Y-m-d H:i', strtotime($v['visit_date'])); ?></td>
        <td class="fw-semibold text-dark">
            <?php echo htmlspecialchars($v['patient_name'] ?? ''); ?>
            <?php if (!empty($v['address'])): ?>
                <br><small class="text-muted"><i class="bi bi-geo-alt"></i> <?php echo htmlspecialchars($v['address']); ?></small>
            <?php endif; ?>
        </td>
        <td class="text-secondary">
            <?php 
            if (!empty($v['doctor_name'])) {
                echo htmlspecialchars($v['doctor_name']); 
            } elseif (!empty($v['nurse_name'])) {
                echo htmlspecialchars($v['nurse_name']) . ' <small class="text-muted">(' . __('nurse') . ')</small>';
            }
            ?>
        </td>
        <td>
            <?php 
            $diagnosis_plain = strip_tags($v['diagnosis'] ?? '');
            $snippet = mb_strimwidth($diagnosis_plain, 0, 30, "...");
            ?>
            <small class="text-muted" title="<?php echo htmlspecialchars($diagnosis_plain); ?>"><?php echo htmlspecialchars($snippet); ?></small>
        </td>
        <td>
            <?php 
                $vitals = [];
                if(!empty($v['blood_pressure'])) $vitals[] = '<i class="bi bi-heart-pulse me-1"></i>' . htmlspecialchars($v['blood_pressure'] ?? '');
                if(!empty($v['weight'])) $vitals[] = '<i class="bi bi-speedometer2 me-1"></i>' . htmlspecialchars($v['weight'] ?? '') . 'kg';
                if(!empty($v['temperature'])) $vitals[] = '<i class="bi bi-thermometer-half me-1"></i>' . htmlspecialchars($v['temperature'] ?? '') . '°C';
                echo implode('<br>', $vitals);
            ?>
        </td>
            <td>
            <?php 
            $treatment_plain = strip_tags($v['treatment_plan'] ?? '');
            $t_snippet = mb_strimwidth($treatment_plain, 0, 30, "...");
            ?>
            <small class="text-muted" title="<?php echo htmlspecialchars($treatment_plain); ?>"><?php echo htmlspecialchars($t_snippet); ?></small>
        </td>
        <td>
            <div class="d-flex gap-1">
                <?php if (!empty($v['lab_inquiries'])): ?> 
                    <span class="badge bg-info text-white" title="<?php echo count($v['lab_inquiries']); ?> <?php echo __('laboratory'); ?>" data-bs-toggle="tooltip">
                        <i class="bi bi-flask"></i> <?php echo count($v['lab_inquiries']); ?>
                    </span>
                <?php endif; ?> 
                <?php if (!empty($v['xray_inquiries'])): ?> 
                    <span class="badge bg-dark text-white" title="<?php echo count($v['xray_inquiries']); ?> <?php echo __('xray'); ?>" data-bs-toggle="tooltip">
                        <i class="bi bi-camera"></i> <?php echo count($v['xray_inquiries']); ?>
                    </span>
                <?php endif; ?>
            </div>
        </td>
        <td class="text-end px-4">
            <div class="d-flex justify-content-end gap-1">
                <?php 
                // Encode safely for attribute
                $json_v = htmlspecialchars(json_encode($v, JSON_UNESCAPED_UNICODE) ?: '{}', ENT_QUOTES, 'UTF-8');
                $patient_name_json = htmlspecialchars(json_encode($v['patient_name'] ?? '', JSON_UNESCAPED_UNICODE) ?: '""', ENT_QUOTES, 'UTF-8');
                ?>
                <button class="btn btn-sm btn-outline-success" 
                        onclick="showVisitResultsModal(JSON.parse(this.getAttribute('data-visit')))" 
                        data-visit="<?php echo $json_v; ?>"
                        data-bs-toggle="tooltip" title="<?php echo __('view_results'); ?>">
                    <i class="bi bi-eye"></i>
                </button>
                <button class="btn btn-sm btn-outline-warning" 
                        onclick="showEditVisitModal(JSON.parse(this.getAttribute('data-visit')))"
                        data-visit="<?php echo $json_v; ?>"
                        data-bs-toggle="tooltip" title="<?php echo __('edit'); ?>">
                    <i class="bi bi-pencil-square"></i>
                </button>
                <button class="btn btn-sm btn-outline-info" 
                        onclick="showLabInquiryModalFromVisit(<?php echo $v['id']; ?>, <?php echo $v['patient_id']; ?>, <?php echo $patient_name_json; ?>)"
                        data-bs-toggle="tooltip" title="<?php echo __('add_inquiry'); ?>">
                    <i class="bi bi-flask"></i>
                </button>
                <button class="btn btn-sm btn-outline-dark" 
                        onclick="showXrayInquiryModalFromVisit(<?php echo $v['id']; ?>, <?php echo $v['patient_id']; ?>, <?php echo $patient_name_json; ?>)"
                        data-bs-toggle="tooltip" title="<?php echo __('add_xray_inquiry'); ?>">
                    <i class="bi bi-camera"></i>
                </button>
                <button class="btn btn-sm btn-outline-primary" 
                        onclick="showReportModal(<?php echo $v['id']; ?>)"
                        data-bs-toggle="tooltip" title="<?php echo __('new_report'); ?>">
                    <i class="bi bi-file-earmark-plus"></i>
                </button>
                <button class="btn btn-sm btn-outline-success" 
                        onclick="showBillModal(<?php echo $v['id']; ?>, <?php echo $v['patient_id']; ?>, <?php echo $patient_name_json; ?>)"
                        data-bs-toggle="tooltip" title="<?php echo __('create_bill'); ?>">
                    <i class="bi bi-receipt"></i>
                </button>
                <a href="print_prescription.php?visit_id=<?php echo $v['id']; ?>" target="_blank" 
                    class="btn btn-sm btn-outline-dark"
                    data-bs-toggle="tooltip" title="<?php echo __('print_prescription'); ?>">
                    <i class="bi bi-printer"></i>
                </a>
                <?php if (!empty($v['sick_leave_start_date']) && !empty($v['sick_leave_days'])): ?>
                <a href="print_sick_leave.php?visit_id=<?php echo $v['id']; ?>" target="_blank" 
                    class="btn btn-sm btn-outline-danger"
                    data-bs-toggle="tooltip" title="<?php echo __('print_sick_leave'); ?>">
                    <i class="bi bi-file-medical"></i>
                </a>
                <?php endif; ?>
            </div>
        </td>
    </tr>
    <?php endforeach; ?>
    <?php endif; 
    $table_html = ob_get_clean();

    ob_start();
    if ($totalPages > 1): ?>
    <div class="d-flex justify-content-between align-items-center p-3 border-top">
        <div class="text-muted small">
            <?php echo __('showing'); ?> <?php echo $offset + 1; ?> - <?php echo min($offset + $limit, $totalVisits); ?> <?php echo __('of'); ?> <?php echo $totalVisits; ?>
        </div>
        <nav aria-label="Page navigation">
            <ul class="pagination pagination-sm mb-0">
                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="#" data-page="<?php echo $page - 1; ?>" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                <?php
                $range = 2;
                $pages_to_show = [];
                $pages_to_show[] = 1;
                if ($totalPages > 1) { $pages_to_show[] = $totalPages; }
                for ($i = $page - $range; $i <= $page + $range; $i++) {
                    if ($i > 1 && $i < $totalPages) { $pages_to_show[] = $i; }
                }
                $pages_to_show = array_unique($pages_to_show);
                sort($pages_to_show);
                
                $prev_page = 0;
                foreach ($pages_to_show as $p):
                    if ($prev_page > 0 && $p > $prev_page + 1): ?>
                        <li class="page-item disabled"><span class="page-link">...</span></li>
                    <?php endif; ?>
                    <li class="page-item <?php echo $page == $p ? 'active' : ''; ?>">
                        <a class="page-link" href="#" data-page="<?php echo $p; ?>">
                            <?php echo $p; ?>
                        </a>
                    </li>
                    <?php 
                    $prev_page = $p;
                endforeach; 
                ?>
                <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="#" data-page="<?php echo $page + 1; ?>" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            </ul>
        </nav>
    </div>
    <?php endif; 
    $pagination_html = ob_get_clean();

    header('Content-Type: application/json');
    echo json_encode(['html' => $table_html, 'pagination' => $pagination_html]);
    exit;
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="fw-bold text-secondary"><?php echo __('visits'); ?></h3>
    <button class="btn btn-info shadow-sm text-white" data-bs-toggle="modal" data-bs-target="#recordVisitModal">
        <i class="bi bi-plus-lg me-1"></i> <?php echo __('add_visit'); ?>
    </button>
</div>

<!-- Search Bar -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <form id="visitsSearchForm" class="row g-3" onsubmit="return false;">
            <div class="col-md-3">
                <div class="input-group">
                    <span class="input-group-text bg-light border-end-0 text-muted"><i class="bi bi-search"></i></span>
                    <input type="text" name="patient" id="visitSearchPatient" class="form-control bg-light border-start-0" placeholder="<?php echo __('patient'); ?>" value="<?php echo htmlspecialchars($search_patient); ?>">
                </div>
            </div>
            <div class="col-md-3">
                <div class="input-group">
                    <span class="input-group-text bg-light border-end-0 text-muted"><i class="bi bi-person-badge"></i></span>
                    <input type="text" name="doctor" id="visitSearchDoctor" class="form-control bg-light border-start-0" placeholder="<?php echo __('doctor'); ?>" value="<?php echo htmlspecialchars($search_doctor); ?>">
                </div>
            </div>
            <div class="col-md-4">
                <div class="input-group">
                    <span class="input-group-text bg-light border-end-0 text-muted"><i class="bi bi-calendar-event"></i></span>
                    <input type="date" name="date" id="visitSearchDate" class="form-control bg-light border-start-0" value="<?php echo htmlspecialchars($search_date); ?>">
                </div>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-secondary w-100" onclick="fetchVisits(1)"><?php echo __('search'); ?></button>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light text-secondary">
                    <tr>
                        <th class="px-4 py-3">#</th>
                        <th class="py-3"><?php echo __('date'); ?></th>
                        <th class="py-3"><?php echo __('patient'); ?></th>
                        <th class="py-3"><?php echo __('doctor'); ?></th>
                        <th class="py-3"><?php echo __('diagnosis'); ?></th>
                        <th class="py-3"><?php echo __('vitals'); ?></th>
                        <th class="py-3"><?php echo __('treatment'); ?></th>
                        <th class="py-3"><?php echo __('inquiries'); ?></th>
                        <th class="py-3 text-end px-4"><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody id="visitsTableBody">
                    <?php if (empty($visits)): ?>
                    <tr>
                        <td colspan="9" class="text-center py-5 text-muted">
                            <i class="bi bi-clipboard2-pulse display-4 d-block mb-3"></i>
                            <?php echo __('no_visits_found'); ?>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($visits as $v): ?>
                    <tr>
                        <td class="px-4 text-muted small">
                            <?php echo $v['id']; ?>
                            <?php if (($v['visit_type'] ?? 'Clinic') === 'Home'): ?>
                                <br><span class="badge bg-warning text-dark"><i class="bi bi-house"></i> Home</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-secondary"><?php echo date('Y-m-d H:i', strtotime($v['visit_date'])); ?></td>
                        <td class="fw-semibold text-dark">
                            <?php echo htmlspecialchars($v['patient_name'] ?? ''); ?>
                            <?php if (!empty($v['address'])): ?>
                                <br><small class="text-muted"><i class="bi bi-geo-alt"></i> <?php echo htmlspecialchars($v['address']); ?></small>
                            <?php endif; ?>
                        </td>
                        <td class="text-secondary">
                            <?php 
                            if (!empty($v['doctor_name'])) {
                                echo htmlspecialchars($v['doctor_name']); 
                            } elseif (!empty($v['nurse_name'])) {
                                echo htmlspecialchars($v['nurse_name']) . ' <small class="text-muted">(' . __('nurse') . ')</small>';
                            }
                            ?>
                        </td>
                        <td>
                            <?php 
                            $diagnosis_plain = strip_tags($v['diagnosis'] ?? '');
                            $snippet = mb_strimwidth($diagnosis_plain, 0, 30, "...");
                            ?>
                            <small class="text-muted" title="<?php echo htmlspecialchars($diagnosis_plain); ?>"><?php echo htmlspecialchars($snippet); ?></small>
                        </td>
                        <td>
                            <?php 
                                $vitals = [];
                                if(!empty($v['blood_pressure'])) $vitals[] = '<i class="bi bi-heart-pulse me-1"></i>' . htmlspecialchars($v['blood_pressure'] ?? '');
                                if(!empty($v['weight'])) $vitals[] = '<i class="bi bi-speedometer2 me-1"></i>' . htmlspecialchars($v['weight'] ?? '') . 'kg';
                                if(!empty($v['temperature'])) $vitals[] = '<i class="bi bi-thermometer-half me-1"></i>' . htmlspecialchars($v['temperature'] ?? '') . '°C';
                                echo implode('<br>', $vitals);
                            ?>
                        </td>
                         <td>
                            <?php 
                            $treatment_plain = strip_tags($v['treatment_plan'] ?? '');
                            $t_snippet = mb_strimwidth($treatment_plain, 0, 30, "...");
                            ?>
                            <small class="text-muted" title="<?php echo htmlspecialchars($treatment_plain); ?>"><?php echo htmlspecialchars($t_snippet); ?></small>
                        </td>
                        <td>
                            <div class="d-flex gap-1">
                                <?php if (!empty($v['lab_inquiries'])): ?> 
                                    <span class="badge bg-info text-white" title="<?php echo count($v['lab_inquiries']); ?> <?php echo __('laboratory'); ?>" data-bs-toggle="tooltip">
                                        <i class="bi bi-flask"></i> <?php echo count($v['lab_inquiries']); ?>
                                    </span>
                                <?php endif; ?> 
                                <?php if (!empty($v['xray_inquiries'])): ?> 
                                    <span class="badge bg-dark text-white" title="<?php echo count($v['xray_inquiries']); ?> <?php echo __('xray'); ?>" data-bs-toggle="tooltip">
                                        <i class="bi bi-camera"></i> <?php echo count($v['xray_inquiries']); ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td class="text-end px-4">
                            <div class="d-flex justify-content-end gap-1">
                                <?php 
                                // Encode safely for attribute
                                $json_v = htmlspecialchars(json_encode($v, JSON_UNESCAPED_UNICODE) ?: '{}', ENT_QUOTES, 'UTF-8');
                                $patient_name_json = htmlspecialchars(json_encode($v['patient_name'] ?? '', JSON_UNESCAPED_UNICODE) ?: '""', ENT_QUOTES, 'UTF-8');
                                ?>
                                <button class="btn btn-sm btn-outline-success" 
                                        onclick="showVisitResultsModal(JSON.parse(this.getAttribute('data-visit')))" 
                                        data-visit="<?php echo $json_v; ?>"
                                        data-bs-toggle="tooltip" title="<?php echo __('view_results'); ?>">
                                    <i class="bi bi-eye"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-warning" 
                                        onclick="showEditVisitModal(JSON.parse(this.getAttribute('data-visit')))"
                                        data-visit="<?php echo $json_v; ?>"
                                        data-bs-toggle="tooltip" title="<?php echo __('edit'); ?>">
                                    <i class="bi bi-pencil-square"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-info" 
                                        onclick="showLabInquiryModalFromVisit(<?php echo $v['id']; ?>, <?php echo $v['patient_id']; ?>, <?php echo $patient_name_json; ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('add_inquiry'); ?>">
                                    <i class="bi bi-flask"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-dark" 
                                        onclick="showXrayInquiryModalFromVisit(<?php echo $v['id']; ?>, <?php echo $v['patient_id']; ?>, <?php echo $patient_name_json; ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('add_xray_inquiry'); ?>">
                                    <i class="bi bi-camera"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-primary" 
                                        onclick="showReportModal(<?php echo $v['id']; ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('new_report'); ?>">
                                    <i class="bi bi-file-earmark-plus"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-success" 
                                        onclick="showBillModal(<?php echo $v['id']; ?>, <?php echo $v['patient_id']; ?>, <?php echo $patient_name_json; ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('create_bill'); ?>">
                                    <i class="bi bi-receipt"></i>
                                </button>
                                <a href="print_prescription.php?visit_id=<?php echo $v['id']; ?>" target="_blank" 
                                   class="btn btn-sm btn-outline-dark"
                                   data-bs-toggle="tooltip" title="<?php echo __('print_prescription'); ?>">
                                    <i class="bi bi-printer"></i>
                                </a>
                                <?php if (!empty($v['sick_leave_start_date']) && !empty($v['sick_leave_days'])): ?>
                                <a href="print_sick_leave.php?visit_id=<?php echo $v['id']; ?>" target="_blank" 
                                   class="btn btn-sm btn-outline-danger"
                                   data-bs-toggle="tooltip" title="<?php echo __('print_sick_leave'); ?>">
                                    <i class="bi bi-file-medical"></i>
                                </a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <div id="visitsPagination">
        <?php if ($totalPages > 1): ?>
        <div class="d-flex justify-content-between align-items-center p-3 border-top">
            <div class="text-muted small">
                <?php echo __('showing'); ?> <?php echo $offset + 1; ?> - <?php echo min($offset + $limit, $totalVisits); ?> <?php echo __('of'); ?> <?php echo $totalVisits; ?>
            </div>
            <nav aria-label="Page navigation">
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="#" data-page="<?php echo $page - 1; ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <?php
                    $range = 2;
                    $pages_to_show = [];
                    $pages_to_show[] = 1;
                    if ($totalPages > 1) { $pages_to_show[] = $totalPages; }
                    for ($i = $page - $range; $i <= $page + $range; $i++) {
                        if ($i > 1 && $i < $totalPages) { $pages_to_show[] = $i; }
                    }
                    $pages_to_show = array_unique($pages_to_show);
                    sort($pages_to_show);
                    
                    $prev_page = 0;
                    foreach ($pages_to_show as $p):
                        if ($prev_page > 0 && $p > $prev_page + 1): ?>
                            <li class="page-item disabled"><span class="page-link">...</span></li>
                        <?php endif; ?>
                        <li class="page-item <?php echo $page == $p ? 'active' : ''; ?>">
                            <a class="page-link" href="#" data-page="<?php echo $p; ?>">
                                <?php echo $p; ?>
                            </a>
                        </li>
                        <?php 
                        $prev_page = $p;
                    endforeach; 
                    ?>
                    <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="#" data-page="<?php echo $page + 1; ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const searchPatient = document.getElementById('visitSearchPatient');
    const searchDoctor = document.getElementById('visitSearchDoctor');
    const searchDate = document.getElementById('visitSearchDate');
    const paginationContainer = document.getElementById('visitsPagination');

    let timeout = null;

    function debounceSearch() {
        clearTimeout(timeout);
        timeout = setTimeout(() => fetchVisits(1), 300);
    }

    if (searchPatient) searchPatient.addEventListener('input', debounceSearch);
    if (searchDoctor) searchDoctor.addEventListener('input', debounceSearch);
    if (searchDate) searchDate.addEventListener('change', () => fetchVisits(1));

    if (paginationContainer) {
        paginationContainer.addEventListener('click', function(e) {
            e.preventDefault();
            const link = e.target.closest('.page-link');
            if (link && !link.parentElement.classList.contains('disabled')) {
                const page = link.getAttribute('data-page');
                if (page) fetchVisits(page);
            }
        });
    }
});

function fetchVisits(page) {
    const patient = document.getElementById('visitSearchPatient').value;
    const doctor = document.getElementById('visitSearchDoctor').value;
    const date = document.getElementById('visitSearchDate').value;
    const tableBody = document.getElementById('visitsTableBody');
    const paginationContainer = document.getElementById('visitsPagination');

    if (tableBody) tableBody.style.opacity = '0.5';

    const params = new URLSearchParams();
    if (patient) params.append('patient', patient);
    if (doctor) params.append('doctor', doctor);
    if (date) params.append('date', date);
    params.append('page', page);
    params.append('ajax_search', '1');

    fetch('visits.php?' + params.toString())
        .then(response => response.json())
        .then(data => {
            if (tableBody) {
                tableBody.innerHTML = data.html;
                tableBody.style.opacity = '1';
            }
            if (paginationContainer) {
                paginationContainer.innerHTML = data.pagination;
            }
            // Re-initialize tooltips
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl)
            })
        })
        .catch(error => {
            console.error('Error fetching visits:', error);
            if (tableBody) tableBody.style.opacity = '1';
        });
}
</script>