<?php
// get_last_fasttag.php
include("../config.php"); // Your database connection

$response = array();

if (isset($_POST['truck_no'])) {
    $truck_no = $_POST['truck_no'];

    // Query to get the last `fast_tag_closing` from the `trip` table for the selected truck_no
    $tripQuery = "SELECT fast_tag_closing FROM trip WHERE truck_no = '$truck_no' ORDER BY id DESC ";
    $tripResult = mysqli_query($conn, $tripQuery);

    if ($tripResult && mysqli_num_rows($tripResult) > 0) {
        // If there is a fast_tag_closing value from the `trip` table
        $tripRow = mysqli_fetch_assoc($tripResult);
        $response['fast_tag_opening'] = $tripRow['fast_tag_closing']; // Set fast tag closing as opening
    } else {
        // Debugging: Check if truck_mst query is being executed
        error_log("No record found in trip table for truck: $truck_no");

        // If no fast_tag_closing found, fetch `tr_fasttag_balance` from `truck_mst`
        $truckQuery = "SELECT tr_fasttag_balance FROM truck_mst WHERE truck_no = '$truck_no' LIMIT 1";
        $truckResult = mysqli_query($conn, $truckQuery);

        if ($truckResult && mysqli_num_rows($truckResult) > 0) {
            $truckRow = mysqli_fetch_assoc($truckResult);
            $response['fast_tag_opening'] = $truckRow['tr_fasttag_balance']; // Set fast tag balance as opening
        } else {
            // Debugging: Check if truck_mst query returns no data
            error_log("No record found in truck_mst table for truck: $truck_no");
            $response['fast_tag_opening'] = 0; // Default to 0 if no record is found
        }
    }
} else {
    // Debugging: Check if truck_no is not provided
    error_log("No truck_no provided in request.");
}

// Return response as JSON
echo json_encode($response);
die();
?>
