<?php
// Unified print template. Use ?format=standard or ?format=alt (default: alt)
require 'db.php';

$timesheetId = isset($_GET['id']) ? (int)$_GET['id'] : null;
if (!$timesheetId) { die("Error: No timesheet ID specified."); }

$format = ($_GET['format'] ?? 'alt') === 'standard' ? 'standard' : 'alt';

// CSS config per format
$css = [
    'standard' => [
        'body_size'    => '8.5px',
        'val_pop_size' => '9.5px',
        'hours_size'   => '11px',
        'note_height'  => '14px',
        'note_tall'    => '20px',
        'oncall_size'  => '14px',
        'footer_mb'    => '8px',
        'cert_mb'      => '15px',
        'header_mb'    => '8px',
        'td_padding'   => '1px 2px',
        'td_height'    => '12px',
        'grand_size'   => '13px',
        'no_blank_page' => 'html, body { height: max-content; }',
    ],
    'alt' => [
        'body_size'    => '9px',
        'val_pop_size' => '11px',
        'hours_size'   => '11px',
        'note_height'  => '16px',
        'note_tall'    => '32px',
        'oncall_size'  => '16px',
        'footer_mb'    => '15px',
        'cert_mb'      => '35px',
        'header_mb'    => '25px',
        'td_padding'   => '2px',
        'td_height'    => '12px',
        'grand_size'   => '14px',
        'no_blank_page' => '',
    ],
];
$c = $css[$format];

// 1. Fetch Header Info
try {
    $stmt = $pdo->prepare("SELECT t.*, u.full_name FROM timesheets t JOIN users u ON t.user_id = u.id WHERE t.id = ?");
    $stmt->execute([$timesheetId]);
    $header = $stmt->fetch();
} catch (PDOException $e) {
    die("Database Error (Header).");
}
if (!$header) { die("Timesheet not found."); }

// 2. Fetch ALL Accounts
try {
    $stmt = $pdo->prepare("
        SELECT
            COALESCE(l.name, 'General') as loc_name,
            l.id as loc_id,
            a.id as acc_id,
            a.category,
            a.description,
            a.code,
            te.entry_date,
            te.hours
        FROM accounts a
        LEFT JOIN locations l ON a.location_id = l.id
        LEFT JOIN time_entries te ON te.account_id = a.id AND te.timesheet_id = ?
        ORDER BY (l.id IS NULL), l.id, a.category DESC, a.code, te.entry_date
    ");
    $stmt->execute([$timesheetId]);
    $rows = $stmt->fetchAll();
} catch (PDOException $e) {
    die("Database Error (Rows).");
}

// 3. Process Data
$grid = [];
$totals = ['grand' => 0];

$weekEnding = new DateTime($header['week_ending_date']);
$dates = [];
$dayLabels = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
$dailyTotals = [];

for ($i = 6; $i >= 0; $i--) {
    $d = clone $weekEnding;
    $d->modify("-$i days");
    $dateStr = $d->format('Y-m-d');
    $dates[] = $dateStr;
    $dailyTotals[$dateStr] = 0;
}

foreach ($rows as $r) {
    $key = $r['loc_name'] . '|' . $r['category'] . '|' . $r['code'];
    if (!isset($grid[$key])) {
        $grid[$key] = ['meta' => $r, 'days' => array_fill_keys($dates, 0), 'row_total' => 0];
    }
    if ($r['entry_date'] && $r['hours']) {
        $val = (float)$r['hours'];
        $grid[$key]['days'][$r['entry_date']] = $val;
        $grid[$key]['row_total'] += $val;
        $totals['grand'] += $val;
        if (isset($dailyTotals[$r['entry_date']])) {
            $dailyTotals[$r['entry_date']] += $val;
        }
    }
}

$note1 = $header['note_1'] ?? '';
$note2 = $header['note_2'] ?? '';
$note3 = $header['note_3'] ?? '';
$note4 = $header['note_4'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Timesheet Print</title>
    <style>
        @media print {
            @page { margin: 0.25in; size: letter portrait; }
            * { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; color-adjust: exact !important; }
            body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            <?= $c['no_blank_page'] ?>
        }
        body { font-family: Arial, sans-serif; font-size: <?= $c['body_size'] ?>; color: #000; margin: 0; padding: 0; line-height: 1.1; }
        .container { width: 100%; box-sizing: border-box; }
        .top-header { width: 100%; border-collapse: collapse; margin-bottom: <?= $c['header_mb'] ?>; }
        .top-header td { padding: <?= $c['td_padding'] ?>; vertical-align: bottom; }
        .border-bottom { border-bottom: 1px solid #000; }
        .bottom-footer { margin-top: <?= $c['footer_mb'] ?>; width: 100%; page-break-inside: avoid; }
        .cert-text { font-size: <?= $c['body_size'] ?>; font-style: italic; margin-bottom: <?= $c['cert_mb'] ?>; }
        .footer-sig { border-top: 1px solid #000; width: 250px; padding-top: 2px; font-weight: bold; }
        .grid-table { width: 100%; border-collapse: collapse; border: 1px solid #000; }
        .grid-table th, .grid-table td { border: 1px solid #000; padding: <?= $c['td_padding'] ?>; height: <?= $c['td_height'] ?>; }
        .col-desc { width: 45%; text-align: left; padding-left: 5px !important; }
        .col-code { width: 8%; text-align: center; }
        .col-day { width: 5%; text-align: center; }
        .col-total { width: 6%; font-weight: bold; background-color: #f0f0f0; text-align: center; }
        .val-pop { font-size: <?= $c['val_pop_size'] ?>; font-weight: 700; }
        .hours-entered { font-size: <?= $c['hours_size'] ?>; font-weight: 900; color: #000 !important; }
        .loc-row td { background-color: #ccc; font-weight: bold; text-align: left; padding-left: 5px; text-transform: uppercase; }
        .cat-row td { text-align: left; padding-left: 5px; font-style: italic; font-size: 7.5px; background-color: #eee; }
        .notes-row td { height: <?= $c['note_height'] ?>; border-bottom: 1px solid #000; vertical-align: middle; }
        .notes-row-tall td { height: <?= $c['note_tall'] ?>; border-bottom: 1px solid #000; vertical-align: middle; }
        .totals-row td { font-weight: bold; background-color: #f0f0f0; border-top: 2px solid #000; }
    </style>
</head>
<body>
<div class="container">
    <table class="top-header">
        <tr>
            <td width="10%" class="border-bottom val-pop">Name:</td>
            <td width="30%" class="border-bottom val-pop"><?= htmlspecialchars($header['full_name']) ?></td>
            <td width="30%"></td>
            <td width="10%" class="border-bottom val-pop">Date:</td>
            <td width="20%" class="border-bottom val-pop"><?= htmlspecialchars($header['week_ending_date']) ?></td>
        </tr>
    </table>

    <table class="grid-table">
        <thead>
            <tr style="background-color:#fff; font-weight:bold;">
                <th class="col-desc"></th>
                <th class="col-code"></th>
                <?php foreach ($dayLabels as $d) echo "<th class='col-day'>$d</th>"; ?>
                <th class="col-total">TOTAL</th>
            </tr>
            <tr style="font-size:8px;">
                <th class="col-desc" style="text-align:right; font-weight:bold;">DATE:</th>
                <th class="col-code"></th>
                <?php foreach ($dates as $date) echo "<th class='val-pop'>" . date('m/d', strtotime($date)) . "</th>"; ?>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <?php
            $currentLoc = '';
            $currentCat = '';
            foreach ($grid as $key => $data):
                $meta = $data['meta'];
                $isPto = ($meta['category'] === 'PTO');
                if (!$isPto && $meta['loc_name'] !== $currentLoc) {
                    $currentLoc = $meta['loc_name'];
                    echo "<tr class='loc-row'><td colspan='10'>" . htmlspecialchars($currentLoc) . "</td></tr>";
                    $currentCat = '';
                }
                if (!$isPto && $meta['category'] !== $currentCat) {
                    $currentCat = $meta['category'];
                    if ($currentCat === 'EXPENSE') {
                        $catText = "EXPENSE ACCOUNTS--USE THESE ACCOUNTS FOR INSPECTION, REPAIR, REPLACEMENT &amp; MOVES.";
                    } elseif ($currentCat === 'CAPITAL') {
                        $catText = "CAPITAL ACCOUNTS--USE THESE ACCOUNTS FOR NEW PLANT ONLY! PLEASE LIST MATERIAL USED.";
                    } else {
                        $catText = htmlspecialchars($currentCat) . " ACCOUNTS";
                    }
                    echo "<tr class='cat-row'><td colspan='10'>$catText</td></tr>";
                }
            ?>
                <?php if ($isPto): ?>
                <tr><td colspan="10" style="border:none; height:6px;"></td></tr>
                <tr>
                    <td class="col-desc" style="font-weight:bold;"><?= htmlspecialchars($meta['description']) ?></td>
                    <td class="col-code" style="text-align:center;"><?= htmlspecialchars($meta['code']) ?></td>
                    <?php foreach ($dates as $d): ?>
                        <td class="col-day hours-entered" style="text-align:center;"><?= $data['days'][$d] > 0 ? (float)$data['days'][$d] : '' ?></td>
                    <?php endforeach; ?>
                    <td class="col-total hours-entered" style="text-align:center;"><?= $data['row_total'] > 0 ? (float)$data['row_total'] : '' ?></td>
                </tr>
                <?php else: ?>
                <tr>
                    <td class="col-desc"><?= htmlspecialchars($meta['description']) ?></td>
                    <td class="col-code"><?= htmlspecialchars($meta['code']) ?></td>
                    <?php foreach ($dates as $d): ?>
                        <td class="col-day hours-entered"><?= $data['days'][$d] > 0 ? (float)$data['days'][$d] : '' ?></td>
                    <?php endforeach; ?>
                    <td class="col-total hours-entered"><?= $data['row_total'] > 0 ? (float)$data['row_total'] : '' ?></td>
                </tr>
                <?php endif; ?>
            <?php endforeach; ?>

            <tr class="notes-row"><td colspan="10" style="text-align:left; padding-left:5px; font-style:italic;"><?= htmlspecialchars($note1) ?></td></tr>
            <tr class="notes-row"><td colspan="10" style="text-align:left; padding-left:5px;"><?= htmlspecialchars($note2) ?></td></tr>
            <tr class="notes-row"><td colspan="10" style="text-align:left; padding-left:5px;"><?= htmlspecialchars($note3) ?></td></tr>
            <tr class="notes-row"><td colspan="10" style="text-align:left; padding-left:5px;"><?= htmlspecialchars($note4) ?></td></tr>
            <tr class="notes-row-tall">
                <td colspan="10" style="text-align:center; font-weight:bold; color:red; font-size:<?= $c['oncall_size'] ?>; letter-spacing:1px;">
                    <?= ($header['on_call'] == 1) ? 'ON CALL' : '' ?>
                </td>
            </tr>
        </tbody>
        <tfoot>
            <tr class="totals-row val-pop">
                <td colspan="2" style="text-align:right; padding-right:10px;">DAILY TOTALS:</td>
                <?php foreach ($dates as $d): ?>
                    <td class="col-day hours-entered"><?= $dailyTotals[$d] > 0 ? (float)$dailyTotals[$d] : '' ?></td>
                <?php endforeach; ?>
                <td class="col-total hours-entered" style="border:2px solid #000; font-size:<?= $c['grand_size'] ?>;"><?= (float)$totals['grand'] ?></td>
            </tr>
        </tfoot>
    </table>

    <div class="bottom-footer">
        <div class="cert-text">I hereby certify this timesheet to be an accurate reflection of my time worked during this time period.</div>
        <div class="footer-sig">Signed:</div>
    </div>
</div>
</body>
</html>
