<?php
$search_query = $_GET['search'] ?? '';
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Build Query
$where = "WHERE 1=1";
$params = [];

if ($search_query) {
    $where .= " AND (p.name LIKE ? OR p.phone LIKE ?)";
    $params[] = "%$search_query%";
    $params[] = "%$search_query%";
}

// Count Total
$countQuery = "SELECT COUNT(*) FROM patients p $where";
$stmt = $db->prepare($countQuery);
$stmt->execute($params);
$totalPatients = $stmt->fetchColumn();
$totalPages = ceil($totalPatients / $limit);

// Fetch Data
$query = "
    SELECT p.*, ic.name_$lang as insurance_name 
    FROM patients p 
    LEFT JOIN insurance_companies ic ON p.insurance_company_id = ic.id 
    $where
    ORDER BY p.id DESC
    LIMIT $limit OFFSET $offset";

$stmt = $db->prepare($query);
$stmt->execute($params);
$patients = $stmt->fetchAll();

// --- AJAX HANDLER ---
if (isset($_GET['ajax_search'])) {
    ob_start();
    if (empty($patients)):
    ?>
    <tr>
        <td colspan="6" class="text-center py-5 text-muted">
            <i class="bi bi-people display-4 d-block mb-3"></i>
            <?php echo __('no_patients_found'); ?>
        </td>
    </tr>
    <?php else: ?>
    <?php foreach ($patients as $p): ?>
    <tr>
        <td class="px-4 text-secondary">
                            <?php echo str_pad($p['id'], 6, '0', STR_PAD_LEFT); ?>
                        </td>
                        <td class="px-4">
            <div class="fw-semibold text-dark"><?php echo htmlspecialchars($p['name']); ?></div>
            <small class="text-muted"><?php echo $p['dob']; ?></small>
        </td>
        <td><?php echo calculate_age($p['dob']); ?></td>
        <td><?php echo htmlspecialchars($p['phone']); ?></td>
        <td>
            <span class="badge <?php echo $p['insurance_name'] ? 'bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25' : 'bg-secondary bg-opacity-10 text-secondary border border-secondary border-opacity-25'; ?> px-2 py-1">
                <?php echo $p['insurance_name'] ?: __('not_insured'); ?>
            </span>
        </td>
        <td class="text-secondary"><?php echo htmlspecialchars($p['policy_number'] ?: '-'); ?></td>
        <td class="text-end px-4">
            <div class="btn-group shadow-sm border rounded bg-white">
                                <a href="print_patient_label.php?id=<?php echo $p['id']; ?>" target="_blank" class="btn btn-link text-dark py-1 px-2 border-end" 
                                   data-bs-toggle="tooltip" title="<?php echo __('print'); ?>">
                                    <i class="bi bi-upc-scan"></i>
                                </a>
                                <button class="btn btn-link text-primary py-1 px-2 border-end" 
                        onclick="showEditPatientModal(<?php echo htmlspecialchars(json_encode($p, JSON_UNESCAPED_UNICODE)); ?>)"
                        data-bs-toggle="tooltip" title="<?php echo __('edit'); ?>">
                    <i class="bi bi-pencil-square"></i>
                </button>
                <button class="btn btn-link text-info py-1 px-2 border-end" 
                        onclick="showRecordVisitModal(<?php echo $p['id']; ?>)"
                        data-bs-toggle="tooltip" title="<?php echo __('add_visit'); ?>">
                    <i class="bi bi-clipboard2-plus"></i>
                </button>
                <button class="btn btn-link text-success py-1 px-2 border-end" 
                        onclick="showBillModal(null, <?php echo $p['id']; ?>, <?php echo htmlspecialchars(json_encode($p['name'], JSON_UNESCAPED_UNICODE)); ?>)"
                        data-bs-toggle="tooltip" title="<?php echo __('add_bill'); ?>">
                    <i class="bi bi-receipt"></i>
                </button>
                <button class="btn btn-link text-danger py-1 px-2" 
                        onclick="showDeletePatientModal(<?php echo $p['id']; ?>, <?php echo htmlspecialchars(json_encode($p['name'], JSON_UNESCAPED_UNICODE)); ?>)"
                        data-bs-toggle="tooltip" title="<?php echo __('delete'); ?>">
                    <i class="bi bi-trash3"></i>
                </button>
            </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, $totalPatients); ?> <?php echo __('of'); ?> <?php echo $totalPatients; ?>
        </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="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search_query); ?>" 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="?page=<?php echo $p; ?>&search=<?php echo urlencode($search_query); ?>">
                            <?php echo $p; ?>
                        </a>
                    </li>
                    <?php 
                    $prev_page = $p;
                endforeach; 
                ?>
                <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search_query); ?>" 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 __('patients'); ?></h3>
    <div class="d-flex gap-2">
        <button class="btn btn-success shadow-sm" data-bs-toggle="modal" data-bs-target="#importPatientsModal">
            <i class="bi bi-file-earmark-excel me-1"></i> <?php echo __("import_excel"); ?>
        </button>
        <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#addPatientModal">
        <i class="bi bi-person-plus me-1"></i> <?php echo __('add_patient'); ?>
    </button>
    </div>
</div>

<!-- Search Bar -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <form method="GET" action="" class="row g-3">
            <div class="col-md-10">
                <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="search" id="patientSearchInput" class="form-control bg-light border-start-0" placeholder="<?php echo __('name') . ' ' . __('or') . ' ' . __('phone'); ?>" value="<?php echo htmlspecialchars($search_query); ?>" autocomplete="off">
                </div>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-secondary w-100"><?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"><?php echo __('patient_number'); ?></th>
                        <th class="px-4 py-3"><?php echo __('name'); ?></th>
                        <th class="py-3"><?php echo __('age'); ?></th>
                        <th class="py-3"><?php echo __('phone'); ?></th>
                        <th class="py-3"><?php echo __('insurance'); ?></th>
                        <th class="py-3"><?php echo __('policy_number'); ?></th>
                        <th class="py-3 text-end px-4"><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody id="patientsTableBody">
                    <?php if (empty($patients)): ?>
                    <tr>
                        <td colspan="6" class="text-center py-5 text-muted">
                            <i class="bi bi-people display-4 d-block mb-3"></i>
                            <?php echo __('no_patients_found'); ?>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($patients as $p): ?>
                    <tr>
                        <td class="px-4 text-secondary">
                            <?php echo str_pad($p['id'], 6, '0', STR_PAD_LEFT); ?>
                        </td>
                        <td class="px-4">
                            <div class="fw-semibold text-dark"><?php echo htmlspecialchars($p['name']); ?></div>
                            <small class="text-muted"><?php echo $p['dob']; ?></small>
                        </td>
                        <td><?php echo calculate_age($p['dob']); ?></td>
                        <td><?php echo htmlspecialchars($p['phone']); ?></td>
                        <td>
                            <span class="badge <?php echo $p['insurance_name'] ? 'bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25' : 'bg-secondary bg-opacity-10 text-secondary border border-secondary border-opacity-25'; ?> px-2 py-1">
                                <?php echo $p['insurance_name'] ?: __('not_insured'); ?>
                            </span>
                        </td>
                        <td class="text-secondary"><?php echo htmlspecialchars($p['policy_number'] ?: '-'); ?></td>
                        <td class="text-end px-4">
                            <div class="btn-group shadow-sm border rounded bg-white">
                                <a href="print_patient_label.php?id=<?php echo $p['id']; ?>" target="_blank" class="btn btn-link text-dark py-1 px-2 border-end" 
                                   data-bs-toggle="tooltip" title="<?php echo __('print'); ?>">
                                    <i class="bi bi-upc-scan"></i>
                                </a>
                                <button class="btn btn-link text-primary py-1 px-2 border-end" 
                                        onclick="showEditPatientModal(<?php echo htmlspecialchars(json_encode($p, JSON_UNESCAPED_UNICODE)); ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('edit'); ?>">
                                    <i class="bi bi-pencil-square"></i>
                                </button>
                                <button class="btn btn-link text-info py-1 px-2 border-end" 
                                        onclick="showRecordVisitModal(<?php echo $p['id']; ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('add_visit'); ?>">
                                    <i class="bi bi-clipboard2-plus"></i>
                                </button>
                                <button class="btn btn-link text-success py-1 px-2 border-end" 
                                        onclick="showBillModal(null, <?php echo $p['id']; ?>, <?php echo htmlspecialchars(json_encode($p['name'], JSON_UNESCAPED_UNICODE)); ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('add_bill'); ?>">
                                    <i class="bi bi-receipt"></i>
                                </button>
                                <button class="btn btn-link text-danger py-1 px-2" 
                                        onclick="showDeletePatientModal(<?php echo $p['id']; ?>, <?php echo htmlspecialchars(json_encode($p['name'], JSON_UNESCAPED_UNICODE)); ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('delete'); ?>">
                                    <i class="bi bi-trash3"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <div id="patientsPagination">
        <?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, $totalPatients); ?> <?php echo __('of'); ?> <?php echo $totalPatients; ?>
            </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="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search_query); ?>" 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="?page=<?php echo $p; ?>&search=<?php echo urlencode($search_query); ?>">
                                <?php echo $p; ?>
                            </a>
                        </li>
                        <?php 
                        $prev_page = $p;
                    endforeach; 
                    ?>
                    <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search_query); ?>" 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 searchInput = document.getElementById('patientSearchInput');
    const tableBody = document.getElementById('patientsTableBody');
    const paginationContainer = document.getElementById('patientsPagination');

    let timeout = null;

    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const query = this.value.trim();

            // Search after 2 chars or if cleared
            if (query.length >= 2 || query.length === 0) {
                clearTimeout(timeout);
                timeout = setTimeout(() => {
                    fetchPatients(query);
                }, 300);
            }
        });
    }

    function fetchPatients(query) {
        if (tableBody) tableBody.style.opacity = '0.5';
        
        const params = new URLSearchParams();
        if (query) params.append('search', query);
        params.append('ajax_search', '1');

        fetch('patients.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 patients:', error);
                if (tableBody) tableBody.style.opacity = '1';
            });
    }
});
</script>
