<?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;
    $road_tax_date = $_POST['road_tax_date'] ?? null;
    $user_id = $userid; // Assume $userid is already available from auth.php

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

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

        if ($stmt->execute()) {
            // Log the action
            $log_message = "Updated road tax until date to " . date('d/m/Y', $road_tax_timestamp) . " for vehicle ID $fleet_id.";
            $log_query = "INSERT INTO action_logs (user_id, action_type, action_details, action_timestamp) VALUES (?, 'Update Road Tax', ?, ?)";
            $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 road tax.']);
        }

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