<?php $pdo = $db; ?>
<?php
if (!is_admin()) {
    // header('Location: index.php'); exit;
}

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

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

if (!empty($_GET['status'])) {
    $where .= " AND l.status = ?";
    $params[] = $_GET['status'];
}

$logs = $pdo->prepare("
    SELECT l.*, e.name_en 
    FROM leave_requests l 
    JOIN employees e ON l.employee_id = e.id 
    WHERE $where
    ORDER BY l.created_at DESC 
    LIMIT $limit OFFSET $offset
");
$logs->execute($params);
$requests = $logs->fetchAll(PDO::FETCH_ASSOC);

$total_logs = $pdo->prepare("SELECT COUNT(*) FROM leave_requests l WHERE $where");
$total_logs->execute($params);
$total_rows = $total_logs->fetchColumn();
$total_pages = ceil($total_rows / $limit);

$employees = $pdo->query("SELECT id, name_en FROM employees ORDER BY name_en")->fetchAll(PDO::FETCH_KEY_PAIR);

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_leave'])) {
        $emp_id = $_POST['employee_id'];
        $type = $_POST['leave_type'];
        $start = $_POST['start_date'];
        $end = $_POST['end_date'];
        $reason = $_POST['reason'];
        
        $diff = strtotime($end) - strtotime($start);
        $days = round($diff / (60 * 60 * 24)) + 1;

        $stmt = $pdo->prepare("INSERT INTO leave_requests (employee_id, leave_type, start_date, end_date, days, reason, status) VALUES (?, ?, ?, ?, ?, ?, 'Pending')");
        $stmt->execute([$emp_id, $type, $start, $end, $days, $reason]);
    } elseif (isset($_POST['approve_leave'])) {
        $stmt = $pdo->prepare("UPDATE leave_requests SET status = 'Approved' WHERE id = ?");
        $stmt->execute([$_POST['id']]);
    } elseif (isset($_POST['reject_leave'])) {
        $stmt = $pdo->prepare("UPDATE leave_requests SET status = 'Rejected' WHERE id = ?");
        $stmt->execute([$_POST['id']]);
    } elseif (isset($_POST['delete_leave'])) {
        $stmt = $pdo->prepare("DELETE FROM leave_requests WHERE id = ?");
        $stmt->execute([$_POST['id']]);
    }
    
    echo "<script>window.location.href='hr_leaves.php';</script>";
}
?>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0 text-gray-800"><?php echo __("leave_requests"); ?></h1>
        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addLeaveModal">
            <i class="fas fa-plus"></i> <?php echo __("new_request"); ?>
        </button>
    </div>

    <!-- Filter -->
    <div class="card shadow mb-4">
        <div class="card-body">
            <form method="GET" class="d-flex align-items-center">
                <select name="status" class="form-select me-2" style="width: auto;">
                    <option value=""><?php echo __("all_statuses"); ?></option>
                    <option value="Pending" <?php echo (isset($_GET['status']) && $_GET['status'] == 'Pending') ? 'selected' : ''; ?>><?php echo __("pending"); ?></option>
                    <option value="Approved" <?php echo (isset($_GET['status']) && $_GET['status'] == 'Approved') ? 'selected' : ''; ?>><?php echo __("approved"); ?></option>
                    <option value="Rejected" <?php echo (isset($_GET['status']) && $_GET['status'] == 'Rejected') ? 'selected' : ''; ?>><?php echo __("rejected"); ?></option>
                </select>
                <button type="submit" class="btn btn-primary"><?php echo __("filter"); ?></button>
            </form>
        </div>
    </div>

    <!-- Table -->
    <div class="card shadow mb-4">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th><?php echo __("employee"); ?></th>
                            <th><?php echo __("type"); ?></th>
                            <th><?php echo __("duration"); ?></th>
                            <th><?php echo __("days"); ?></th>
                            <th><?php echo __("reason"); ?></th>
                            <th><?php echo __("status"); ?></th>
                            <th><?php echo __("actions"); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($requests as $req): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($req['name_en']); ?></td>
                            <td><?php echo htmlspecialchars($req['leave_type']); ?></td>
                            <td>
                                <?php echo $req['start_date']; ?> to <?php echo $req['end_date']; ?>
                            </td>
                            <td><?php echo $req['days']; ?></td>
                            <td><?php echo htmlspecialchars($req['reason']); ?></td>
                            <td>
                                <span class="badge bg-<?php 
                                    echo $req['status'] == 'Approved' ? 'success' : 
                                        ($req['status'] == 'Pending' ? 'warning' : 'danger'); 
                                ?>">
                                    <?php echo $req['status']; ?>
                                </span>
                            </td>
                            <td>
                                <?php if($req['status'] == 'Pending'): ?>
                                <form method="POST" style="display:inline;">
                                    <input type="hidden" name="id" value="<?php echo $req['id']; ?>">
                                    <button type="submit" name="approve_leave" class="btn btn-success btn-sm" title="<?php echo __("approve"); ?>"><i class="fas fa-check"></i></button>
                                </form>
                                <form method="POST" style="display:inline;">
                                    <input type="hidden" name="id" value="<?php echo $req['id']; ?>">
                                    <button type="submit" name="reject_leave" class="btn btn-danger btn-sm" title="<?php echo __("reject"); ?>"><i class="fas fa-times"></i></button>
                                </form>
                                <?php endif; ?>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('<?php echo __("confirm_delete_request"); ?>');">
                                    <input type="hidden" name="id" value="<?php echo $req['id']; ?>">
                                    <button type="submit" name="delete_leave" class="btn btn-secondary btn-sm" title="<?php echo __("delete"); ?>"><i class="fas fa-trash"></i></button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($requests)): ?>
                        <tr><td colspan="7" class="text-center"><?php echo __("no_requests_found"); ?></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
             <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center">
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo $_GET['status'] ?? ''; ?>">
                                <?php echo $i; ?>
                            </a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Add Modal -->
<div class="modal fade" id="addLeaveModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <form method="POST">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><?php echo __("request_leave"); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="add_leave" value="1">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __("employee"); ?></label>
                        <select name="employee_id" class="form-select" required>
                            <?php foreach ($employees as $id => $name): ?>
                                <option value="<?php echo $id; ?>"><?php echo htmlspecialchars($name); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __("leave_type"); ?></label>
                        <select name="leave_type" class="form-select">
                            <option value="Annual"><?php echo __("annual"); ?></option>
                            <option value="Sick"><?php echo __("sick"); ?></option>
                            <option value="Casual"><?php echo __("casual"); ?></option>
                            <option value="Unpaid"><?php echo __("unpaid"); ?></option>
                        </select>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __("start_date"); ?></label>
                            <input type="date" name="start_date" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __("end_date"); ?></label>
                            <input type="date" name="end_date" class="form-control" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __("reason"); ?></label>
                        <textarea name="reason" class="form-control" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __("close"); ?></button>
                    <button type="submit" class="btn btn-primary"><?php echo __("submit"); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>