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

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

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['save_holiday'])) {
        if (!canAdd('hr_attendance') && !canEdit('hr_attendance')) {
            $error = "لا تملك صلاحية التعديل.";
        } else {
            $id = $_POST['id'] ?? null;
            $name = trim($_POST['name']);
            $from = $_POST['date_from'];
            $to = $_POST['date_to'];
            
            if (!empty($name) && !empty($from) && !empty($to)) {
                if ($id) {
                    $stmt = db()->prepare("UPDATE hr_holidays SET name=?, date_from=?, date_to=? WHERE id=?");
                    $stmt->execute([$name, $from, $to, $id]);
                    $success = "تم تحديث العطلة بنجاح.";
                } else {
                    $stmt = db()->prepare("INSERT INTO hr_holidays (name, date_from, date_to) VALUES (?, ?, ?)");
                    $stmt->execute([$name, $from, $to]);
                    $success = "تم إضافة العطلة بنجاح.";
                }
            }
        }
    } elseif (isset($_POST['delete_holiday'])) {
        if (!canDelete('hr_attendance')) {
            $error = "لا تملك صلاحية الحذف.";
        } else {
            $id = $_POST['id'];
            $stmt = db()->prepare("DELETE FROM hr_holidays WHERE id = ?");
            $stmt->execute([$id]);
            $success = "تم حذف العطلة.";
        }
    }
}

$holidays = db()->query("SELECT * FROM hr_holidays ORDER BY date_from DESC")->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_attendance')): ?>
        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#holidayModal" onclick="resetHolidayForm()">
            <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; ?>

<div class="card shadow-sm">
    <div class="card-body">
        <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 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($holidays)): ?>
                        <tr><td colspan="7" class="text-center py-4 text-muted">لا توجد عطلات مسجلة.</td></tr>
                    <?php else: ?>
                        <?php foreach ($holidays as $row): 
                            $today = date('Y-m-d');
                            $status_cls = 'secondary';
                            $status_txt = 'منتهية';
                            
                            if ($today >= $row['date_from'] && $today <= $row['date_to']) {
                                $status_cls = 'success';
                                $status_txt = 'جارية';
                            } elseif ($today < $row['date_from']) {
                                $status_cls = 'primary';
                                $status_txt = 'قادمة';
                            }
                        ?>
                        <tr>
                            <td class="fw-bold"><?= htmlspecialchars($row['name']) ?></td>
                            <td><?= $row['date_from'] ?></td>
                            <td><?= $row['date_to'] ?></td>
                            <td><span class="badge bg-<?= $status_cls ?>"><?= $status_txt ?></span></td>
                            <td><small class="text-muted"><i class="fas fa-user text-primary opacity-50 me-1"></i><?= htmlspecialchars(getAuditUserName($row['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($row['updated_by'] ?? null)) ?></small></td>
                            <td>
                                <?php if (canEdit('hr_attendance')): ?>
                                <button class="btn btn-sm btn-outline-primary" 
                                        data-bs-toggle="modal" 
                                        data-bs-target="#holidayModal"
                                        data-id="<?= $row['id'] ?>"
                                        data-name="<?= htmlspecialchars($row['name']) ?>"
                                        data-from="<?= $row['date_from'] ?>"
                                        data-to="<?= $row['date_to'] ?>"
                                        onclick="editHoliday(this)">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <?php endif; ?>
                                <?php if (canDelete('hr_attendance')): ?>
                                <form method="post" onsubmit="return confirm('هل أنت متأكد؟');" class="d-inline">
                                    <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                    <button type="submit" name="delete_holiday" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
                                </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Holiday Modal -->
<div class="modal fade" id="holidayModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="holidayModalTitle">إضافة عطلة جديدة</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" id="holidayForm">
                <div class="modal-body">
                    <input type="hidden" name="id" id="holidayId">
                    <div class="mb-3">
                        <label class="form-label">اسم العطلة</label>
                        <input type="text" name="name" id="holidayName" class="form-control" required placeholder="مثال: عيد الفطر">
                    </div>
                    <div class="row g-2">
                        <div class="col">
                            <label class="form-label">من تاريخ</label>
                            <input type="date" name="date_from" id="holidayFrom" class="form-control" required>
                        </div>
                        <div class="col">
                            <label class="form-label">إلى تاريخ</label>
                            <input type="date" name="date_to" id="holidayTo" class="form-control" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" name="save_holiday" class="btn btn-primary">حفظ</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function resetHolidayForm() {
        document.getElementById('holidayForm').reset();
        document.getElementById('holidayId').value = '';
        document.getElementById('holidayModalTitle').textContent = 'إضافة عطلة جديدة';
    }

    function editHoliday(btn) {
        document.getElementById('holidayModalTitle').textContent = 'تعديل عطلة';
        document.getElementById('holidayId').value = btn.getAttribute('data-id');
        document.getElementById('holidayName').value = btn.getAttribute('data-name');
        document.getElementById('holidayFrom').value = btn.getAttribute('data-from');
        document.getElementById('holidayTo').value = btn.getAttribute('data-to');
    }
</script>

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