<?php
require 'db.php';

// Fetch all timesheets
$stmt = $pdo->query("
    SELECT t.*, u.full_name,
    (SELECT SUM(hours) FROM time_entries WHERE timesheet_id = t.id) as total_hours
    FROM timesheets t 
    JOIN users u ON t.user_id = u.id 
    ORDER BY t.week_ending_date DESC, t.id DESC
");
$timesheets = $stmt->fetchAll();

$autoPrintId = isset($_GET['print_id']) ? (int)$_GET['print_id'] : null;
?>

<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Timesheets - 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 z-10">
        <button class="open-sidebar-btn md:hidden mr-3 text-gray-500 hover:text-blue-600 transition">
    <i class="fas fa-bars text-xl"></i>
</button>    
        <h2 class="font-bold text-lg text-gray-700 dark:text-gray-200">My Timesheets</h2>
            
            <a href="timesheet_edit.php" class="bg-blue-600 hover:bg-blue-500 text-white px-4 py-2 rounded shadow font-bold uppercase text-xs transition flex items-center">
                <i class="fas fa-plus mr-2"></i> Start New Week
            </a>
        </header>

        <div class="flex-1 overflow-auto p-4">
            <div class="bg-white dark:bg-gray-800 rounded shadow overflow-hidden border dark:border-gray-700">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="bg-gray-100 dark:bg-gray-700/80 text-[10px] uppercase text-gray-500 dark:text-gray-400 font-bold border-b dark:border-gray-700 tracking-wider">
                            <th class="px-6 py-3">Week Ending</th>
                            <th class="px-6 py-3 text-center">Status</th>
                            <th class="px-6 py-3 text-center">Total Hours</th>
                            <th class="px-6 py-3 text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 dark:divide-gray-700 text-xs">
                        <?php if (count($timesheets) === 0): ?>
                            <tr><td colspan="4" class="px-6 py-8 text-center text-gray-500 italic">No timesheets found.</td></tr>
                        <?php endif; ?>

                        <?php foreach ($timesheets as $ts): ?>
                            <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors">
                                <td class="px-6 py-3 font-medium text-gray-900 dark:text-gray-200">
                                    <?php echo date('M j, Y', strtotime($ts['week_ending_date'])); ?>
                                </td>
                                <td class="px-6 py-3 text-center">
                                    <?php if ($ts['status'] === 'submitted'): ?>
                                        <span class="px-2 inline-flex text-[10px] font-bold uppercase rounded-full bg-green-100 text-green-800 dark:bg-green-900/50 dark:text-green-400">Submitted</span>
                                    <?php else: ?>
                                        <span class="px-2 inline-flex text-[10px] font-bold uppercase rounded-full bg-yellow-100 text-yellow-800 dark:bg-yellow-900/50 dark:text-yellow-400">Draft</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-3 text-center font-mono text-gray-500">
                                    <?php echo number_format($ts['total_hours'], 2); ?>
                                </td>
                                <td class="px-6 py-3 text-right space-x-3">
                                    <a href="timesheet_edit.php?id=<?php echo $ts['id']; ?>" class="text-blue-600 hover:text-blue-500 font-bold uppercase tracking-wide text-[10px]">Edit</a>
                                    <button onclick="printTimesheet(<?php echo $ts['id']; ?>, 'print_alt.php')" class="text-gray-500 hover:text-gray-300 font-bold uppercase tracking-wide text-[10px] transition">Print</button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>

    <iframe id="printFrame" name="printFrame" style="position:absolute; top:-9999px; left:-9999px; width:1px; height:1px;"></iframe>

    <script>
        function printTimesheet(id, page) {
            const iframe = document.getElementById('printFrame');
            iframe.src = page + '?id=' + id;
            iframe.onload = function() {
                setTimeout(function() {
                    iframe.contentWindow.focus();
                    iframe.contentWindow.print();
                }, 500);
            };
        }

        <?php if ($autoPrintId): ?>
            // Updated to automatically trigger the alt print format on save
            printTimesheet(<?php echo $autoPrintId; ?>, 'print_alt.php');
            window.history.replaceState({}, document.title, "timesheet.php");
        <?php endif; ?>

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