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

// --- Handle Timesheet Deletion ---
if (isset($_GET['delete_timesheet'])) {
    $tid = $_GET['delete_timesheet'];
    
    // Delete all time entries first
    $stmtDelEntries = $pdo->prepare("DELETE FROM time_entries WHERE timesheet_id = ?");
    $stmtDelEntries->execute([$tid]);
    
    // Delete the timesheet
    $stmtDelTs = $pdo->prepare("DELETE FROM timesheets WHERE id = ?");
    $stmtDelTs->execute([$tid]);
    
    // Redirect to the list view or dashboard
    header("Location: timesheet.php"); 
    exit;
}
// ---------------------------------

$timesheetId = $_GET['id'] ?? null;
$existingEntries = []; 
$weekEndingDate = date('Y-m-d');
$status = 'new';
$onCall = 0;
$note1 = ''; $note2 = ''; $note3 = ''; $note4 = '';

if ($timesheetId) {
    $stmt = $pdo->prepare("SELECT * FROM timesheets WHERE id = ?");
    $stmt->execute([$timesheetId]);
    $ts = $stmt->fetch();
    if ($ts) {
        $weekEndingDate = $ts['week_ending_date'];
        $status = $ts['status'];
        $onCall = $ts['on_call']; 
        $note1 = $ts['note_1']; $note2 = $ts['note_2']; $note3 = $ts['note_3']; $note4 = $ts['note_4'];
        
        $stmtEntry = $pdo->prepare("SELECT account_id, entry_date, hours FROM time_entries WHERE timesheet_id = ?");
        $stmtEntry->execute([$timesheetId]);
        while ($row = $stmtEntry->fetch()) {
            $entryDate = new DateTime($row['entry_date']);
            $weekEnd = new DateTime($weekEndingDate);
            $diff = $entryDate->diff($weekEnd)->days; 
            $dayIndex = 6 - $diff;
            if ($dayIndex >= 0 && $dayIndex <= 6) {
                // If there are multiple entries for the same account on the same day (like auto-synced jobs), add them together
                if (!isset($existingEntries[$row['account_id']][$dayIndex])) {
                    $existingEntries[$row['account_id']][$dayIndex] = 0;
                }
                $existingEntries[$row['account_id']][$dayIndex] += (float)$row['hours'];
            }
        }
    }
}

$sql = "SELECT l.id as loc_id, l.name as loc_name, a.id as acc_id, a.code, a.description, a.category
        FROM locations l JOIN accounts a ON l.id = a.location_id
        ORDER BY l.id, a.category DESC, a.code";
$stmt = $pdo->query($sql);
$data = [];
while ($row = $stmt->fetch()) { $data[$row['loc_name']][$row['category']][] = $row; }

$stmtGeneral = $pdo->query("SELECT id as acc_id, code, description, category FROM accounts WHERE location_id IS NULL ORDER BY category DESC, code");
$generalAccounts = [];
foreach ($stmtGeneral->fetchAll() as $ga) { $generalAccounts[$ga['category']][] = $ga; }

$pto = getPtoBalance($pdo, 1, (int)date('Y'));
$ptoYear = (int)date('Y');

$days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
$todayDayIndex = -1; // default: no highlight
if (!empty($weekEndingDate)) {
    $weekEnd = new DateTime($weekEndingDate);
    $today = new DateTime(date('Y-m-d'));
    $diff = $today->diff($weekEnd)->days;
    if ($today <= $weekEnd) {
        $idx = 6 - $diff;
        if ($idx >= 0 && $idx <= 6) {
            $todayDayIndex = $idx;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
    <meta charset="UTF-8">
    <title>Timesheet Editor - 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">
    <style>
        input[type=number] {
            -moz-appearance: textfield;
            appearance: textfield;
        }
        input[type=number]::-webkit-inner-spin-button, 
        input[type=number]::-webkit-outer-spin-button { 
            -webkit-appearance: none; 
            margin: 0; 
        }
        .sheet-input:focus { background-color: #e0f2fe; outline: 2px solid #3b82f6; outline-offset: -2px; }
        .dark .sheet-input:focus { background-color: #1e3a8a; outline: 2px solid #60a5fa; }
        .note-input { border: none; border-bottom: 1px solid #9ca3af; background: transparent; padding: 4px 0; margin-bottom: 4px; }
        .note-input:focus { outline: none; border-bottom: 2px solid #3b82f6; }
        .dark .note-input { border-bottom-color: #4b5563; color: white; }
        .dark .note-input:focus { border-bottom-color: #60a5fa; }
        @keyframes pulse-text { 0%, 100% { opacity: 1; } 50% { opacity: .5; } }
        .saving { animation: pulse-text 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite; }
    </style>
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-200 h-full flex overflow-hidden text-xs">

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

    <main class="flex-1 flex flex-col h-full overflow-hidden relative">
        
        <header class="h-14 bg-white dark:bg-gray-800 shadow flex items-center px-6 justify-between shrink-0 z-10">
            <div class="flex items-center gap-4">
                <a href="timesheet.php" class="text-gray-500 hover:text-blue-500 text-sm"><i class="fas fa-arrow-left"></i> Back</a>
                <h2 class="font-bold text-lg text-gray-700 dark:text-gray-200">
                    <?php echo $timesheetId ? "Editing Timesheet #<span id='displayId'>$timesheetId</span>" : "New Timesheet <span id='displayId'></span>"; ?>
                </h2>
            </div>
            <div class="flex items-center gap-3">
                <span class="text-gray-400 text-[10px] uppercase font-bold tracking-wider">Status: <?php echo strtoupper($status); ?></span>
                <div class="bg-gray-200 dark:bg-gray-700 px-3 py-1 rounded text-gray-700 dark:text-gray-200 font-mono text-[10px] uppercase">Tech: CHRIS</div>
            </div>
        </header>

        <div class="flex-1 overflow-auto p-4 pb-24">
            <form id="mainForm" method="POST" action="save.php" class="max-w-6xl mx-auto bg-white dark:bg-gray-800 shadow-sm border border-gray-300 dark:border-gray-700 p-6 rounded">
                <input type="hidden" name="timesheet_id" id="timesheetId" value="<?php echo htmlspecialchars($timesheetId ?? ''); ?>">
                <input type="hidden" name="status_action" id="statusAction" value="draft">
                
                <div class="flex justify-end mb-4 items-center gap-2">
                    <span class="text-gray-500 dark:text-gray-400 font-bold uppercase text-[10px]">Week Ending:</span>
                    <input type="date" name="week_ending" id="weekEnding" value="<?php echo $weekEndingDate; ?>" class="bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 py-1 font-mono text-sm focus:outline-none focus:border-blue-500" onchange="triggerAutosave()">
                </div>

                <?php foreach ($data as $location => $categories): ?>
                    <div class="mb-6 border border-gray-300 dark:border-gray-600 rounded overflow-hidden">
                        <div class="bg-slate-200 dark:bg-slate-700 border-b border-gray-300 dark:border-gray-600 px-3 py-2 font-bold text-gray-800 dark:text-gray-200 uppercase text-xs tracking-wider">
                            <?php echo htmlspecialchars($location); ?>
                        </div>
                        <table class="w-full border-collapse text-gray-600 dark:text-gray-300">
                            <thead>
                                <tr class="bg-gray-50 dark:bg-gray-800/50 border-b border-gray-300 dark:border-gray-600 text-[10px] text-gray-500 uppercase">
                                    <th class="border-r border-gray-300 dark:border-gray-600 px-2 py-1.5 text-left w-1/3">Description</th>
                                    <th class="border-r border-gray-300 dark:border-gray-600 px-2 py-1.5 text-left w-20">Code</th>
                                    <?php foreach ($days as $day): ?>
                                        <?php $dayIdx = array_search($day, $days); ?>
<th class="border-r border-gray-300 dark:border-gray-600 px-1 py-1.5 w-10 text-center <?= $dayIdx === $todayDayIndex ? 'bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300' : '' ?>"><?php echo $day; ?></th>                                    <?php endforeach; ?>
                                    <th class="px-2 py-1.5 w-14 text-right">Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($categories as $catName => $accounts): ?>
                                    <tr class="bg-gray-100 dark:bg-gray-900 border-b border-gray-300 dark:border-gray-600">
                                        <td colspan="10" class="px-2 py-1 font-bold text-gray-500 dark:text-gray-400 italic text-[10px]">
                                            <?php echo htmlspecialchars($catName); ?> ACCOUNTS
                                        </td>
                                    </tr>
                                    <?php foreach ($accounts as $acc): ?>
                                        <tr class="border-b border-gray-200 dark:border-gray-700 hover:bg-blue-50 dark:hover:bg-gray-700/50 transition">
                                            <td class="border-r border-gray-200 dark:border-gray-700 px-2 py-1 truncate"><?php echo htmlspecialchars($acc['description']); ?></td>
                                            <td class="border-r border-gray-200 dark:border-gray-700 px-2 py-1 font-mono text-gray-400 text-[10px]"><?php echo htmlspecialchars($acc['code']); ?></td>
                                            <?php for ($i = 0; $i < 7; $i++): 
                                                $rawVal = $existingEntries[$acc['acc_id']][$i] ?? 0;
                                                $displayVal = ($rawVal > 0) ? $rawVal : '';
                                            ?>
                                                <td class="border-r border-gray-200 dark:border-gray-700 p-0 h-7 relative <?= $i === $todayDayIndex ? 'bg-blue-50 dark:bg-blue-900/20' : '' ?>">
                                                    <input type="number" step="0.25" min="0" max="24" name="hours[<?php echo $acc['acc_id']; ?>][<?php echo $i; ?>]" value="<?php echo $displayVal; ?>" data-day-index="<?php echo $i; ?>" class="sheet-input absolute inset-0 w-full h-full text-center bg-transparent border-none focus:ring-0 p-0 font-bold text-gray-800 dark:text-gray-200 placeholder-transparent" oninput="handleInput(this)">
                                                </td>
                                            <?php endfor; ?>
                                            <td class="px-2 py-1 text-right font-mono font-bold text-gray-800 dark:text-gray-200 row-total bg-gray-50 dark:bg-gray-800"></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endforeach; ?>

                <?php if (!empty($generalAccounts)): ?>
                <div class="mb-6 border border-gray-300 dark:border-gray-600 rounded overflow-hidden">
                    <div class="bg-slate-200 dark:bg-slate-700 border-b border-gray-300 dark:border-gray-600 px-3 py-2 font-bold text-gray-800 dark:text-gray-200 uppercase text-xs tracking-wider">
                        General
                    </div>
                    <table class="w-full border-collapse text-gray-600 dark:text-gray-300">
                        <thead>
                            <tr class="bg-gray-50 dark:bg-gray-800/50 border-b border-gray-300 dark:border-gray-600 text-[10px] text-gray-500 uppercase">
                                <th class="border-r border-gray-300 dark:border-gray-600 px-2 py-1.5 text-left w-1/3">Description</th>
                                <th class="border-r border-gray-300 dark:border-gray-600 px-2 py-1.5 text-left w-20">Code</th>
                                <?php foreach ($days as $day): ?>
                                    <?php $dayIdx = array_search($day, $days); ?>
                                    <th class="border-r border-gray-300 dark:border-gray-600 px-1 py-1.5 w-10 text-center <?= $dayIdx === $todayDayIndex ? 'bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300' : '' ?>"><?= $day ?></th>
                                <?php endforeach; ?>
                                <th class="px-2 py-1.5 w-14 text-right">Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($generalAccounts as $catName => $accounts): ?>
                                <?php foreach ($accounts as $acc): ?>
                                    <tr class="border-b border-gray-200 dark:border-gray-700 hover:bg-blue-50 dark:hover:bg-gray-700/50 transition">
                                        <td class="border-r border-gray-200 dark:border-gray-700 px-2 py-1 truncate"><?= htmlspecialchars($acc['description']) ?></td>
                                        <td class="border-r border-gray-200 dark:border-gray-700 px-2 py-1"></td>
                                        <?php for ($i = 0; $i < 7; $i++):
                                            $rawVal = $existingEntries[$acc['acc_id']][$i] ?? 0;
                                            $displayVal = ($rawVal > 0) ? $rawVal : '';
                                        ?>
                                            <td class="border-r border-gray-200 dark:border-gray-700 p-0 h-7 relative <?= $i === $todayDayIndex ? 'bg-blue-50 dark:bg-blue-900/20' : '' ?>">
                                                <input type="number" step="0.25" min="0" max="24" name="hours[<?= $acc['acc_id'] ?>][<?= $i ?>]" value="<?= $displayVal ?>" data-day-index="<?= $i ?>" class="sheet-input absolute inset-0 w-full h-full text-center bg-transparent border-none focus:ring-0 p-0 font-bold text-gray-800 dark:text-gray-200 placeholder-transparent" oninput="handleInput(this)">
                                            </td>
                                        <?php endfor; ?>
                                        <td class="px-2 py-1 text-right font-mono font-bold text-gray-800 dark:text-gray-200 row-total bg-gray-50 dark:bg-gray-800"></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>

                <div class="mb-6 border border-gray-300 dark:border-gray-600 rounded bg-gray-50 dark:bg-gray-900">
                    <table class="w-full border-collapse font-bold text-gray-800 dark:text-gray-200">
                        <tbody>
                            <tr class="h-8">
                                <td class="w-1/3 px-2 py-1 text-right border-r border-gray-300 dark:border-gray-600 uppercase text-[10px]">Daily Totals</td>
                                <td class="w-20 border-r border-gray-300 dark:border-gray-600"></td>
                                <?php for ($i = 0; $i < 7; $i++): ?>
                                    <td class="w-10 text-center border-r border-gray-300 dark:border-gray-600 text-blue-600 dark:text-blue-400 font-mono <?= $i === $todayDayIndex ? 'bg-blue-100 dark:bg-blue-900/40' : '' ?>" id="day-total-<?php echo $i; ?>"></td>
                                <?php endfor; ?>
                                <td class="w-14 text-right px-2 py-1 font-mono text-sm text-green-600 dark:text-green-400" id="finalGrandTotal"></td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <?php
                    if ($pto['remaining'] <= 0) $remainColor = 'text-red-600 dark:text-red-400';
                    elseif ($pto['remaining'] <= 8) $remainColor = 'text-amber-600 dark:text-amber-400';
                    else $remainColor = 'text-emerald-600 dark:text-emerald-400';
                ?>
                <div class="mb-6 border border-gray-300 dark:border-gray-600 rounded bg-gray-50 dark:bg-gray-900 p-4">
                    <div class="text-[10px] font-bold text-gray-400 uppercase tracking-wide mb-3">PTO Balance — <?= $ptoYear ?></div>
                    <div class="flex items-center gap-8">
                        <div>
                            <div class="text-[10px] text-gray-400 uppercase tracking-wider">Allotted</div>
                            <div class="font-mono font-bold text-gray-800 dark:text-gray-200 text-lg"><?= number_format($pto['allotted'], 1) ?><span class="text-xs font-normal text-gray-400 ml-0.5">h</span></div>
                        </div>
                        <div>
                            <div class="text-[10px] text-gray-400 uppercase tracking-wider">Used</div>
                            <div class="font-mono font-bold text-gray-800 dark:text-gray-200 text-lg"><?= number_format($pto['used'], 1) ?><span class="text-xs font-normal text-gray-400 ml-0.5">h</span></div>
                        </div>
                        <div>
                            <div class="text-[10px] text-gray-400 uppercase tracking-wider">Remaining</div>
                            <div class="font-mono font-bold text-lg <?= $remainColor ?>"><?= number_format($pto['remaining'], 1) ?><span class="text-xs font-normal ml-0.5">h</span></div>
                        </div>
                    </div>
                </div>

                <div class="border border-gray-300 dark:border-gray-600 rounded bg-gray-50 dark:bg-gray-900 p-4">
                    <div class="text-[10px] font-bold text-gray-400 uppercase tracking-wide mb-2">Notes</div>
                    <input type="text" id="note1" name="note_1" value="<?php echo htmlspecialchars($note1); ?>" class="note-input w-full font-mono text-xs" oninput="triggerAutosave()">
                    <input type="text" id="note2" name="note_2" value="<?php echo htmlspecialchars($note2); ?>" class="note-input w-full font-mono text-xs" oninput="triggerAutosave()">
                    <input type="text" id="note3" name="note_3" value="<?php echo htmlspecialchars($note3); ?>" class="note-input w-full font-mono text-xs" oninput="triggerAutosave()">
                    <input type="text" id="note4" name="note_4" value="<?php echo htmlspecialchars($note4); ?>" class="note-input w-full font-mono text-xs" oninput="triggerAutosave()">
                </div>
            </form>
        </div>

        <div class="absolute bottom-0 left-0 right-0 bg-white dark:bg-gray-800 border-t border-gray-300 dark:border-gray-700 p-4 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.1)] flex justify-between items-center z-20">
            <div class="flex items-center gap-6">
                <div>
                    <span class="block text-gray-400 uppercase text-[10px] font-bold tracking-wider">Total Hours</span>
                    <span id="grandTotalDisplay" class="text-xl font-mono font-bold text-gray-900 dark:text-white"></span>
                </div>
                <div id="saveStatus" class="text-[10px] font-bold uppercase tracking-wide text-gray-400 flex items-center gap-1.5">
                    <i class="fas fa-check-circle"></i> Saved
                </div>
            </div>
            
            <div class="flex items-center gap-3">
                
                <?php if ($timesheetId): ?>
                <a href="timesheet_edit.php?delete_timesheet=<?= $timesheetId ?>" onclick="return confirm('WARNING: Are you sure you want to completely delete this timesheet and ALL of its recorded time entries?');" class="flex items-center gap-1.5 text-red-600 hover:text-red-800 bg-red-50 hover:bg-red-100 dark:bg-red-900/30 dark:text-red-400 dark:hover:bg-red-900/50 border border-red-200 dark:border-red-800 px-4 py-1.5 rounded text-[10px] font-bold uppercase tracking-wider transition">
                    <i class="fas fa-trash-alt"></i> Delete
                </a>
                <?php endif; ?>

                <div class="flex items-center gap-2 bg-gray-100 dark:bg-gray-700 px-3 py-1.5 rounded border border-gray-200 dark:border-gray-600">
                    <input type="checkbox" name="on_call" id="onCall" value="1" form="mainForm" <?php echo ($onCall == 1) ? 'checked' : ''; ?> class="w-3.5 h-3.5 text-blue-600 rounded border-gray-300 focus:ring-blue-500 cursor-pointer" onchange="triggerAutosave()">
                    <label for="onCall" class="text-[10px] font-bold uppercase text-gray-600 dark:text-gray-300 cursor-pointer select-none">On Call</label>
                </div>

                <button type="button" onclick="clearForm()" class="text-gray-600 hover:text-gray-800 bg-gray-50 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 border border-gray-300 dark:border-gray-600 px-4 py-1.5 rounded text-[10px] font-bold uppercase tracking-wider transition">
                    Clear Grid
                </button>

                <button type="submit" form="mainForm" onclick="document.getElementById('statusAction').value='submitted';" class="bg-blue-600 hover:bg-blue-500 text-white px-6 py-1.5 rounded shadow text-[10px] font-bold uppercase tracking-wider transition">
                    Submit & Print
                </button>
            </div>
        </div>
    </main>

    <script>
        let autosaveTimeout;
        const statusEl = document.getElementById('saveStatus');
        const idField = document.getElementById('timesheetId');

        function handleInput(input) { calc(input); calcColumns(); triggerAutosave(); }

        function triggerAutosave() {
            statusEl.innerHTML = '<span class="saving text-blue-500"><i class="fas fa-sync fa-spin"></i> Saving...</span>';
            clearTimeout(autosaveTimeout);
            autosaveTimeout = setTimeout(performAutosave, 1000);
        }

        function performAutosave() {
            const formData = new FormData(document.getElementById('mainForm'));
            const data = {
                timesheet_id: formData.get('timesheet_id'),
                week_ending: formData.get('week_ending'),
                on_call: document.getElementById('onCall').checked ? 1 : 0,
                note_1: document.getElementById('note1').value,
                note_2: document.getElementById('note2').value,
                note_3: document.getElementById('note3').value,
                note_4: document.getElementById('note4').value,
                hours: {}
            };

            for (let [key, value] of formData.entries()) {
                if (key.startsWith('hours[')) {
                    const match = key.match(/hours\[(\d+)\]\[(\d+)\]/);
                    if (match) {
                        const accId = match[1]; const day = match[2];
                        if (!data.hours[accId]) data.hours[accId] = {};
                        data.hours[accId][day] = value;
                    }
                }
            }

            fetch('autosave.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) })
            .then(async r => {
                if (!r.ok) { const text = await r.text(); throw new Error("Server error: " + text); }
                return r.json();
            })
            .then(result => {
                if (result.status === 'success') {
                    statusEl.innerHTML = '<span class="text-emerald-500"><i class="fas fa-check-circle"></i> Saved</span>';
                    if (!idField.value && result.timesheet_id) {
                        idField.value = result.timesheet_id;
                        document.getElementById('displayId').innerText = result.timesheet_id;
                        window.history.replaceState({}, '', `timesheet_edit.php?id=${result.timesheet_id}`);
                        window.location.reload(); // Reload to show the delete button if newly created
                    }
                } else {
                    console.error("Database Error:", result.message);
                    statusEl.innerHTML = '<span class="text-red-500" title="'+result.message+'"><i class="fas fa-exclamation-circle"></i> Error Saving</span>';
                }
            })
            .catch(err => {
                console.error("Autosave Failed:", err);
                statusEl.innerHTML = '<span class="text-red-500"><i class="fas fa-exclamation-triangle"></i> Network Error</span>';
            });
        }

        function calc(input) {
            const row = input.closest('tr');
            let rowSum = 0;
            row.querySelectorAll('input[type="number"]').forEach(f => { rowSum += parseFloat(f.value) || 0; });
            row.querySelector('.row-total').textContent = rowSum === 0 ? '' : parseFloat(rowSum.toFixed(2));
        }
        
        function calcColumns() {
            let grandTotal = 0;
            for (let i = 0; i < 7; i++) {
                let daySum = 0;
                document.querySelectorAll(`input[data-day-index="${i}"]`).forEach(inp => { daySum += parseFloat(inp.value) || 0; });
                const cell = document.getElementById(`day-total-${i}`);
                // Changed '0' to ''
                if (cell) cell.textContent = daySum === 0 ? '' : parseFloat(daySum.toFixed(2));
                grandTotal += daySum;
            }
            // Check if grandTotal is 0, if so, output an empty string
            const grandStr = grandTotal === 0 ? '' : parseFloat(grandTotal.toFixed(2));
            document.getElementById('grandTotalDisplay').textContent = grandStr;
            document.getElementById('finalGrandTotal').textContent = grandStr;
        }

        function clearForm() {
            if (!confirm("Clear grid?")) return;
            document.querySelectorAll('input[type="number"], .note-input').forEach(i => i.value = '');
            document.querySelectorAll('.row-total').forEach(s => s.textContent = '');
            // Changed all '0's to ''
            for(let i=0; i<7; i++) document.getElementById(`day-total-${i}`).textContent = '';
            document.getElementById('grandTotalDisplay').textContent = '';
            document.getElementById('finalGrandTotal').textContent = '';
            triggerAutosave();
        }
        
        document.addEventListener('DOMContentLoaded', () => {
            document.querySelectorAll('tr').forEach(tr => {
                const firstInput = tr.querySelector('input[type="number"]');
                if(firstInput) calc(firstInput);
            });
            calcColumns();
        });

    </script>
</body>
</html>
