<?php
// Pagination Logic
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

$where_clause = "";
$params = [];

if ($search) {
    $where_clause = "WHERE name_en LIKE ? OR name_ar LIKE ?";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

// Total count
$count_query = "SELECT COUNT(*) FROM xray_groups $where_clause";
$stmt = $db->prepare($count_query);
$stmt->execute($params);
$total_records = $stmt->fetchColumn();
$total_pages = ceil($total_records / $limit);

// Fetch data
$query = "SELECT * FROM xray_groups $where_clause ORDER BY id DESC LIMIT $limit OFFSET $offset";
$stmt = $db->prepare($query);
$stmt->execute($params);
$groups = $stmt->fetchAll();

// Handle AJAX Request
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
    ob_start();
?>
    <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 __('name_en'); ?></th>
                <th class="py-3"><?php echo __('name_ar'); ?></th>
                <th class="py-3 text-end px-4"><?php echo __('actions'); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($groups)): ?>
            <tr>
                <td colspan="4" class="text-center py-5 text-muted">
                    <i class="bi bi-collection display-4 d-block mb-3"></i>
                    <?php echo __('no_data_found'); ?>
                </td>
            </tr>
            <?php else: ?>
            <?php foreach ($groups as $group): ?>
            <tr>
                <td class="px-4 text-secondary"><?php echo $group['id']; ?></td>
                <td class="fw-semibold text-dark"><?php echo htmlspecialchars($group['name_en']); ?></td>
                <td class="text-secondary"><?php echo htmlspecialchars($group['name_ar']); ?></td>
                <td class="text-end px-4">
                    <div class="btn-group shadow-sm border rounded bg-white">
                        <button class="btn btn-link text-primary py-1 px-2 border-end" 
                                onclick="showEditXrayGroupModal(<?php echo htmlspecialchars(json_encode($group, 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-danger py-1 px-2" 
                                onclick="showDeleteXrayGroupModal(<?php echo $group['id']; ?>)"
                                data-bs-toggle="tooltip" title="<?php echo __('delete'); ?>">
                            <i class="bi bi-trash3"></i>
                        </button>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
    
    <!-- Pagination Controls -->
    <?php if ($total_pages > 1): ?>
    <div class="d-flex justify-content-between align-items-center p-3 border-top bg-light">
        <div class="small text-muted">
            <?php echo __('showing'); ?> <?php echo $offset + 1; ?> <?php echo __('to'); ?> <?php echo min($offset + $limit, $total_records); ?> <?php echo __('of'); ?> <?php echo $total_records; ?> <?php echo __('entries'); ?>
        </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="#" onclick="loadPage(<?php echo $page - 1; ?>); return false;">
                        <i class="bi bi-chevron-left"></i>
                    </a>
                </li>
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <li class="page-item <?php echo $page == $i ? 'active' : ''; ?>">
                    <a class="page-link" href="#" onclick="loadPage(<?php echo $i; ?>); return false;"><?php echo $i; ?></a>
                </li>
                <?php endfor; ?>
                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="#" onclick="loadPage(<?php echo $page + 1; ?>); return false;">
                        <i class="bi bi-chevron-right"></i>
                    </a>
                </li>
            </ul>
        </nav>
    </div>
    <?php endif; ?>
<?php
    $html = ob_get_clean();
    header('Content-Type: application/json');
    echo json_encode(['html' => $html]);
    exit;
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="fw-bold text-secondary"><?php echo __('xray_groups'); ?></h3>
    <div class="d-flex gap-2">
        <div class="input-group shadow-sm" style="width: 250px;">
            <span class="input-group-text bg-white border-end-0"><i class="bi bi-search text-muted"></i></span>
            <input type="text" id="searchInput" class="form-control border-start-0 ps-0" placeholder="<?php echo __('search'); ?>..." onkeyup="debounceSearch()">
        </div>
        <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#addXrayGroupModal" onclick="resetXrayGroupModal()">
            <i class="bi bi-plus-lg me-1"></i> <?php echo __('add_xray_group'); ?>
        </button>
    </div>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body p-0">
        <div class="table-responsive" id="tableContainer">
            <!-- Initial Table Load -->
            <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 __('name_en'); ?></th>
                        <th class="py-3"><?php echo __('name_ar'); ?></th>
                        <th class="py-3 text-end px-4"><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($groups)): ?>
                    <tr>
                        <td colspan="4" class="text-center py-5 text-muted">
                            <i class="bi bi-collection display-4 d-block mb-3"></i>
                            <?php echo __('no_data_found'); ?>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($groups as $group): ?>
                    <tr>
                        <td class="px-4 text-secondary"><?php echo $group['id']; ?></td>
                        <td class="fw-semibold text-dark"><?php echo htmlspecialchars($group['name_en']); ?></td>
                        <td class="text-secondary"><?php echo htmlspecialchars($group['name_ar']); ?></td>
                        <td class="text-end px-4">
                            <div class="btn-group shadow-sm border rounded bg-white">
                                <button class="btn btn-link text-primary py-1 px-2 border-end" 
                                        onclick="showEditXrayGroupModal(<?php echo htmlspecialchars(json_encode($group, 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-danger py-1 px-2" 
                                        onclick="showDeleteXrayGroupModal(<?php echo $group['id']; ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('delete'); ?>">
                                    <i class="bi bi-trash3"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            
             <!-- Pagination Controls (Initial) -->
            <?php if ($total_pages > 1): ?>
            <div class="d-flex justify-content-between align-items-center p-3 border-top bg-light">
                <div class="small text-muted">
                    <?php echo __('showing'); ?> <?php echo $offset + 1; ?> <?php echo __('to'); ?> <?php echo min($offset + $limit, $total_records); ?> <?php echo __('of'); ?> <?php echo $total_records; ?> <?php echo __('entries'); ?>
                </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="#" onclick="loadPage(<?php echo $page - 1; ?>); return false;">
                                <i class="bi bi-chevron-left"></i>
                            </a>
                        </li>
                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php echo $page == $i ? 'active' : ''; ?>">
                            <a class="page-link" href="#" onclick="loadPage(<?php echo $i; ?>); return false;"><?php echo $i; ?></a>
                        </li>
                        <?php endfor; ?>
                        <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                            <a class="page-link" href="#" onclick="loadPage(<?php echo $page + 1; ?>); return false;">
                                <i class="bi bi-chevron-right"></i>
                            </a>
                        </li>
                    </ul>
                </nav>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Add/Edit Xray Group Modal -->
<div class="modal fade" id="addXrayGroupModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="groupModalTitle"><?php echo __('add_xray_group'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="action" id="groupAction" value="add_xray_group">
                <input type="hidden" name="id" id="groupId">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_en'); ?> <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name_en" id="groupNameEn" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_ar'); ?> <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name_ar" id="groupNameAr" required>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('close'); ?></button>
                    <button type="submit" class="btn btn-primary"><?php echo __('save'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Xray Group Modal -->
<div class="modal fade" id="deleteXrayGroupModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><?php echo __('delete_xray_group'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="action" value="delete_xray_group">
                <input type="hidden" name="id" id="deleteGroupId">
                <div class="modal-body p-4 text-center">
                    <div class="mb-3 text-danger">
                        <i class="bi bi-exclamation-triangle display-1"></i>
                    </div>
                    <p class="mb-0 fs-5"><?php echo __('are_you_sure_delete'); ?></p>
                    <p class="text-muted small"><?php echo __('action_cannot_be_undone'); ?></p>
                </div>
                <div class="modal-footer bg-light justify-content-center">
                    <button type="button" class="btn btn-secondary px-4" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-danger px-4"><?php echo __('delete'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
let searchTimeout;

function debounceSearch() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
        loadPage(1);
    }, 300);
}

function loadPage(page) {
    const search = document.getElementById('searchInput').value;
    const url = `xray_groups.php?page=${page}&search=${encodeURIComponent(search)}`;
    
    fetch(url, {
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('tableContainer').innerHTML = data.html;
    })
    .catch(error => console.error('Error:', error));
}

function resetXrayGroupModal() {
    document.getElementById('groupModalTitle').textContent = '<?php echo __('add_xray_group'); ?>';
    document.getElementById('groupAction').value = 'add_xray_group';
    document.getElementById('groupId').value = '';
    
    document.getElementById('groupNameEn').value = '';
    document.getElementById('groupNameAr').value = '';
}

function showEditXrayGroupModal(group) {
    document.getElementById('groupModalTitle').textContent = '<?php echo __('edit_xray_group'); ?>';
    document.getElementById('groupAction').value = 'edit_xray_group';
    document.getElementById('groupId').value = group.id;
    
    document.getElementById('groupNameEn').value = group.name_en;
    document.getElementById('groupNameAr').value = group.name_ar;
    
    var modal = new bootstrap.Modal(document.getElementById('addXrayGroupModal'));
    modal.show();
}

function showDeleteXrayGroupModal(id) {
    document.getElementById('deleteGroupId').value = id;
    var modal = new bootstrap.Modal(document.getElementById('deleteXrayGroupModal'));
    modal.show();
}
</script>