<?php
include 'layouts/dbconn.php';
// Enable error logging
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    // Get POST data
    $booking_number = $_POST['cargo_tracking_code'];
    $payment_amount = $_POST['payment_amount'];

    // Begin transaction
    $conn->begin_transaction();

    // First, get the booking_id for the given booking_number
    $get_booking_id = "SELECT booking_id FROM cargo_bookings WHERE booking_number = ?";
    $stmt_id = $conn->prepare($get_booking_id);
    if (!$stmt_id) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    $stmt_id->bind_param("s", $booking_number);
    $stmt_id->execute();
    $result = $stmt_id->get_result();
    $booking = $result->fetch_assoc();
    $booking_id = $booking['booking_id'];
    $stmt_id->close();

    // Update the payment status and paid amount
    $query = "UPDATE cargo_bookings 
              SET payment_status = 'Paid',
                  paid_amount = ?,
                  payment_date = CURRENT_TIMESTAMP 
              WHERE booking_number = ?";
              
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    $stmt->bind_param("ds", $payment_amount, $booking_number);
    
    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }

    // Check if the update was successful
    if ($stmt->affected_rows > 0) {
        // Commit transaction
        $conn->commit();
        
        // Set success session message
        session_start();
        $_SESSION['success_message'] = "Payment of $payment_amount has been successfully recorded for booking $booking_number";
        
        // Redirect to payment view page with the booking_id
        header("Location: cargo_payment_view.php?booking_id=" . $booking_id);
        exit();
    } else {
        throw new Exception("No records were updated");
    }
} catch (Exception $e) {
    // Rollback transaction on error
    if ($conn && $conn->ping()) {
        $conn->rollback();
    }
    
    // Set error session message
    session_start();
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
    
    // Redirect back to the payment page
    header("Location: add_cargo_payment.php");
    exit();
}

// Close connections
if (isset($stmt)) {
    $stmt->close();
}
if (isset($conn)) {
    $conn->close();
}
?>