<?php
include('../include/auth.php');
include('../include/lskfjwfe.php'); // Correct database connectivity file

header('Content-Type: application/json'); // Ensure JSON response type

// Check if the form data is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fleet_id = $_POST['fleet_id'] ?? null;
    $kteo_date = $_POST['kteo_date'] ?? null;
    $user_id = $userid; // Assume $userid is already available from auth.php

    // Validate input
    if ($fleet_id && $kteo_date) {
        // Convert kteo_date to timestamp
        $kteo_timestamp = strtotime($kteo_date);

        // Update the fleet table
        $update_query = "UPDATE fleet SET fleet_kteo = ? WHERE fleet_id = ?";
        $stmt = $db2->prepare($update_query);
        $stmt->bind_param("ii", $kteo_timestamp, $fleet_id);

        if ($stmt->execute()) {
            // Log the action
            $log_message = "Updated KTEO until date to " . date('d/m/Y', $kteo_timestamp) . " for vehicle ID $fleet_id.";
            $log_query = "INSERT INTO action_logs (user_id, action_type, action_details, action_timestamp) VALUES (?, 'Update KTEO', ?, ?)";
            $log_stmt = $db2->prepare($log_query);
            $log_stmt->bind_param("isi", $user_id, $log_message, time());
            $log_stmt->execute();

            echo json_encode(['success' => true, 'message' => 'Update successful']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update KTEO.']);
        }

        $stmt->close();
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid input.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
?>
