<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Log incoming request
error_log("Received request for fetch_cargo_details.php");
error_log("GET params: " . print_r($_GET, true));

// Include database connection
include 'layouts/dbconn.php';

// Set headers
header('Content-Type: application/json');
header('Cache-Control: no-cache, must-revalidate');
header('X-Debug-Request-Time: ' . time());

// Log database connection status
error_log("Database connection status: " . ($conn ? "Connected" : "Failed"));

// Check if booking number is provided
if (!isset($_GET['booking_number'])) {
    error_log("Error: No booking number provided");
    echo json_encode([
        'success' => false,
        'error' => 'Booking number is required',
        'debug' => 'No booking_number in $_GET'
    ]);
    exit;
}

// Sanitize input
$bookingNumber = mysqli_real_escape_string($conn, $_GET['booking_number']);
error_log("Searching for booking number: " . $bookingNumber);

// Prepare and execute query
$query = "SELECT total_amount FROM cargo_bookings WHERE booking_number = ?";
error_log("Query: " . $query);

try {
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }

    $stmt->bind_param("s", $bookingNumber);
    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }

    $result = $stmt->get_result();
    error_log("Query executed. Rows found: " . $result->num_rows);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        error_log("Data found: " . print_r($row, true));
        echo json_encode([
            'success' => true,
            'total_amount' => $row['total_amount'],
            'debug_time' => date('Y-m-d H:i:s'),
            'debug_rows' => $result->num_rows
        ]);
    } else {
        error_log("No data found for booking number: " . $bookingNumber);
        echo json_encode([
            'success' => false,
            'error' => 'No booking found with this number',
            'debug_booking' => $bookingNumber
        ]);
    }

} catch (Exception $e) {
    error_log("Exception occurred: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => 'Database error occurred',
        'debug_message' => $e->getMessage()
    ]);
}

if ($stmt) {
    $stmt->close();
}
$conn->close();