<?php
require_once 'config.php';
require_once 'auth_functions.php';
requireEmployee(); // or requireAdmin() depending on your role system

// If admin should see a specific employee's leaves, you can take ?user_id=...
$userId = $_SESSION['user_id']; // adjust if needed

$sql = "
    SELECT la.*, u.full_name, u.employee_id
    FROM leave_applications la
    INNER JOIN users u ON la.user_id = u.id
    WHERE la.user_id = ?
    ORDER BY la.start_date DESC, la.id DESC
";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $userId);
$stmt->execute();
$result = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Leave Applications</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container mt-4">
    <h3 class="mb-3">My Leave Applications</h3>

    <div class="table-responsive">
        <table class="table table-bordered table-striped align-middle">
            <thead class="table-dark">
                <tr>
                    <th>#</th>
                    <th>Applied Date</th>
                    <th>Start Date</th>
                    <th>End Date</th>
                    <th>All Leave Dates<br><small>(end date not counted, Sat/Sun skipped)</small></th>
                    <th>Type</th>
                    <th>Half / Short Info</th>
                    <th>Status</th>
                    <th>Reason</th>
                </tr>
            </thead>
            <tbody>
            <?php
            if ($result->num_rows === 0):
            ?>
                <tr>
                    <td colspan="9" class="text-center">No leave applications found.</td>
                </tr>
            <?php
            else:
                $i = 1;
                while ($row = $result->fetch_assoc()):
                    // Build list of all leave dates from start to end-1, skipping Sat/Sun
                    $dates = [];
                    try {
                        $leaveStart = new DateTime($row['start_date']);
                        $leaveEnd   = new DateTime($row['end_date']);

                        // DO NOT count DB end_date itself as a leave day
                        $leaveEnd->modify('-1 day');

                        $cursor = clone $leaveStart;
                        while ($cursor <= $leaveEnd) {
                            $dow = (int)$cursor->format('N'); // 1=Mon..7=Sun
                            if ($dow < 6) { // Mon–Fri only
                                $dates[] = $cursor->format('Y-m-d');
                            }
                            $cursor->modify('+1 day');
                        }
                    } catch (Exception $e) {
                        // If invalid dates, just show raw start/end
                    }

                    // Build labels
                    $typeLabel = ucfirst($row['leave_type']); // casual, medical, etc.
                    $halfInfo  = '';
                    if ((int)$row['is_half_day'] === 1) {
                        if ($row['half_day_session'] === 'first_half') {
                            $halfInfo = 'Half day (First half)';
                        } elseif ($row['half_day_session'] === 'second_half') {
                            $halfInfo = 'Half day (Second half)';
                        } else {
                            $halfInfo = 'Half day';
                        }
                    } elseif ($row['leave_type'] === 'short') {
                        $halfInfo = 'Short leave'.($row['short_leave_time'] ? ' - '.$row['short_leave_time'] : '');
                    }

                    $statusClass = 'secondary';
                    if ($row['status'] === 'approved')  $statusClass = 'success';
                    if ($row['status'] === 'pending')   $statusClass = 'warning';
                    if ($row['status'] === 'rejected')  $statusClass = 'danger';
            ?>
                <tr>
                    <td><?= $i++; ?></td>
                    <td><?= htmlspecialchars(date('Y-m-d', strtotime($row['created_at'] ?? $row['start_date']))); ?></td>
                    <td><?= htmlspecialchars($row['start_date']); ?></td>
                    <td><?= htmlspecialchars($row['end_date']); ?></td>
                    <td style="white-space: nowrap;">
                        <?php
                        if (!empty($dates)) {
                            // show each date on a new line
                            echo implode('<br>', array_map('htmlspecialchars', $dates));
                        } else {
                            echo '<span class="text-muted">No working days (Sat/Sun only?)</span>';
                        }
                        ?>
                    </td>
                    <td><?= htmlspecialchars($typeLabel); ?></td>
                    <td><?= htmlspecialchars($halfInfo); ?></td>
                    <td>
                        <span class="badge bg-<?= $statusClass; ?>">
                            <?= htmlspecialchars(ucfirst($row['status'])); ?>
                        </span>
                    </td>
                    <td><?= nl2br(htmlspecialchars($row['reason'] ?? '')); ?></td>
                </tr>
            <?php
                endwhile;
            endif;
            ?>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>
