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

// Only logged in users can access this page
if (!isset($_SESSION['user_id'])) {
    echo "<div class='alert alert-danger'>يرجى تسجيل الدخول.</div>";
    require_once 'includes/footer.php';
    exit;
}

$user_id = $_SESSION['user_id'];
$error = '';
$success = '';
if (isset($_SESSION["success"])) {
    $success = $_SESSION["success"];
    unset($_SESSION["success"]);
}

// Check if current user is linked to an employee
$stmt = db()->prepare("SELECT id, first_name, last_name, department_id FROM hr_employees WHERE user_id = ? AND status = 'active'");
$stmt->execute([$user_id]);
$employee = $stmt->fetch();

if (!$employee) {
    echo "<div class='container mt-5'><div class='alert alert-warning text-center'>";
    echo "<i class='fas fa-exclamation-triangle fa-3x mb-3 text-warning'></i><br>";
    echo "<h4>لم يتم العثور على ملف موظف مرتبط بحسابك</h4>";
    echo "<p>يرجى التواصل مع قسم الموارد البشرية لربط حسابك بملف الموظف الخاص بك لتتمكن من تقديم طلبات الإجازات.</p>";
    echo "</div></div>";
    require_once 'includes/footer.php';
    exit;
}

$emp_id = $employee['id'];

// Handle Form Submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['request_leave'])) {
        $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 {
                $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]);
                $_SESSION["success"] = "تم تقديم طلب الإجازة بنجاح، بانتظار الاعتماد."; header("Location: my_leaves.php"); exit;
            } catch (PDOException $e) {
                $error = "حدث خطأ أثناء تقديم الطلب: " . $e->getMessage();
            }
        }
    }
}

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

// Fetch My Leaves
$countStmt = db()->prepare("SELECT COUNT(*) FROM hr_leaves WHERE employee_id = ?");
$countStmt->execute([$emp_id]);
$totalFiltered = $countStmt->fetchColumn();

$sql = "SELECT l.*, u.full_name as approver_name
        FROM hr_leaves l
        LEFT JOIN users u ON l.approved_by = u.id
        WHERE l.employee_id = ?
        ORDER BY l.created_at DESC
        LIMIT $limit OFFSET $offset";
$stmt = db()->prepare($sql);
$stmt->execute([$emp_id]);
$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"><i class="fas fa-calendar-day text-primary me-2"></i> إجازاتي</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#leaveModal">
            <i class="fas fa-plus"></i> تقديم طلب إجازة
        </button>
    </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>
                    <tr>
                        <th>نوع الإجازة</th>
                        <th>الفترة</th>
                        <th>المدة</th>
                        <th>السبب</th>
                        <th>تاريخ التقديم</th>
                        <th>الحالة</th>
                        <th>المعتمد</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($requests)): ?>
                        <tr><td colspan="7" class="text-center py-4 text-muted">لا توجد طلبات إجازات سابقة.</td></tr>
                    <?php else: ?>
                        <?php foreach ($requests as $req): ?>
                        <tr>
                            <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 class="small"><?= date('Y-m-d', strtotime($req['created_at'])) ?></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>
                            <td class="small"><?= $req['status'] === 'pending' ? '-' : htmlspecialchars($req['approver_name'] ?? 'مدير النظام') ?></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php echo renderPagination($page, ceil($totalFiltered / $limit)); ?>
    </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">تقديم طلب إجازة جديد</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">نوع الإجازة</label>
                        <select name="leave_type" 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" class="form-control" required>
                        </div>
                        <div class="col">
                            <label class="form-label">إلى تاريخ</label>
                            <input type="date" name="end_date" class="form-control" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">السبب</label>
                        <textarea name="reason" 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>

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