<?php
$search_name = $_GET['name'] ?? '';
$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_name) {
    $where .= " AND (name_en LIKE ? OR name_ar LIKE ?)";
    $params[] = "%$search_name%";
    $params[] = "%$search_name%";
}

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

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

// --- AJAX HANDLER ---
if (isset($_GET['ajax_search'])) {
    ob_start();
    if (empty($departments)):
    ?>
    <tr>
        <td colspan="6" class="text-center py-5 text-muted">
            <i class="bi bi-diagram-3 display-4 d-block mb-3"></i>
            <?php echo __('no_departments_found'); ?>
        </td>
    </tr>
    <?php else: ?>
    <?php foreach ($departments as $dept): ?>
    <tr>
        <td class="px-4 text-secondary"><?php echo $dept['id']; ?></td>
        <td class="fw-semibold text-dark"><?php echo htmlspecialchars($dept['name_en']); ?></td>
        <td class="text-secondary"><?php echo htmlspecialchars($dept['name_ar']); ?></td>
        <td class="text-center">
            <?php if ($dept['active']): ?>
                <span class="badge bg-success-subtle text-success rounded-pill px-3"><?php echo __('active'); ?></span>
            <?php else: ?>
                <span class="badge bg-secondary-subtle text-secondary rounded-pill px-3"><?php echo __('inactive'); ?></span>
            <?php endif; ?>
        </td>
        <td class="text-center">
            <?php if ($dept['show_in_queue']): ?>
                <span class="badge bg-info-subtle text-info rounded-pill px-3"><?php echo __('yes'); ?></span>
            <?php else: ?>
                <span class="badge bg-secondary-subtle text-secondary rounded-pill px-3"><?php echo __('no'); ?></span>
            <?php endif; ?>
        </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="showEditDepartmentModal(<?php echo htmlspecialchars(json_encode($dept, 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="showDeleteDepartmentModal(<?php echo $dept['id']; ?>)"
                        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, $totalDepartments); ?> <?php echo __('of'); ?> <?php echo $totalDepartments; ?>
        </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 __('departments'); ?></h3>
    <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#addDepartmentModal" onclick="resetDepartmentModal()">
        <i class="bi bi-plus-lg me-1"></i> <?php echo __('add_department'); ?>
    </button>
</div>

<!-- Search Bar -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <form id="departmentsSearchForm" class="row g-3" onsubmit="return false;">
            <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="name" id="deptSearchName" class="form-control bg-light border-start-0" placeholder="<?php echo __('name'); ?>" value="<?php echo htmlspecialchars($search_name); ?>">
                </div>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-secondary w-100" onclick="fetchDepartments(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 __('name_en'); ?></th>
                        <th class="py-3"><?php echo __('name_ar'); ?></th>
                        <th class="py-3 text-center"><?php echo __('active'); ?></th>
                        <th class="py-3 text-center"><?php echo __('show_in_queue'); ?></th>
                        <th class="py-3 text-end px-4"><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody id="departmentsTableBody">
                    <?php if (empty($departments)): ?>
                    <tr>
                        <td colspan="6" class="text-center py-5 text-muted">
                            <i class="bi bi-diagram-3 display-4 d-block mb-3"></i>
                            <?php echo __('no_departments_found'); ?>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($departments as $dept): ?>
                    <tr>
                        <td class="px-4 text-secondary"><?php echo $dept['id']; ?></td>
                        <td class="fw-semibold text-dark"><?php echo htmlspecialchars($dept['name_en']); ?></td>
                        <td class="text-secondary"><?php echo htmlspecialchars($dept['name_ar']); ?></td>
                        <td class="text-center">
                            <?php if ($dept['active']): ?>
                                <span class="badge bg-success-subtle text-success rounded-pill px-3"><?php echo __('active'); ?></span>
                            <?php else: ?>
                                <span class="badge bg-secondary-subtle text-secondary rounded-pill px-3"><?php echo __('inactive'); ?></span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center">
                            <?php if ($dept['show_in_queue']): ?>
                                <span class="badge bg-info-subtle text-info rounded-pill px-3"><?php echo __('yes'); ?></span>
                            <?php else: ?>
                                <span class="badge bg-secondary-subtle text-secondary rounded-pill px-3"><?php echo __('no'); ?></span>
                            <?php endif; ?>
                        </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="showEditDepartmentModal(<?php echo htmlspecialchars(json_encode($dept, 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="showDeleteDepartmentModal(<?php echo $dept['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>
        </div>
        
        <!-- Pagination -->
        <div id="departmentsPagination">
        <?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, $totalDepartments); ?> <?php echo __('of'); ?> <?php echo $totalDepartments; ?>
            </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>

<!-- Add/Edit Department Modal -->
<div class="modal fade" id="addDepartmentModal" 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="deptModalTitle"><?php echo __('add_department'); ?></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="deptAction" value="add_department">
                <input type="hidden" name="id" id="deptId">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_en'); ?> <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="name_en" id="deptNameEn" required>
                            <button type="button" class="btn btn-outline-secondary" onclick="translateDepartment('en', 'ar')" title="<?php echo __('auto_translate'); ?>">
                                <i class="bi bi-translate"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_ar'); ?> <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="name_ar" id="deptNameAr" required>
                            <button type="button" class="btn btn-outline-secondary" onclick="translateDepartment('ar', 'en')" title="<?php echo __('auto_translate'); ?>">
                                <i class="bi bi-translate"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mb-3 form-check form-switch">
                        <input type="checkbox" class="form-check-input" name="active" id="deptActive" value="1" checked>
                        <label class="form-check-label" for="deptActive"><?php echo __('active'); ?></label>
                    </div>
                    <div class="mb-3 form-check form-switch">
                        <input type="checkbox" class="form-check-input" name="show_in_queue" id="deptShowInQueue" value="1" checked>
                        <label class="form-check-label" for="deptShowInQueue"><?php echo __('show_in_queue'); ?></label>
                    </div>
                    <div class="mb-3 form-check form-switch">
                        <input type="checkbox" class="form-check-input" name="requires_vitals" id="deptRequiresVitals" value="1">
                        <label class="form-check-label" for="deptRequiresVitals"><?php echo __('requires_vitals'); ?> <small class="text-muted">(<?php echo __('routes_to_vitals_first'); ?>)</small></label>
                    </div>
                    <div class="mb-3 form-check form-switch">
                        <input type="checkbox" class="form-check-input" name="is_vitals_room" id="deptIsVitalsRoom" value="1">
                        <label class="form-check-label" for="deptIsVitalsRoom"><?php echo __('is_vitals_room'); ?></label>
                    </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 Department Modal -->
<div class="modal fade" id="deleteDepartmentModal" 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_department'); ?></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_department">
                <input type="hidden" name="id" id="deleteDeptId">
                <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>
document.addEventListener('DOMContentLoaded', function() {
    const searchName = document.getElementById('deptSearchName');
    const paginationContainer = document.getElementById('departmentsPagination');

    let timeout = null;

    if (searchName) {
        searchName.addEventListener('input', function() {
            clearTimeout(timeout);
            timeout = setTimeout(() => fetchDepartments(1), 300);
        });
    }

    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) fetchDepartments(page);
            }
        });
    }
});

function fetchDepartments(page) {
    const name = document.getElementById('deptSearchName').value;
    const tableBody = document.getElementById('departmentsTableBody');
    const paginationContainer = document.getElementById('departmentsPagination');

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

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

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

function resetDepartmentModal() {
    document.getElementById('deptModalTitle').textContent = '<?php echo __('add_department'); ?>';
    document.getElementById('deptAction').value = 'add_department';
    document.getElementById('deptId').value = '';
    
    document.getElementById('deptNameEn').value = '';
    document.getElementById('deptNameAr').value = '';
    document.getElementById('deptActive').checked = true;
    document.getElementById('deptShowInQueue').checked = true;
    document.getElementById('deptRequiresVitals').checked = false;
    document.getElementById('deptIsVitalsRoom').checked = false;
}

function showEditDepartmentModal(dept) {
    document.getElementById('deptModalTitle').textContent = '<?php echo __('edit_department'); ?>';
    document.getElementById('deptAction').value = 'edit_department';
    document.getElementById('deptId').value = dept.id;
    
    document.getElementById('deptNameEn').value = dept.name_en;
    document.getElementById('deptNameAr').value = dept.name_ar;
    document.getElementById('deptActive').checked = (dept.active == 1);
    document.getElementById('deptShowInQueue').checked = (dept.show_in_queue == 1);
    document.getElementById('deptRequiresVitals').checked = (dept.requires_vitals == 1);
    document.getElementById('deptIsVitalsRoom').checked = (dept.is_vitals_room == 1);
    
    var modal = new bootstrap.Modal(document.getElementById('addDepartmentModal'));
    modal.show();
}

function showDeleteDepartmentModal(id) {
    document.getElementById('deleteDeptId').value = id;
    var modal = new bootstrap.Modal(document.getElementById('deleteDepartmentModal'));
    modal.show();
}

async function translateDepartment(source, target) {
    const text = document.getElementById(source === 'en' ? 'deptNameEn' : 'deptNameAr').value;
    if (!text) return;
    
    const btn = event.currentTarget;
    const originalContent = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
    
    try {
        const response = await fetch('api/ai_report.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                target: 'translate',
                text: text,
                from: source === 'en' ? 'English' : 'Arabic',
                to: target === 'en' ? 'English' : 'Arabic'
            })
        });
        const data = await response.json();
        if (data.success) {
            document.getElementById(target === 'en' ? 'deptNameEn' : 'deptNameAr').value = data.report;
        } else {
            alert('Translation failed: ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        console.error(e);
        alert('Network error');
    } finally {
        btn.disabled = false;
        btn.innerHTML = originalContent;
    }
}
</script>