<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user   = requireRole([1, 2, 5]); // Admin/Dev/HR only
$db     = getDB();
$action = post('action', '');

if ($action === 'add') {
    $jobCardId  = (int)post('job_card_id', 0);
    $eventType  = post('event_type', '');
    $eventTime  = post('event_time', '');
    $odoReading = post('odo_reading') !== null && post('odo_reading') !== '' ? (int)post('odo_reading') : null;

    if (!$jobCardId || !$eventType || !$eventTime) apiError('Missing required fields.', 422);

    $allowed = ['depart','arrive_site','start_work','depart_site','arrive_base',
                'pause_travel','resume_travel','pause_work','resume_work',
                'completed','internal_complete','invoiced','no_charge','cancelled'];
    if (!in_array($eventType, $allowed)) apiError('Invalid event type.', 422);

    // Require ODO for travel events
    $requiresOdo = ['depart','arrive_site','depart_site','arrive_base','pause_travel','resume_travel'];
    if (in_array($eventType, $requiresOdo) && $odoReading === null) apiError('ODO reading required for this event.', 422);

    $db->prepare("
        INSERT INTO job_card_time_logs (job_card_id, user_id, event_type, event_time, odo_reading)
        VALUES (?, ?, ?, ?, ?)
    ")->execute([$jobCardId, $user['id'], $eventType, $eventTime, $odoReading]);

    apiSuccess(['id' => $db->lastInsertId()], 'Event added.');
}

if ($action === 'update') {
    $id         = (int)post('id', 0);
    $eventTime  = post('event_time', '');
    $odoReading = post('odo_reading') !== null && post('odo_reading') !== '' ? (int)post('odo_reading') : null;

    if (!$id || !$eventTime) apiError('Missing required fields.', 422);

    $db->prepare("UPDATE job_card_time_logs SET event_time=?, odo_reading=? WHERE id=?")
       ->execute([$eventTime, $odoReading, $id]);

    apiSuccess([], 'Entry updated.');
}

if ($action === 'delete') {
    $id = (int)post('id', 0);
    if (!$id) apiError('Entry ID required.', 422);
    $db->prepare("DELETE FROM job_card_time_logs WHERE id=?")->execute([$id]);
    apiSuccess([], 'Entry deleted.');
}

apiError('Unknown action.', 422);