<?php
$currentYear = (int) date('Y');
$selectedMonth = (int) ($filters['month'] ?? 0);
$selectedYear = (int) ($filters['year'] ?? 0);
$months = [
    1 => 'Jan', 2 => 'Feb', 3 => 'Mac', 4 => 'Apr',
    5 => 'Mei', 6 => 'Jun', 7 => 'Jul', 8 => 'Ogos',
    9 => 'Sep', 10 => 'Okt', 11 => 'Nov', 12 => 'Dis',
];
?>

<div class="d-flex flex-column flex-lg-row justify-content-between gap-3 align-items-lg-center mb-3">
    <h2 class="h4 mb-0">Admin Dashboard</h2>
    <form class="row gy-2 gx-2 align-items-end bg-white rounded-3 shadow-sm px-3 py-2" method="get" action="index.php">
        <input type="hidden" name="route" value="admin/requests">
        <div class="col-auto">
            <label class="form-label">Search</label>
            <input type="text" name="search" value="<?= htmlspecialchars($filters['search'] ?? '') ?>" class="form-control form-control-sm" placeholder="Nama/Info">
        </div>
        <div class="col-auto">
            <label class="form-label">Staff</label>
            <select name="staff_id" class="form-select form-select-sm">
                <option value="">Semua Staff</option>
                <?php foreach ($staffList as $staff): ?>
                    <option value="<?= $staff['id'] ?>" <?= (int) ($filters['staff_id'] ?? 0) === (int) $staff['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($staff['name']) ?> (<?= htmlspecialchars($staff['login_id']) ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php if (!empty($locations)): ?>
            <div class="col-auto">
                <label class="form-label">Lokasi</label>
                <select name="location" class="form-select form-select-sm">
                    <option value="">Semua Lokasi</option>
                    <?php foreach ($locations as $loc): ?>
                        <option value="<?= htmlspecialchars($loc) ?>" <?= ($filters['location'] ?? '') === $loc ? 'selected' : '' ?>>
                            <?= htmlspecialchars($loc) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        <?php endif; ?>
        <div class="col-auto">
            <label class="form-label">Month</label>
            <select name="month" class="form-select form-select-sm">
                <option value="">Semua</option>
                <?php foreach ($months as $num => $label): ?>
                    <option value="<?= $num ?>" <?= $selectedMonth === $num ? 'selected' : '' ?>>
                        <?= $label ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-auto">
            <label class="form-label">Year</label>
            <select name="year" class="form-select form-select-sm">
                <option value="">Semua</option>
                <?php for ($y = $currentYear + 1; $y >= $currentYear - 4; $y--): ?>
                    <option value="<?= $y ?>" <?= $selectedYear === $y ? 'selected' : '' ?>>
                        <?= $y ?>
                    </option>
                <?php endfor; ?>
            </select>
        </div>
        <div class="col-auto">
            <label class="form-label">Status</label>
            <select name="status" class="form-select form-select-sm">
                <?php foreach (['pending','approved','rejected'] as $status): ?>
                    <option value="<?= $status ?>" <?= ($filters['status'] ?? '') === $status ? 'selected' : '' ?>><?= ucfirst($status) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-auto">
            <label class="form-label">Sort</label>
            <select name="sort" class="form-select form-select-sm">
                <option value="date" <?= ($filters['sort'] ?? '') === 'date' ? 'selected' : '' ?>>Date</option>
                <option value="name" <?= ($filters['sort'] ?? '') === 'name' ? 'selected' : '' ?>>Name</option>
                <option value="status" <?= ($filters['sort'] ?? '') === 'status' ? 'selected' : '' ?>>Status</option>
                <option value="amount" <?= ($filters['sort'] ?? '') === 'amount' ? 'selected' : '' ?>>Amount / Days</option>
            </select>
        </div>
        <div class="col-auto">
            <label class="form-label">Direction</label>
            <select name="direction" class="form-select form-select-sm">
                <option value="DESC" <?= ($filters['direction'] ?? '') === 'DESC' ? 'selected' : '' ?>>Desc</option>
                <option value="ASC" <?= ($filters['direction'] ?? '') === 'ASC' ? 'selected' : '' ?>>Asc</option>
            </select>
        </div>
        <div class="col-auto">
            <label class="form-label d-block">&nbsp;</label>
            <button class="btn btn-sm btn-primary">Filter</button>
        </div>
    </form>
        <?php
        $exportParams = function (string $type, string $format) use ($filters) {
            $query = http_build_query([
                'route' => 'admin/export',
                'type' => $type,
                'format' => $format,
                'status' => $filters['status'] ?? 'approved',
                'staff_id' => $filters['staff_id'] ?? null,
                'month' => $filters['month'] ?? null,
                'year' => $filters['year'] ?? null,
                'location' => $filters['location'] ?? null,
                'search' => $filters['search'] ?? null,
            ]);
            return "index.php?{$query}";
        };
        ?>
    <div class="dropdown">
        <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" id="downloadDropdown"
                data-bs-toggle="dropdown" aria-expanded="false">
            Download
        </button>
        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="downloadDropdown">
            <li><h6 class="dropdown-header">Advance</h6></li>
            <li><a class="dropdown-item" href="<?= $exportParams('advance', 'pdf') ?>">Advance PDF</a></li>
            <li><a class="dropdown-item" href="<?= $exportParams('advance', 'csv') ?>">Advance CSV</a></li>
            <li><hr class="dropdown-divider"></li>
            <li><h6 class="dropdown-header">Leave</h6></li>
            <li><a class="dropdown-item" href="<?= $exportParams('leave', 'pdf') ?>">Leave PDF</a></li>
            <li><a class="dropdown-item" href="<?= $exportParams('leave', 'csv') ?>">Leave CSV</a></li>
            <li><hr class="dropdown-divider"></li>
            <li><h6 class="dropdown-header">Claim</h6></li>
            <li><a class="dropdown-item" href="<?= $exportParams('claim', 'pdf') ?>">Claim PDF</a></li>
            <li><a class="dropdown-item" href="<?= $exportParams('claim', 'csv') ?>">Claim CSV</a></li>
        </ul>
    </div>
</div>

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

<div class="row gy-4">
    <div class="col-md-4">
        <div class="card summary-card bg-success text-white">
            <div class="card-body">
                <h5>Advance Salary (Approved)</h5>
                <p class="display-6">RM <?= number_format($summary['advance_total'], 2) ?></p>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card summary-card bg-info text-white">
            <div class="card-body">
                <h5>Leave Days (Approved)</h5>
                <p class="display-6"><?= (int) $summary['leave_days'] ?> hari</p>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card summary-card bg-warning text-dark">
            <div class="card-body">
                <h5>Claims (Approved)</h5>
                <p class="display-6">RM <?= number_format($summary['claim_total'], 2) ?></p>
            </div>
        </div>
    </div>
</div>

<?php
$tables = [
    ['key' => 'advance', 'title' => 'Advance Salary', 'data' => $advance, 'columns' => ['ID', 'Nama', 'Jumlah', 'Status', 'Updated']],
    ['key' => 'leave', 'title' => 'Leave Requests', 'data' => $leave, 'columns' => ['ID', 'Nama', 'Jumlah Hari', 'Status', 'Tarikh']],
    ['key' => 'claim', 'title' => 'Claims', 'data' => $claims, 'columns' => ['ID', 'Nama', 'Amount', 'Status', 'Updated']],
];

$buildPageLink = function (string $param, int $page) use ($query) {
    $params = array_merge($query, ['route' => 'admin/requests', $param => $page]);
    return 'index.php?' . http_build_query($params);
};
?>

<div class="mt-4">
    <?php foreach ($tables as $table): ?>
        <div class="card shadow-sm mb-3">
            <div class="card-body">
                <h5><?= $table['title'] ?></h5>
                <?php if (empty($table['data'])): ?>
                    <p class="text-muted mb-0">No records found.</p>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover align-middle">
                            <thead>
                            <tr>
                                <?php foreach ($table['columns'] as $column): ?>
                                    <th><?= $column ?></th>
                                <?php endforeach; ?>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($table['data'] as $row): ?>
                                <tr>
                                    <td>#<?= $row['id'] ?></td>
                                    <td><?= htmlspecialchars($row['nama'] ?? $row['nama_staff']) ?></td>
                                    <td>
                                        <?php if (isset($row['jumlah'])): ?>
                                            RM <?= number_format($row['jumlah'], 2) ?>
                                        <?php elseif (isset($row['jumlah_hari'])): ?>
                                            <?= $row['jumlah_hari'] ?> hari
                                        <?php else: ?>
                                            RM <?= number_format($row['amount'], 2) ?>
                                        <?php endif; ?>
                                    </td>
                                    <?php
                                    if ($row['status'] === 'approved') {
                                        $color = 'success';
                                    } elseif ($row['status'] === 'rejected') {
                                        $color = 'danger';
                                    } else {
                                        $color = 'secondary';
                                    }
                                    ?>
                                    <td><span class="badge bg-<?= $color ?>"><?= ucfirst($row['status']) ?></span></td>
                                    <td><?= htmlspecialchars($row['updated_at'] ?? $row['tarikh_mula']) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
                <?php
                $pager = $pagination[$table['key']];
                $totalPages = max(1, (int) ceil($pager['total'] / $pager['limit']));
                $currentPage = $pager['page'];
                ?>
                <?php if ($totalPages > 1): ?>
                    <nav>
                        <ul class="pagination pagination-sm mb-0">
                            <li class="page-item <?= $currentPage <= 1 ? 'disabled' : '' ?>">
                                <a class="page-link" href="<?= $currentPage <= 1 ? '#' : $buildPageLink('page_' . $table['key'], $currentPage - 1) ?>">Prev</a>
                            </li>
                            <li class="page-item disabled"><span class="page-link"><?= $currentPage ?> / <?= $totalPages ?></span></li>
                            <li class="page-item <?= $currentPage >= $totalPages ? 'disabled' : '' ?>">
                                <a class="page-link" href="<?= $currentPage >= $totalPages ? '#' : $buildPageLink('page_' . $table['key'], $currentPage + 1) ?>">Next</a>
                            </li>
                        </ul>
                    </nav>
                <?php endif; ?>
            </div>
        </div>
    <?php endforeach; ?>
</div>

