<?php
require_once 'includes/header.php';
require_once 'includes/pagination.php';

if (!canView('hr_leaves')) {
    echo "<div class='alert alert-danger'>ليس لديك صلاحية للوصول إلى هذه الصفحة.</div>";
    require_once 'includes/footer.php';
    exit;
}

$tab = $_GET['tab'] ?? 'pending';
$error = '';
$success = '';

// Handle Form Submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['request_leave'])) {
        if (!canAdd('hr_leaves')) {
            $error = "لا تملك صلاحية الإضافة.";
        } else {
            $id = $_POST['id'] ?? null; // For edit
            $emp_id = $_POST['employee_id'];
            $type = $_POST['leave_type'];
            $start = $_POST['start_date'];
            $end = $_POST['end_date'];
            $reason = trim($_POST['reason']);
            
            $start_dt = new DateTime($start);
            $end_dt = new DateTime($end);
            $days = $end_dt->diff($start_dt)->days + 1;

            if ($days <= 0) {
                $error = "تاريخ النهاية يجب أن يكون بعد تاريخ البداية.";
            } else {
                try {
                    if ($id) {
                        // Update existing request
                        $stmt = db()->prepare("UPDATE hr_leaves SET employee_id=?, leave_type=?, start_date=?, end_date=?, days_count=?, reason=? WHERE id=? AND status='pending'");
                        $stmt->execute([$emp_id, $type, $start, $end, $days, $reason, $id]);
                        $success = "تم تحديث طلب الإجازة بنجاح.";
                    } else {
                        // New request
                        $stmt = db()->prepare("INSERT INTO hr_leaves (employee_id, leave_type, start_date, end_date, days_count, reason, status) VALUES (?, ?, ?, ?, ?, ?, 'pending')");
                        $stmt->execute([$emp_id, $type, $start, $end, $days, $reason]);
                        $success = "تم تقديم طلب الإجازة بنجاح.";
                    }
                } catch (PDOException $e) {
                    $error = "خطأ: " . $e->getMessage();
                }
            }
        }
    } elseif (isset($_POST['update_status'])) {
        if (!canEdit('hr_leaves')) {
            $error = "لا تملك صلاحية الاعتماد.";
        } else {
            $id = $_POST['id'];
            $status = $_POST['status'];
            $stmt = db()->prepare("UPDATE hr_leaves SET status = ?, approved_by = ? WHERE id = ?");
            $stmt->execute([$status, $_SESSION['user_id'], $id]);
            $success = "تم تحديث حالة الطلب.";
        }
    }
}

// Fetch Employees for Dropdown
$employees = db()->query("SELECT id, first_name, last_name FROM hr_employees WHERE status = 'active' ORDER BY first_name")->fetchAll();

// Pagination Setup
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Filters & Search
$search = $_GET['search'] ?? '';
$filter_type = $_GET['filter_type'] ?? '';
$filter_status = $_GET['filter_status'] ?? '';

$conditions = [];
$params = [];

if ($tab === 'pending') {
    $conditions[] = "l.status = 'pending'";
} else {
    if ($filter_status) {
        $conditions[] = "l.status = ?";
        $params[] = $filter_status;
    }
}

if ($search) {
    $conditions[] = "(e.first_name LIKE ? OR e.last_name LIKE ? OR l.reason LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($filter_type) {
    $conditions[] = "l.leave_type = ?";
    $params[] = $filter_type;
}

$where_clause = count($conditions) > 0 ? "WHERE " . implode(' AND ', $conditions) : "WHERE 1=1";

// Count Total
$countSql = "SELECT COUNT(*) FROM hr_leaves l JOIN hr_employees e ON l.employee_id = e.id $where_clause";
$countStmt = db()->prepare($countSql);
$countStmt->execute($params);
$totalFiltered = $countStmt->fetchColumn();

// Fetch Records
$sql = "SELECT l.*, e.first_name, e.last_name, u.full_name as approver_name
        FROM hr_leaves l
        JOIN hr_employees e ON l.employee_id = e.id
        LEFT JOIN users u ON l.approved_by = u.id
        $where_clause
        ORDER BY l.created_at DESC
        LIMIT $limit OFFSET $offset";
$stmt = db()->prepare($sql);
$stmt->execute($params);
$requests = $stmt->fetchAll();

?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">إدارة الإجازات</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <?php if (canAdd('hr_leaves')): ?>
        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#leaveModal" onclick="resetLeaveForm()">
            <i class="fas fa-plus"></i> طلب إجازة جديد
        </button>
        <?php endif; ?>
    </div>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<?php if ($success): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>

<ul class="nav nav-tabs mb-4">
    <li class="nav-item">
        <a class="nav-link <?= $tab === 'pending' ? 'active' : '' ?>" href="?tab=pending">الطلبات المعلقة</a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?= $tab === 'all' ? 'active' : '' ?>" href="?tab=all">سجل الإجازات</a>
    </li>
</ul>

<!-- Filter & Search Form -->
<div class="card shadow-sm mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3 align-items-center">
            <input type="hidden" name="tab" value="<?= htmlspecialchars($tab) ?>">
            
            <div class="col-md-4">
                <input type="text" name="search" class="form-control" placeholder="بحث باسم الموظف أو السبب..." value="<?= htmlspecialchars($search) ?>">
            </div>
            
            <div class="col-md-3">
                <select name="filter_type" class="form-select">
                    <option value="">-- كل الأنواع --</option>
                    <option value="annual" <?= $filter_type === 'annual' ? 'selected' : '' ?>>سنوية</option>
                    <option value="sick" <?= $filter_type === 'sick' ? 'selected' : '' ?>>مرضية</option>
                    <option value="unpaid" <?= $filter_type === 'unpaid' ? 'selected' : '' ?>>بدون راتب</option>
                    <option value="maternity" <?= $filter_type === 'maternity' ? 'selected' : '' ?>>أمومة</option>
                    <option value="emergency" <?= $filter_type === 'emergency' ? 'selected' : '' ?>>طارئة</option>
                    <option value="other" <?= $filter_type === 'other' ? 'selected' : '' ?>>أخرى</option>
                </select>
            </div>
            
            <?php if ($tab === 'all'): ?>
            <div class="col-md-3">
                <select name="filter_status" class="form-select">
                    <option value="">-- كل الحالات --</option>
                    <option value="pending" <?= $filter_status === 'pending' ? 'selected' : '' ?>>معلقة</option>
                    <option value="approved" <?= $filter_status === 'approved' ? 'selected' : '' ?>>مقبولة</option>
                    <option value="rejected" <?= $filter_status === 'rejected' ? 'selected' : '' ?>>مرفوضة</option>
                </select>
            </div>
            <?php endif; ?>
            
            <div class="col-md-2 d-flex gap-2">
                <button type="submit" class="btn btn-primary flex-grow-1"><i class="fas fa-search"></i> بحث</button>
                <?php if ($search || $filter_type || $filter_status): ?>
                    <a href="?tab=<?= htmlspecialchars($tab) ?>" class="btn btn-outline-secondary">إلغاء</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                    <tr>
                        <th>الموظف</th>
                        <th>نوع الإجازة</th>
                        <th>الفترة</th>
                        <th>المدة</th>
                        <th>السبب</th>
                        <th>الحالة</th>
                        <?php if ($tab === 'all'): ?><th>المعتمد</th><?php endif; ?>
                        <th class="text-secondary text-nowrap" style="font-size: 0.85rem;"><i class="fas fa-user-plus me-1"></i>أضيف بواسطة</th>
                        <th class="text-secondary text-nowrap" style="font-size: 0.85rem;"><i class="fas fa-user-edit me-1"></i>عُدل بواسطة</th>
                        <th>إجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($requests)): ?>
                        <tr><td colspan="10" class="text-center py-4 text-muted">لا توجد طلبات.</td></tr>
                    <?php else: ?>
                        <?php foreach ($requests as $req): ?>
                        <tr>
                            <td class="fw-bold"><?= htmlspecialchars($req['first_name'] . ' ' . $req['last_name']) ?></td>
                            <td>
                                <?php
                                $type_map = [
                                    'annual' => 'سنوية',
                                    'sick' => 'مرضية',
                                    'unpaid' => 'بدون راتب',
                                    'maternity' => 'أمومة',
                                    'emergency' => 'طارئة',
                                    'other' => 'أخرى'
                                ];
                                echo $type_map[$req['leave_type']] ?? $req['leave_type'];
                                ?>
                            </td>
                            <td class="small">
                                من <?= $req['start_date'] ?><br>إلى <?= $req['end_date'] ?>
                            </td>
                            <td><?= $req['days_count'] ?> يوم</td>
                            <td class="text-truncate" style="max-width: 150px;"><?= htmlspecialchars($req['reason']) ?></td>
                            <td>
                                <?php
                                $status_cls = match($req['status']) {
                                    'approved' => 'success',
                                    'rejected' => 'danger',
                                    default => 'warning'
                                };
                                $status_txt = match($req['status']) {
                                    'approved' => 'مقبولة',
                                    'rejected' => 'مرفوضة',
                                    default => 'معلقة'
                                };
                                ?>
                                <span class="badge bg-<?= $status_cls ?>"><?= $status_txt ?></span>
                            </td>
                            <?php if ($tab === 'all'): ?>
                                <td class="small"><?= htmlspecialchars($req['approver_name'] ?? '-') ?></td>
                            <?php endif; ?>
                            <td><small class="text-muted"><i class="fas fa-user text-primary opacity-50 me-1"></i><?= htmlspecialchars(getAuditUserName($req['created_by'] ?? null)) ?></small></td>
                            <td><small class="text-muted"><i class="fas fa-user-edit text-warning opacity-50 me-1"></i><?= htmlspecialchars(getAuditUserName($req['updated_by'] ?? null)) ?></small></td>
                            <td>
                                <?php if ($req['status'] === 'pending' && canEdit('hr_leaves')): ?>
                                <button class="btn btn-sm btn-outline-primary" 
                                        title="تعديل الطلب"
                                        data-bs-toggle="modal" 
                                        data-bs-target="#leaveModal"
                                        data-id="<?= $req['id'] ?>"
                                        data-emp="<?= $req['employee_id'] ?>"
                                        data-type="<?= $req['leave_type'] ?>"
                                        data-start="<?= $req['start_date'] ?>"
                                        data-end="<?= $req['end_date'] ?>"
                                        data-reason="<?= htmlspecialchars($req['reason']) ?>"
                                        onclick="editLeave(this)">
                                    <i class="fas fa-edit"></i>
                                </button>
                                
                                <form method="post" class="d-inline">
                                    <input type="hidden" name="id" value="<?= $req['id'] ?>">
                                    <input type="hidden" name="status" value="approved">
                                    <button type="submit" name="update_status" class="btn btn-sm btn-success" title="قبول"><i class="fas fa-check"></i></button>
                                </form>
                                <form method="post" class="d-inline">
                                    <input type="hidden" name="id" value="<?= $req['id'] ?>">
                                    <input type="hidden" name="status" value="rejected">
                                    <button type="submit" name="update_status" class="btn btn-sm btn-danger" title="رفض" onclick="return confirm('هل أنت متأكد من الرفض؟')"><i class="fas fa-times"></i></button>
                                </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php 
        $totalPages = ceil($totalFiltered / $limit);
        echo renderPagination($page, $totalPages); 
        ?>
    </div>
</div>

<!-- Leave Request Modal -->
<div class="modal fade" id="leaveModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="leaveModalTitle">تقديم طلب إجازة</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" id="leaveForm">
                <div class="modal-body">
                    <input type="hidden" name="id" id="leaveId">
                    <div class="mb-3">
                        <label class="form-label">الموظف</label>
                        <select name="employee_id" id="leaveEmp" class="form-select" required>
                            <option value="">-- اختر الموظف --</option>
                            <?php foreach ($employees as $emp): ?>
                            <option value="<?= $emp['id'] ?>"><?= htmlspecialchars($emp['first_name'] . ' ' . $emp['last_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">نوع الإجازة</label>
                        <select name="leave_type" id="leaveType" class="form-select" required>
                            <option value="annual">سنوية</option>
                            <option value="sick">مرضية</option>
                            <option value="emergency">طارئة</option>
                            <option value="unpaid">بدون راتب</option>
                            <option value="maternity">أمومة</option>
                            <option value="other">أخرى</option>
                        </select>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col">
                            <label class="form-label">من تاريخ</label>
                            <input type="date" name="start_date" id="leaveStart" class="form-control" required>
                        </div>
                        <div class="col">
                            <label class="form-label">إلى تاريخ</label>
                            <input type="date" name="end_date" id="leaveEnd" class="form-control" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">السبب</label>
                        <textarea name="reason" id="leaveReason" class="form-control" rows="3" placeholder="سبب الإجازة..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" name="request_leave" class="btn btn-primary">حفظ الطلب</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function resetLeaveForm() {
        document.getElementById('leaveForm').reset();
        document.getElementById('leaveId').value = '';
        document.getElementById('leaveModalTitle').textContent = 'تقديم طلب إجازة';
    }

    function editLeave(btn) {
        document.getElementById('leaveModalTitle').textContent = 'تعديل طلب إجازة';
        document.getElementById('leaveId').value = btn.getAttribute('data-id');
        document.getElementById('leaveEmp').value = btn.getAttribute('data-emp');
        document.getElementById('leaveType').value = btn.getAttribute('data-type');
        document.getElementById('leaveStart').value = btn.getAttribute('data-start');
        document.getElementById('leaveEnd').value = btn.getAttribute('data-end');
        document.getElementById('leaveReason').value = btn.getAttribute('data-reason');
    }
</script>

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