<?php
// تفعيل عرض الأخطاء لغرض التطوير
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$pageTitle = 'إدارة الموظفين';
include '../../includes/header.php';

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

checkLogin();

if (!hasPermission('view_employees')) {
    $_SESSION['error_message'] = 'ليس لديك صلاحية لعرض قائمة الموظفين.';
    header('Location: ../../index.php');
    exit();
}

$db = getDB();

$employees = [];
$total_employees = 0;
$active_employees = 0;
$inactive_employees = 0;

// تصفية البحث والفلاتر
$search_term = $_GET['search'] ?? '';
$location_filter = $_GET['location_filter'] ?? '';
$position_filter = $_GET['position_filter'] ?? '';
$gender_filter = $_GET['gender_filter'] ?? '';
$status_filter = $_GET['status_filter'] ?? 'all';
$sort_by = $_GET['sort_by'] ?? 'full_name';
$sort_order = (isset($_GET['sort_order']) && $_GET['sort_order'] === 'desc') ? 'DESC' : 'ASC';

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

try {
    $where_clauses = [];
    $params = [];

    if (!empty($search_term)) {
        $like = '%' . $search_term . '%';
        $where_clauses[] = "(e.full_name LIKE ? OR e.national_id_number LIKE ? OR e.position LIKE ? OR e.location_of_work LIKE ? OR e.home_address LIKE ?)";
        $params = array_merge($params, [$like, $like, $like, $like, $like]);
    }
    if ($location_filter && $location_filter !== 'all') {
        $where_clauses[] = "e.location_of_work = ?";
        $params[] = $location_filter;
    }
    if ($position_filter && $position_filter !== 'all') {
        $where_clauses[] = "e.position = ?";
        $params[] = $position_filter;
    }
    if ($gender_filter && $gender_filter !== 'all') {
        $where_clauses[] = "e.gender = ?";
        $params[] = $gender_filter;
    }
    
    // إحصائيات الكروت
    $card_where = $where_clauses ? "WHERE " . implode(" AND ", $where_clauses) : "";
    
    $active_where = $card_where ? $card_where . " AND status = 1" : "WHERE status = 1";
    $active_res = $db->select("SELECT COUNT(*) AS total FROM employees e {$active_where}", $params);
    $active_employees = $active_res[0]['total'] ?? 0;

    $inactive_where = $card_where ? $card_where . " AND status = 0" : "WHERE status = 0";
    $inactive_res = $db->select("SELECT COUNT(*) AS total FROM employees e {$inactive_where}", $params);
    $inactive_employees = $inactive_res[0]['total'] ?? 0;

    if ($status_filter !== 'all') {
        $where_clauses[] = "e.status = ?";
        $params[] = ($status_filter == '1') ? 1 : 0;
    }

    $search_where = $where_clauses ? "WHERE " . implode(" AND ", $where_clauses) : "";

    $total_res = $db->select("SELECT COUNT(*) AS total FROM employees e {$search_where}", $params);
    $total_employees = $total_res[0]['total'] ?? 0;
    $total_pages = ceil($total_employees / $limit);

    $unique_locations = array_column($db->select("SELECT DISTINCT location_of_work FROM employees WHERE location_of_work IS NOT NULL AND location_of_work != '' ORDER BY location_of_work ASC"), 'location_of_work');
    $unique_positions = array_column($db->select("SELECT DISTINCT position FROM employees WHERE position IS NOT NULL AND position != '' ORDER BY position ASC"), 'position');

$sql = "
        SELECT
            e.id, e.full_name, e.phone_number, e.position, e.date_hired, e.gender, e.location_of_work, e.status
        FROM employees e
        {$search_where}
        ORDER BY e.{$sort_by} {$sort_order}
        LIMIT ? OFFSET ?
    ";

    $params_query = array_merge($params, [$limit, $offset]);
    $employees = $db->select($sql, $params_query);

} catch (Exception $e) {
    error_log("Database error: " . $e->getMessage());
    $_SESSION['error_message'] = "حدث خطأ في قاعدة البيانات.";
}
?>

<div class="content-area">
    <div class="page-header d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="page-title">إدارة الموظفين</h2>
            <p class="page-subtitle">عرض وتعديل بيانات الموظفين المسجلين في النظام.</p>
        </div>
        <?php if (hasPermission('add_employee')): ?>
            <a href="add_employee.php" class="btn btn-success"><i class="fas fa-user-plus me-2"></i>إضافة موظف</a>
        <?php endif; ?>
    </div>

    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card shadow-sm border-0 bg-primary text-white">
                <div class="card-body d-flex justify-content-between align-items-center">
                    <div><h5>إجمالي الموظفين</h5><h3><?php echo ($active_employees + $inactive_employees); ?></h3></div>
                    <i class="fas fa-users fa-2x"></i>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card shadow-sm border-0 bg-success text-white">
                <div class="card-body d-flex justify-content-between align-items-center">
                    <div><h5>فعال</h5><h3><?php echo $active_employees; ?></h3></div>
                    <i class="fas fa-user-check fa-2x"></i>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card shadow-sm border-0 bg-danger text-white">
                <div class="card-body d-flex justify-content-between align-items-center">
                    <div><h5>متوقف</h5><h3><?php echo $inactive_employees; ?></h3></div>
                    <i class="fas fa-user-slash fa-2x"></i>
                </div>
            </div>
        </div>
    </div>

    <div class="card shadow-sm">
        <div class="card-body">
            <form method="GET" class="row g-3 mb-4">
                <div class="col-md-3">
                    <input type="text" name="search" class="form-control" placeholder="بحث بالاسم أو الهوية..." value="<?php echo htmlspecialchars($search_term); ?>">
                </div>
                <div class="col-md-2">
                    <select name="location_filter" class="form-select">
                        <option value="all">كل المواقع</option>
                        <?php foreach($unique_locations as $loc): ?>
                            <option value="<?php echo htmlspecialchars($loc); ?>" <?php echo ($location_filter === $loc) ? 'selected' : ''; ?>><?php echo htmlspecialchars($loc); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <select name="position_filter" class="form-select">
                        <option value="all">كل المناصب</option>
                        <?php foreach($unique_positions as $pos): ?>
                            <option value="<?php echo htmlspecialchars($pos); ?>" <?php echo ($position_filter === $pos) ? 'selected' : ''; ?>><?php echo htmlspecialchars($pos); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <select name="status_filter" class="form-select">
                        <option value="all">كل الحالات</option>
                        <option value="1" <?php echo ($status_filter === '1') ? 'selected' : ''; ?>>فعال</option>
                        <option value="0" <?php echo ($status_filter === '0') ? 'selected' : ''; ?>>متوقف</option>
                    </select>
                </div>
                <div class="col-md-3 d-flex gap-2">
                    <button class="btn btn-primary w-100"><i class="fas fa-filter"></i> تصفية</button>
                    <a href="index.php" class="btn btn-light border"><i class="fas fa-redo"></i></a>
                </div>
            </form>

            <div class="table-responsive">
                <table class="table table-hover align-middle">
             <thead class="table-light">
    <tr>
        <th>#</th>
        <th>الاسم الكامل</th>
        <th>رقم الهاتف</th> <th>المنصب</th>
        <th>تاريخ التعيين</th>
        <th>موقع العمل</th>
        <th>الجنس</th>
        <th>الحالة</th>
        <th class="text-center">إجراءات</th>
    </tr>
</thead>
                    <tbody>
                        <?php foreach($employees as $i => $emp): ?>
                            <tr>
                                <td><?php echo (($page-1)*$limit)+$i+1; ?></td>
                                <td class="fw-bold"><?php echo htmlspecialchars($emp['full_name']); ?></td>
                                <td>
                <span class="text-muted"><i class="fas fa-phone-alt me-1 small"></i></span>
                <?php echo htmlspecialchars($emp['phone_number'] ?: '---'); ?>
            </td>
                                <td><span class="badge bg-light text-dark border"><?php echo htmlspecialchars($emp['position']); ?></span></td>
                                <td><?php echo date('Y-m-d', strtotime($emp['date_hired'])); ?></td>
                                <td><?php echo htmlspecialchars($emp['location_of_work'] ?: 'غير محدد'); ?></td>
                                
                                <td><?php echo $emp['gender']=='male' ? 'ذكر' : 'أنثى'; ?></td>
                                <td>
                                    <span class="badge <?php echo $emp['status']==1?'bg-success':'bg-danger'; ?>" id="statusBadge-<?php echo $emp['id']; ?>">
                                        <?php echo $emp['status']==1?'فعال':'متوقف'; ?>
                                    </span>
                                    <?php if(hasPermission('edit_employee')): ?>
                                        <button class="btn btn-sm btn-link text-decoration-none" onclick="toggleStatus(<?php echo $emp['id']; ?>)">
                                            <i class="fas fa-sync-alt"></i>
                                        </button>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <div class="btn-group">
                                        <?php if(hasPermission('edit_employee')): ?>
                                            <a href="edit_employee.php?id=<?php echo $emp['id']; ?>" class="btn btn-sm btn-outline-warning"><i class="fas fa-edit"></i></a>
                                        <?php endif; ?>
                                        <?php if(hasPermission('delete_employee')): ?>
                                            <button class="btn btn-sm btn-outline-danger" onclick="showDeleteModal(<?php echo $emp['id']; ?>,'<?php echo addslashes($emp['full_name']); ?>')"><i class="fas fa-trash"></i></button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <?php if($total_pages > 1): ?>
                <nav class="mt-4"><ul class="pagination justify-content-center">
                    <li class="page-item <?php echo $page<=1?'disabled':''; ?>"><a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo $search_term; ?>">السابق</a></li>
                    <?php for($i=1;$i<=$total_pages;$i++): ?>
                        <li class="page-item <?php echo $page==$i?'active':''; ?>"><a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo $search_term; ?>"><?php echo $i; ?></a></li>
                    <?php endfor; ?>
                    <li class="page-item <?php echo $page>=$total_pages?'disabled':''; ?>"><a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo $search_term; ?>">التالي</a></li>
                </ul></nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="modal fade" id="deleteConfirmationModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteModalLabel">تأكيد الحذف</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                هل أنت متأكد أنك تريد حذف الموظف: <strong id="employeeNameInModal"></strong>؟
                <p class="text-muted small mt-2">ملاحظة: لا يمكن التراجع عن هذا الإجراء.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteButton">تأكيد الحذف</button>
            </div>
        </div>
    </div>
</div>

<script>
function toggleStatus(employeeId) {
    if (!confirm('هل تريد تغيير حالة هذا الموظف؟')) return;
    fetch('toggle_status.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: employeeId })
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) location.reload();
        else alert('خطأ: ' + data.message);
    });
}

function showDeleteModal(id, name) {
    // التأكد من وجود العنصر قبل محاولة الكتابة فيه لتجنب خطأ Uncaught TypeError
    const nameElem = document.getElementById('employeeNameInModal');
    if(nameElem) {
        nameElem.textContent = name;
    }
    
    const confirmBtn = document.getElementById('confirmDeleteButton');
    if(confirmBtn) {
        confirmBtn.onclick = function() {
            window.location.href = 'delete_employee.php?id=' + id;
        };
    }
    
    // تشغيل الـ Modal الخاص ببوتستراب
    var myModal = new bootstrap.Modal(document.getElementById('deleteConfirmationModal'));
    myModal.show();
}
</script>

<?php include '../../includes/footer.php'; ?>