<?php
// save.php
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $timesheetId = $_POST['timesheet_id']; 
    $weekEnding = $_POST['week_ending'];
    $status = $_POST['status_action']; 
    $hoursData = $_POST['hours'] ?? [];
    $onCall = isset($_POST['on_call']) ? 1 : 0;
    
    $note1 = $_POST['note_1'] ?? '';
    $note2 = $_POST['note_2'] ?? '';
    $note3 = $_POST['note_3'] ?? '';
    $note4 = $_POST['note_4'] ?? '';
    $note5 = $_POST['note_5'] ?? '';

    try {
        $pdo->beginTransaction();

        if (empty($timesheetId)) {
            $stmt = $pdo->prepare("INSERT INTO timesheets (user_id, week_ending_date, status, on_call, note_1, note_2, note_3, note_4, note_5) VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$weekEnding, $status, $onCall, $note1, $note2, $note3, $note4, $note5]);
            $timesheetId = $pdo->lastInsertId();
        } else {
            $stmt = $pdo->prepare("UPDATE timesheets SET week_ending_date = ?, status = ?, on_call = ?, note_1 = ?, note_2 = ?, note_3 = ?, note_4 = ?, note_5 = ? WHERE id = ?");
            $stmt->execute([$weekEnding, $status, $onCall, $note1, $note2, $note3, $note4, $note5, $timesheetId]);
            $stmtDel = $pdo->prepare("DELETE FROM time_entries WHERE timesheet_id = ?");
            $stmtDel->execute([$timesheetId]);
        }

        $stmtEntry = $pdo->prepare("INSERT INTO time_entries (timesheet_id, account_id, entry_date, hours) VALUES (?, ?, ?, ?)");
        foreach ($hoursData as $accountId => $days) {
            foreach ($days as $dayIndex => $hours) {
                if (is_numeric($hours) && $hours > 0) {
                    $daysToSubtract = 6 - $dayIndex;
                    $entryDate = date('Y-m-d', strtotime("$weekEnding - $daysToSubtract days"));
                    $stmtEntry->execute([$timesheetId, $accountId, $entryDate, $hours]);
                }
            }
        }
        $pdo->commit();

        if ($status === 'submitted') {
            header("Location: timesheet.php?print_id=" . $timesheetId);
        } else {
            header("Location: timesheet.php");
        }
        exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        die("Error saving: " . $e->getMessage());
    }
}
?>