<?php
require 'db.php';
require_once 'helpers.php';

$user_id = 1;
$currentYear = (int)date('Y');
$success = false;
$error = '';

// Handle form save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $year      = (int)($_POST['year'] ?? $currentYear);
    $allotted  = (float)($_POST['allotted_hours'] ?? 0);
    $manual    = (float)($_POST['manual_adjustment'] ?? 0);

    try {
        $stmt = $pdo->prepare("
            INSERT INTO pto_balance (user_id, year, allotted_hours, manual_adjustment)
            VALUES (?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE allotted_hours = VALUES(allotted_hours), manual_adjustment = VALUES(manual_adjustment)
        ");
        $stmt->execute([$user_id, $year, $allotted, $manual]);
        $success = true;
    } catch (PDOException $e) {
        $error = "Save failed. Please try again.";
    }
}

// Load all years that have a pto_balance record, plus current year
$stmt = $pdo->prepare("SELECT year FROM pto_balance WHERE user_id = ? ORDER BY year DESC");
$stmt->execute([$user_id]);
$years = array_column($stmt->fetchAll(), 'year');
if (!in_array($currentYear, $years)) $years[] = $currentYear;
rsort($years);

// Selected year
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : $currentYear;
if (!in_array($selectedYear, $years)) $years[] = $selectedYear;
rsort($years);

$pto = getPtoBalance($pdo, $user_id, $selectedYear);
?>
<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
    <meta charset="UTF-8">
    <title>PTO Management - Tech Dash</title>
    <link rel="stylesheet" href="/assets/css/tailwind.min.css">
    
    <script>
        if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
            document.documentElement.style.backgroundColor = '#111827';
        } else {
            document.documentElement.classList.remove('dark');
            document.documentElement.style.backgroundColor = '#f3f4f6';
        }
    </script>
    <link href="/assets/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-200 h-full flex overflow-hidden text-sm">

    <?php include 'sidebar.php'; ?>

    <main class="flex-1 flex flex-col h-full overflow-hidden">
        <header class="h-14 bg-white dark:bg-gray-800 shadow flex items-center px-6 justify-between shrink-0">
            <h2 class="font-bold text-lg text-gray-700 dark:text-gray-200">PTO Management</h2>
            <div class="flex items-center gap-2">
                <?php foreach ($years as $y): ?>
                    <a href="pto_management.php?year=<?= $y ?>"
                       class="px-3 py-1 rounded text-[11px] font-bold uppercase tracking-wider border transition
                              <?= $y === $selectedYear
                                  ? 'bg-blue-600 text-white border-blue-600'
                                  : 'bg-white dark:bg-gray-700 text-gray-600 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:border-blue-400' ?>">
                        <?= $y ?>
                    </a>
                <?php endforeach; ?>
                <a href="pto_management.php?year=<?= $selectedYear + 1 ?>"
                   class="px-3 py-1 rounded text-[11px] font-bold uppercase tracking-wider border transition bg-white dark:bg-gray-700 text-gray-500 dark:text-gray-400 border-dashed border-gray-300 dark:border-gray-600 hover:border-blue-400">
                    + <?= $selectedYear + 1 ?>
                </a>
            </div>
        </header>

        <div class="flex-1 overflow-auto p-6">
            <div class="max-w-xl mx-auto space-y-6">

                <?php if ($success): ?>
                <div class="bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-200 dark:border-emerald-800 text-emerald-700 dark:text-emerald-400 px-4 py-3 rounded text-sm font-medium">
                    <i class="fas fa-check-circle mr-2"></i> Saved successfully.
                </div>
                <?php endif; ?>
                <?php if ($error): ?>
                <div class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-400 px-4 py-3 rounded text-sm font-medium">
                    <i class="fas fa-exclamation-circle mr-2"></i> <?= htmlspecialchars($error) ?>
                </div>
                <?php endif; ?>

                <!-- Balance Summary -->
                <div class="bg-white dark:bg-gray-800 rounded shadow border border-gray-200 dark:border-gray-700 p-5">
                    <div class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-4">
                        <?= $selectedYear ?> Balance Summary
                    </div>
                    <div class="grid grid-cols-3 gap-4 text-center">
                        <div>
                            <div class="text-[10px] text-gray-400 uppercase tracking-wider mb-1">Allotted</div>
                            <div class="text-2xl font-mono font-bold text-gray-800 dark:text-gray-100"><?= number_format($pto['allotted'], 1) ?><span class="text-sm font-normal text-gray-400 ml-0.5">h</span></div>
                        </div>
                        <div>
                            <div class="text-[10px] text-gray-400 uppercase tracking-wider mb-1">Used</div>
                            <div class="text-2xl font-mono font-bold text-gray-800 dark:text-gray-100"><?= number_format($pto['used'], 1) ?><span class="text-sm font-normal text-gray-400 ml-0.5">h</span></div>
                            <?php if ($pto['manual'] != 0): ?>
                            <div class="text-[10px] text-gray-400 mt-0.5"><?= number_format($pto['tracked'], 1) ?>h tracked + <?= number_format($pto['manual'], 1) ?>h manual</div>
                            <?php else: ?>
                            <div class="text-[10px] text-gray-400 mt-0.5"><?= number_format($pto['tracked'], 1) ?>h from timesheets</div>
                            <?php endif; ?>
                        </div>
                        <div>
                            <div class="text-[10px] text-gray-400 uppercase tracking-wider mb-1">Remaining</div>
                            <?php
                                if ($pto['remaining'] <= 0) $rc = 'text-red-600 dark:text-red-400';
                                elseif ($pto['remaining'] <= 8) $rc = 'text-amber-500 dark:text-amber-400';
                                else $rc = 'text-emerald-600 dark:text-emerald-400';
                            ?>
                            <div class="text-2xl font-mono font-bold <?= $rc ?>"><?= number_format($pto['remaining'], 1) ?><span class="text-sm font-normal ml-0.5">h</span></div>
                        </div>
                    </div>
                </div>

                <!-- Edit Form -->
                <div class="bg-white dark:bg-gray-800 rounded shadow border border-gray-200 dark:border-gray-700 p-5">
                    <div class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-4">
                        Edit <?= $selectedYear ?> Settings
                    </div>
                    <form method="POST" action="pto_management.php?year=<?= $selectedYear ?>" class="space-y-4">
                        <input type="hidden" name="year" value="<?= $selectedYear ?>">

                        <div>
                            <label class="block text-xs font-bold text-gray-600 dark:text-gray-300 mb-1">Allotted Hours</label>
                            <div class="text-[11px] text-gray-400 mb-2">Total PTO hours available for <?= $selectedYear ?>.</div>
                            <input type="number" name="allotted_hours" step="0.5" min="0"
                                   value="<?= number_format($pto['allotted'], 1) ?>"
                                   class="w-full bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 py-2 text-sm font-mono focus:outline-none focus:border-blue-500">
                        </div>

                        <div>
                            <label class="block text-xs font-bold text-gray-600 dark:text-gray-300 mb-1">Manual Adjustment</label>
                            <div class="text-[11px] text-gray-400 mb-2">Hours used outside the timesheet system (e.g. PTO taken before tracking began). Added to your timesheet-tracked hours to get total used.</div>
                            <input type="number" name="manual_adjustment" step="0.5"
                                   value="<?= number_format($pto['manual'], 1) ?>"
                                   class="w-full bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 py-2 text-sm font-mono focus:outline-none focus:border-blue-500">
                        </div>

                        <div class="pt-2">
                            <button type="submit"
                                    class="bg-blue-600 hover:bg-blue-500 text-white px-5 py-2 rounded text-xs font-bold uppercase tracking-wider transition shadow">
                                <i class="fas fa-save mr-1.5"></i> Save Changes
                            </button>
                        </div>
                    </form>
                </div>

            </div>
        </div>
    </main>
</body>
</html>
