<?php
// Pagination and Search
$search_name = $_GET['name'] ?? '';
$search_dept = $_GET['department_id'] ?? '';
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$lang = $_SESSION['lang'] ?? 'en';

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

if ($search_name) {
    $where .= " AND (e.name_en LIKE ? OR e.name_ar LIKE ?)";
    $params[] = "%$search_name%";
    $params[] = "%$search_name%";
}
if ($search_dept) {
    $where .= " AND e.department_id = ?";
    $params[] = $search_dept;
}

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

// Fetch Data
// Explicitly selecting room_number just to be safe, though e.* covers it.
$query = "
    SELECT e.*, e.room_number, d.name_$lang as department_name, p.name_$lang as position_name
    FROM employees e 
    LEFT JOIN departments d ON e.department_id = d.id 
    LEFT JOIN positions p ON e.position_id = p.id
    $where
    ORDER BY e.id DESC
    LIMIT $limit OFFSET $offset";

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

// Fetch Departments for Dropdown (Needed for Search Bar and Modal)
$deptNameCol = ($lang === 'ar') ? 'name_ar' : 'name_en';
$deptQuery = "SELECT id, $deptNameCol as name, active FROM departments ORDER BY $deptNameCol";
try {
    $deptStmt = $db->query($deptQuery);
    $all_departments = $deptStmt->fetchAll();
} catch (Exception $e) {
    $all_departments = [];
    error_log("Error fetching departments: " . $e->getMessage());
}

// Fetch Positions for Dropdown (Needed for Modal)
$posNameCol = ($lang === 'ar') ? 'name_ar' : 'name_en';
$posQuery = "SELECT id, $posNameCol as name FROM positions ORDER BY $posNameCol";
try {
    $posStmt = $db->query($posQuery);
    $all_positions = $posStmt->fetchAll();
} catch (Exception $e) {
    $all_positions = [];
}

// --- AJAX HANDLER ---
if (isset($_GET['ajax_search'])) {
    ob_start();
    if (empty($employees)):
    ?>
    <tr>
        <td colspan="4" class="text-center py-5 text-muted">
            <i class="bi bi-person-workspace display-4 d-block mb-3"></i>
            <?php echo __('no_employees_found'); ?>
        </td>
    </tr>
    <?php else: ?>
    <?php foreach ($employees as $emp): ?>
    <tr>
        <td class="px-4">
            <div class="fw-semibold text-dark"><?php echo htmlspecialchars($emp['name_'.$lang]); ?></div>
            <small class="text-muted"><?php echo htmlspecialchars($emp['name_'.($lang == 'en' ? 'ar' : 'en')]); ?></small>
        </td>
        <td>
            <span class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 px-2 py-1">
                <?php echo htmlspecialchars($emp['department_name'] ?: '-'); ?>
            </span>
            <div class="small text-muted mt-1">
                <i class="bi bi-diagram-2 me-1"></i> <?php echo htmlspecialchars($emp['position_name'] ?: '-'); ?>
            </div>
        </td>
        <td>
            <div class="small text-secondary"><i class="bi bi-telephone me-1"></i> <?php echo htmlspecialchars($emp['mobile'] ?: '-'); ?></div>
            <div class="small text-secondary"><i class="bi bi-envelope me-1"></i> <?php echo htmlspecialchars($emp['email'] ?: '-'); ?></div>
            <div class="small text-secondary"><i class="bi bi-door-open me-1"></i> <?php echo __('room_number'); ?>: <?php echo htmlspecialchars($emp['room_number'] ?: '-'); ?></div>
        </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="showEditEmployeeModal(<?php echo htmlspecialchars(json_encode($emp, 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="showDeleteEmployeeModal(<?php echo $emp['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, $totalEmployees); ?> <?php echo __('of'); ?> <?php echo $totalEmployees; ?>
        </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 __('employees'); ?></h3>
    <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#addEmployeeModal" onclick="resetEmployeeModal()">
        <i class="bi bi-person-plus-fill me-1"></i> <?php echo __('add_employee'); ?>
    </button>
</div>

<!-- Search Bar -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <form id="employeesSearchForm" class="row g-3" onsubmit="return false;">
            <div class="col-md-6">
                <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="empSearchName" class="form-control bg-light border-start-0" placeholder="<?php echo __('name'); ?>" value="<?php echo htmlspecialchars($search_name); ?>">
                </div>
            </div>
            <div class="col-md-4">
                <select name="department_id" id="empSearchDept" class="form-select bg-light">
                    <option value=""><?php echo __('department'); ?> (<?php echo __('all'); ?>)</option>
                    <?php foreach ($all_departments as $dept): ?>
                        <option value="<?php echo $dept['id']; ?>" <?php echo $search_dept == $dept['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($dept['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-secondary w-100" onclick="fetchEmployees(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"><?php echo __('name'); ?></th>
                        <th class="py-3"><?php echo __('department'); ?> / <?php echo __('position'); ?></th>
                        <th class="py-3"><?php echo __('contact'); ?></th>
                        <th class="py-3 text-end px-4"><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody id="employeesTableBody">
                    <?php if (empty($employees)): ?>
                    <tr>
                        <td colspan="4" class="text-center py-5 text-muted">
                            <i class="bi bi-person-workspace display-4 d-block mb-3"></i>
                            <?php echo __('no_employees_found'); ?>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($employees as $emp): ?>
                    <tr>
                        <td class="px-4">
                            <div class="fw-semibold text-dark"><?php echo htmlspecialchars($emp['name_'.$lang]); ?></div>
                            <small class="text-muted"><?php echo htmlspecialchars($emp['name_'.($lang == 'en' ? 'ar' : 'en')]); ?></small>
                        </td>
                        <td>
                            <span class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 px-2 py-1">
                                <?php echo htmlspecialchars($emp['department_name'] ?: '-'); ?>
                            </span>
                            <div class="small text-muted mt-1">
                                <i class="bi bi-diagram-2 me-1"></i> <?php echo htmlspecialchars($emp['position_name'] ?: '-'); ?>
                            </div>
                        </td>
                        <td>
                            <div class="small text-secondary"><i class="bi bi-telephone me-1"></i> <?php echo htmlspecialchars($emp['mobile'] ?: '-'); ?></div>
                            <div class="small text-secondary"><i class="bi bi-envelope me-1"></i> <?php echo htmlspecialchars($emp['email'] ?: '-'); ?></div>
                            <div class="small text-secondary"><i class="bi bi-door-open me-1"></i> <?php echo __('room_number'); ?>: <?php echo htmlspecialchars($emp['room_number'] ?: '-'); ?></div>
                        </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="showEditEmployeeModal(<?php echo htmlspecialchars(json_encode($emp, 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="showDeleteEmployeeModal(<?php echo $emp['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="employeesPagination">
        <?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, $totalEmployees); ?> <?php echo __('of'); ?> <?php echo $totalEmployees; ?>
            </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 Employee Modal -->
<div class="modal fade" id="addEmployeeModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="empModalTitle"><?php echo __('add_employee'); ?></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="empAction" value="add_employee">
                <input type="hidden" name="id" id="empId">
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('name_en'); ?> <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="name_en" id="empNameEn" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('name_ar'); ?> <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="name_ar" id="empNameAr" required>
                        </div>

                        <!-- Room Number -->
                        <div class="col-md-6">
                            <label class="form-label fw-bold" for="empRoomNumber"><?php echo __('room_number'); ?></label>
                            <input type="text" class="form-control" name="room_number" id="empRoomNumber" placeholder="<?php echo __('room_number'); ?>">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('email'); ?></label>
                            <input type="email" class="form-control" name="email" id="empEmail">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('mobile'); ?></label>
                            <input type="text" class="form-control" name="mobile" id="empMobile">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('dob'); ?></label>
                            <div class="input-group">
                                <span class="input-group-text bg-light"><i class="bi bi-calendar3"></i></span>
                                <input type="text" class="form-control" name="dob" id="empDob" placeholder="YYYY-MM-DD" data-inputmask-alias="datetime" data-inputmask-inputformat="yyyy-mm-dd" inputmode="numeric">
                            </div>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('department'); ?> <span class="text-danger">*</span></label>
                            <select class="form-select" name="department_id" id="empDeptId" required>
                                <option value=""><?php echo __('select_department'); ?></option>
                                <?php foreach ($all_departments as $dept): ?>
                                    <option value="<?php echo $dept['id']; ?>">
                                        <?php echo htmlspecialchars($dept['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                         <div class="col-md-6">
                            <label class="form-label"><?php echo __('position'); ?> <span class="text-danger">*</span></label>
                            <select class="form-select" name="position_id" id="empPosId" required>
                                <option value=""><?php echo __('select_position'); ?></option>
                                <?php foreach ($all_positions as $pos): ?>
                                    <option value="<?php echo $pos['id']; ?>">
                                        <?php echo htmlspecialchars($pos['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-12">
                            <label class="form-label"><?php echo __('address'); ?></label>
                            <textarea class="form-control" name="address" id="empAddress" rows="2"></textarea>
                        </div>
                    </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 Employee Modal -->
<div class="modal fade" id="deleteEmployeeModal" 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_employee'); ?></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_employee">
                <input type="hidden" name="id" id="deleteEmpId">
                <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('empSearchName');
    const searchDept = document.getElementById('empSearchDept');
    const paginationContainer = document.getElementById('employeesPagination');
    
    // Initialize Inputmask for DOB is handled globally in footer.php, but if not we can add it here if footer is not included.
    // However, footer is included. The global init should pick up data-inputmask attribute.

    let timeout = null;

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

    if (searchDept) {
        searchDept.addEventListener('change', function() {
            fetchEmployees(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) fetchEmployees(page);
            }
        });
    }
});

function fetchEmployees(page) {
    const name = document.getElementById('empSearchName').value;
    const dept = document.getElementById('empSearchDept').value;
    const tableBody = document.getElementById('employeesTableBody');
    const paginationContainer = document.getElementById('employeesPagination');

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

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

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

function resetEmployeeModal() {
    document.getElementById('empModalTitle').textContent = '<?php echo __('add_employee'); ?>';
    document.getElementById('empAction').value = 'add_employee';
    document.getElementById('empId').value = '';
    
    document.getElementById('empNameEn').value = '';
    document.getElementById('empNameAr').value = '';
    document.getElementById('empEmail').value = '';
    document.getElementById('empMobile').value = '';
    document.getElementById('empRoomNumber').value = '';
    document.getElementById('empDob').value = '';
    document.getElementById('empDeptId').value = '';
    document.getElementById('empPosId').value = '';
    document.getElementById('empAddress').value = '';
}

function showEditEmployeeModal(emp) {
    console.log('Employee Data:', emp); // Debug: Check if room_number is present
    document.getElementById('empModalTitle').textContent = '<?php echo __('edit_employee'); ?>';
    document.getElementById('empAction').value = 'edit_employee';
    document.getElementById('empId').value = emp.id;
    
    document.getElementById('empNameEn').value = emp.name_en || '';
    document.getElementById('empNameAr').value = emp.name_ar || '';
    document.getElementById('empEmail').value = emp.email || '';
    document.getElementById('empMobile').value = emp.mobile || '';
    document.getElementById('empRoomNumber').value = emp.room_number || '';
    document.getElementById('empDob').value = emp.dob || '';
    document.getElementById('empDeptId').value = emp.department_id || '';
    document.getElementById('empPosId').value = emp.position_id || '';
    document.getElementById('empAddress').value = emp.address || '';
    
    var modal = new bootstrap.Modal(document.getElementById('addEmployeeModal'));
    modal.show();
}

function showDeleteEmployeeModal(id) {
    document.getElementById('deleteEmpId').value = id;
    var modal = new bootstrap.Modal(document.getElementById('deleteEmployeeModal'));
    modal.show();
}
</script>