<?php
require_once __DIR__ . '/../includes/auth.php';
AdminAuth::require();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_worker') {
    $name = trim($_POST['name'] ?? '');
    if ($name !== '') {
        db()->insert('workers', [
            'name' => $name,
            'entry_token' => generateToken(),
            'share_token' => generateToken(),
            'payer_token' => generateToken(),
        ]);
    }
    header('Location: /admin/index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_worker') {
    $workerId = (int) ($_POST['worker_id'] ?? 0);
    if ($workerId > 0) {
        // day_entries and week_settlements both have ON DELETE CASCADE on worker_id,
        // so deleting the worker row removes all their related data too.
        db()->query("DELETE FROM workers WHERE id = :id", ['id' => $workerId]);
    }
    header('Location: /admin/index.php');
    exit;
}

$workers = db()->fetchAll("SELECT * FROM workers WHERE active = 1 ORDER BY name ASC");

$owedByWorker = [];
$rows = db()->fetchAll("
    SELECT de.worker_id,
           SUM(CASE WHEN de.status='full' THEN " . FULL_DAY_RATE . " WHEN de.status='half' THEN " . HALF_DAY_RATE . " ELSE 0 END) AS owed
    FROM day_entries de
    LEFT JOIN week_settlements ws ON ws.worker_id = de.worker_id AND ws.week_start = de.week_start
    WHERE ws.paid IS NULL OR ws.paid = 0
    GROUP BY de.worker_id
");
foreach ($rows as $r) {
    $owedByWorker[$r['worker_id']] = (float) $r['owed'];
}

$pageTitle = 'Admin Dashboard - ChuckCo Time Keeper';
require_once __DIR__ . '/../includes/header.php';
?>
<div class="topbar">
    <h1>ChuckCo Time Keeper</h1>
    <a href="/admin/logout.php" class="logout">Log out</a>
</div>
<div class="container">

    <div class="card">
        <h3>All Workers Overview</h3>
        <p class="text-muted" style="font-size:0.85rem;">One link showing everyone's current week together.</p>
        <a href="/all.php?t=<?= e(ALL_WORKERS_TOKEN) ?>" class="btn btn-secondary btn-block" target="_blank">Open All-Workers View</a>
        <a href="/admin/history.php" class="btn btn-secondary btn-block" style="margin-top:0.5rem;">Full History (Everyone)</a>
    </div>

    <div class="card">
        <h3>Add Worker</h3>
        <form method="POST">
            <input type="hidden" name="action" value="add_worker">
            <div class="form-group">
                <label class="form-label">Name</label>
                <input type="text" name="name" class="form-input" required>
            </div>
            <button type="submit" class="btn btn-primary btn-block">Add Worker</button>
        </form>
    </div>

    <div class="card">
        <h3>Workers</h3>
        <?php if (empty($workers)): ?>
            <p class="text-muted">No workers yet. Add one above.</p>
        <?php else: ?>
            <?php foreach ($workers as $w): ?>
                <div class="worker-row" style="display:block;">
                    <div style="display:flex; justify-content:space-between; align-items:center;">
                        <a href="/admin/worker.php?id=<?= (int)$w['id'] ?>" class="worker-name" style="color:inherit; text-decoration:none;"><?= e($w['name']) ?></a>
                        <span class="worker-owed"><?= formatCurrency($owedByWorker[$w['id']] ?? 0) ?> owed</span>
                    </div>
                    <div class="link-row">
                        <a class="btn btn-sm btn-secondary" href="/w.php?t=<?= e($w['entry_token']) ?>" target="_blank">Entry Link</a>
                        <a class="btn btn-sm btn-secondary" href="/s.php?t=<?= e($w['share_token']) ?>" target="_blank">Their Screenshot</a>
                        <a class="btn btn-sm btn-secondary" href="/p.php?t=<?= e($w['payer_token']) ?>" target="_blank">My Screenshot</a>
                        <form method="POST" style="display:inline;" onsubmit="return confirm('Permanently delete <?= e(addslashes($w['name'])) ?> and ALL their time entries and history? This cannot be undone.');">
                            <input type="hidden" name="action" value="delete_worker">
                            <input type="hidden" name="worker_id" value="<?= (int)$w['id'] ?>">
                            <button type="submit" class="btn btn-sm" style="background:rgba(220,38,38,.1); color:var(--error);">Delete</button>
                        </form>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

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