<?php
// autosave.php
require 'db.php'; // Updated to use the unified database connection
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Read the raw JSON payload
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input) { 
        echo json_encode(['status' => 'error', 'message' => 'Invalid JSON input']); 
        exit; 
    }

    $timesheetId = $input['timesheet_id'] ?? null;
    $weekEnding = $input['week_ending'];
    $hoursData = $input['hours'] ?? [];
    $onCall = $input['on_call'] ?? 0;
    
    // Capture Notes
    $note1 = $input['note_1'] ?? '';
    $note2 = $input['note_2'] ?? '';
    $note3 = $input['note_3'] ?? '';
    $note4 = $input['note_4'] ?? '';
    $note5 = $input['note_5'] ?? '';
    
    $status = 'draft'; 

    try {
        $pdo->beginTransaction();

        if (empty($timesheetId)) {
            // INSERT New Timesheet
            $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 {
            // UPDATE Existing Timesheet
            $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]);
            
            // Clear only manually-entered entries (job-synced entries have a job_id and are managed by job_sync.php)
            $stmtDel = $pdo->prepare("DELETE FROM time_entries WHERE timesheet_id = ? AND job_id IS NULL");
            $stmtDel->execute([$timesheetId]);
        }

        // Build a map of job-synced hours (account_id => date => hours) so we don't double-count.
        // The grid loads ALL entries (manual + job-synced) summed together. Without this subtraction,
        // autosave would re-save job-synced hours as manual entries, duplicating them every save.
        $syncedMap = [];
        $stmtSynced = $pdo->prepare("SELECT account_id, entry_date, SUM(hours) as hours FROM time_entries WHERE timesheet_id = ? AND job_id IS NOT NULL GROUP BY account_id, entry_date");
        $stmtSynced->execute([$timesheetId]);
        foreach ($stmtSynced->fetchAll() as $row) {
            $syncedMap[$row['account_id']][$row['entry_date']] = (float)$row['hours'];
        }

        // Insert new grid data (manual entries have no job_id).
        // Subtract any job-synced hours for the same account/date so only the manually-entered delta is stored.
        $stmtEntry = $pdo->prepare("INSERT INTO time_entries (timesheet_id, account_id, entry_date, hours, job_id) VALUES (?, ?, ?, ?, NULL)");
        foreach ($hoursData as $accountId => $days) {
            foreach ($days as $dayIndex => $hours) {
                if ($hours !== '' && is_numeric($hours) && $hours > 0) {
                    $daysToSubtract = 6 - $dayIndex;
                    $entryDate = date('Y-m-d', strtotime("$weekEnding - $daysToSubtract days"));
                    $manualHours = max(0, (float)$hours - ($syncedMap[$accountId][$entryDate] ?? 0));
                    if ($manualHours > 0) {
                        $stmtEntry->execute([$timesheetId, $accountId, $entryDate, $manualHours]);
                    }
                }
            }
        }
        $pdo->commit();
        echo json_encode(['status' => 'success', 'timesheet_id' => $timesheetId]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}
?>