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

$workerId = (int) ($_GET['id'] ?? 0);
$worker = db()->fetch("SELECT * FROM workers WHERE id = :id", ['id' => $workerId]);
if (!$worker) {
    header('Location: /admin/index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'set_day') {
        $date = $_POST['date'] ?? '';
        $status = $_POST['status'] ?? '';
        $reason = trim($_POST['reason'] ?? '');
        $location = trim($_POST['location'] ?? '');
        if (in_array($status, ['full', 'half', 'absent'], true) && $date) {
            $weekStart = getWeekStart($date);
            db()->query("
                INSERT INTO day_entries (worker_id, work_date, week_start, status, absence_reason, location)
                VALUES (:wid, :date, :week, :status, :reason, :location)
                ON DUPLICATE KEY UPDATE status = :status2, absence_reason = :reason2, location = :location2, week_start = :week2
            ", [
                'wid' => $workerId, 'date' => $date, 'week' => $weekStart,
                'status' => $status, 'reason' => $reason ?: null, 'location' => $location ?: null,
                'status2' => $status, 'reason2' => $reason ?: null, 'location2' => $location ?: null, 'week2' => $weekStart,
            ]);
        }
        header('Location: /admin/worker.php?id=' . $workerId);
        exit;
    }

    if ($action === 'clear_day') {
        $date = $_POST['date'] ?? '';
        db()->query("DELETE FROM day_entries WHERE worker_id = :wid AND work_date = :date", ['wid' => $workerId, 'date' => $date]);
        header('Location: /admin/worker.php?id=' . $workerId);
        exit;
    }

    if ($action === 'toggle_paid') {
        $weekStart = $_POST['week_start'] ?? '';
        $existing = db()->fetch("SELECT * FROM week_settlements WHERE worker_id = :wid AND week_start = :w", ['wid' => $workerId, 'w' => $weekStart]);
        if ($existing) {
            $newPaid = $existing['paid'] ? 0 : 1;
            db()->update('week_settlements', ['paid' => $newPaid, 'paid_at' => $newPaid ? date('Y-m-d H:i:s') : null], 'id = :id', ['id' => $existing['id']]);
        } else {
            db()->insert('week_settlements', ['worker_id' => $workerId, 'week_start' => $weekStart, 'paid' => 1, 'paid_at' => date('Y-m-d H:i:s')]);
        }
        header('Location: /admin/worker.php?id=' . $workerId);
        exit;
    }
}

// Gather all weeks that have entries, plus the current week even if empty
$weekStarts = db()->fetchAll("SELECT DISTINCT week_start FROM day_entries WHERE worker_id = :wid ORDER BY week_start DESC", ['wid' => $workerId]);
$weekStartList = array_column($weekStarts, 'week_start');
if (!in_array(currentWeekStart(), $weekStartList, true)) {
    array_unshift($weekStartList, currentWeekStart());
}
rsort($weekStartList);

$settlements = db()->fetchAll("SELECT * FROM week_settlements WHERE worker_id = :wid", ['wid' => $workerId]);
$paidMap = [];
foreach ($settlements as $s) { $paidMap[$s['week_start']] = (bool) $s['paid']; }

$allEntries = db()->fetchAll("SELECT * FROM day_entries WHERE worker_id = :wid", ['wid' => $workerId]);
$entriesByDate = [];
foreach ($allEntries as $en) { $entriesByDate[$en['work_date']] = $en; }

$pageTitle = $worker['name'] . ' - ChuckCo Time Keeper';
require_once __DIR__ . '/../includes/header.php';
?>
<div class="topbar">
    <h1><?= e($worker['name']) ?></h1>
    <a href="/admin/index.php" class="logout">&larr; Back</a>
</div>
<div class="container">

    <div class="card">
        <h3>Links</h3>
        <div class="link-row">
            <a class="btn btn-sm btn-secondary" href="/w.php?t=<?= e($worker['entry_token']) ?>" target="_blank">Entry Link</a>
            <a class="btn btn-sm btn-secondary" href="/s.php?t=<?= e($worker['share_token']) ?>" target="_blank">Their Screenshot</a>
            <a class="btn btn-sm btn-secondary" href="/p.php?t=<?= e($worker['payer_token']) ?>" target="_blank">My Screenshot</a>
        </div>
    </div>

    <?php foreach ($weekStartList as $weekStart):
        $dates = getWeekDates($weekStart);
        $weekEntries = [];
        foreach ($dates as $d) { if (isset($entriesByDate[$d])) $weekEntries[] = $entriesByDate[$d]; }
        $owed = calcOwed($weekEntries);
        $isPaid = $paidMap[$weekStart] ?? false;
    ?>
    <div class="card">
        <div style="display:flex; justify-content:space-between; align-items:center;">
            <h3 style="margin:0;">Week of <?= e(dayLabel($weekStart)) ?></h3>
            <span class="badge <?= $isPaid ? 'badge-full' : 'badge-absent' ?>"><?= $isPaid ? 'Paid' : 'Unpaid' ?></span>
        </div>

        <?php foreach ($dates as $date):
            $entry = $entriesByDate[$date] ?? null;
            $status = $entry['status'] ?? null;
        ?>
        <div class="day-tap" style="flex-wrap:wrap;">
            <div style="flex:1; min-width:100%;">
                <div class="date"><?= e(dayLabel($date)) ?></div>
                <?php if (!empty($entry['location'])): ?>
                    <div class="reason-text"><?= e($entry['location']) ?></div>
                <?php endif; ?>
                <?php if ($status === 'absent' && !empty($entry['absence_reason'])): ?>
                    <div class="reason-text"><?= e($entry['absence_reason']) ?></div>
                <?php endif; ?>
            </div>
            <form method="POST" style="width:100%; margin-top:0.5rem;">
                <input type="hidden" name="action" value="set_day">
                <input type="hidden" name="date" value="<?= e($date) ?>">
                <div class="day-btn-row">
                    <button type="submit" name="status" value="full" class="day-btn <?= $status === 'full' ? 'active-full' : '' ?>">Full</button>
                    <button type="submit" name="status" value="half" class="day-btn <?= $status === 'half' ? 'active-half' : '' ?>">Half</button>
                    <button type="submit" name="status" value="absent" class="day-btn <?= $status === 'absent' ? 'active-absent' : '' ?>">Off</button>
                </div>
                <div class="day-field-row">
                    <input type="text" name="location" class="form-input" placeholder="Location" value="<?= e($entry['location'] ?? '') ?>">
                </div>
                <div class="day-field-row">
                    <input type="text" name="reason" class="form-input" placeholder="Reason if off" value="<?= e($entry['absence_reason'] ?? '') ?>">
                </div>
            </form>
        </div>
        <?php endforeach; ?>

        <div class="owed-total">
            <span>Owed</span>
            <span><?= formatCurrency($owed) ?></span>
        </div>
        <form method="POST" style="margin-top:0.75rem;">
            <input type="hidden" name="action" value="toggle_paid">
            <input type="hidden" name="week_start" value="<?= e($weekStart) ?>">
            <button type="submit" class="btn <?= $isPaid ? 'btn-secondary' : 'btn-success' ?> btn-block">
                <?= $isPaid ? 'Mark as Unpaid' : 'Mark as Paid' ?>
            </button>
        </form>
    </div>
    <?php endforeach; ?>

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