<?php
include 'layouts/session.php';
include 'layouts/dbconn.php';
?>
<!DOCTYPE html>
<html>
<head>
    <title>Cargo Booking</title>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>
<?php

// Function to sanitize input data
function sanitize_input($data) {
    return htmlspecialchars(stripslashes(trim($data)));
}

// Function to validate phone number
function validate_phone_number($phone) {
    return preg_match('/^(\+?[0-9]{1,3})?[0-9]{10}$/', $phone);
}

// Function to validate email
function validate_email($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

// Function to show SweetAlert
function show_sweet_alert($type, $title, $message, $redirect = '') {
    echo "<script>
        Swal.fire({
            icon: '" . $type . "',
            title: '" . addslashes($title) . "',
            html: '" . addslashes($message) . "',
            confirmButtonText: 'Okay'
        }).then((result) => {
            if (result.isConfirmed && '" . $redirect . "') {
                window.location.href = '" . $redirect . "';
            }
        });
    </script>";
}

// Debug POST data
error_log("POST Data: " . print_r($_POST, true));

// Initialize variables
$sender_customer_id = isset($_POST['sender_customer_id']) ? intval($_POST['sender_customer_id']) : null;
$sender_address_id = isset($_POST['sender_address_id']) ? intval($_POST['sender_address_id']) : null;
$receiver_customer_id = isset($_POST['receiver_customer_id']) ? intval($_POST['receiver_customer_id']) : null;
$receiver_address_id = isset($_POST['receiver_address_id']) ? intval($_POST['receiver_address_id']) : null;
$receiver_name = isset($_POST['receiver_name']) ? trim($_POST['receiver_name']) : '';  // Changed sanitization
$receiver_phone = isset($_POST['receiver_phone']) ? trim($_POST['receiver_phone']) : '';
$receiver_email = isset($_POST['receiver_email']) ? trim($_POST['receiver_email']) : '';
$cargo_type = isset($_POST['cargo_type']) ? trim($_POST['cargo_type']) : '';
$weight = isset($_POST['weight']) ? floatval($_POST['weight']) : 0;
$rate = isset($_POST['rate']) ? floatval($_POST['rate']) : '';
$dimensions = isset($_POST['dimensions']) ? trim($_POST['dimensions']) : '';
$special_instructions = isset($_POST['special_instructions']) ? trim($_POST['special_instructions']) : '';
$pickup_date = isset($_POST['pickup_date']) ? trim($_POST['pickup_date']) : '';
$estimated_delivery_date = isset($_POST['estimated_delivery_date']) ? trim($_POST['estimated_delivery_date']) : '';
$currency = isset($_POST['currency']) ? trim($_POST['currency']) : '';
$total_amount = isset($_POST['total_amount']) ? floatval($_POST['total_amount']) : 0;
$payment_status = isset($_POST['payment_status']) ? trim($_POST['payment_status']) : '';

// Debug received values
error_log("Receiver Name after initialization: " . $receiver_name);

// Your validation code remains the same
$errors = [];

if (empty($sender_customer_id)) $errors[] = 'Sender customer ID is required.';
if (empty($sender_address_id)) $errors[] = 'Sender address ID is required.';
if (empty($receiver_address_id)) $errors[] = 'Receiver address ID is required.';

// Receiver information validation
if (empty($receiver_customer_id)) {
    if (empty($receiver_name)) $errors[] = 'Receiver name is required.';
    if (empty($receiver_phone)) {
        $errors[] = 'Receiver phone is required.';
    } elseif (!validate_phone_number($receiver_phone)) {
        $errors[] = 'Invalid receiver phone number format.';
    }
    if (empty($receiver_email)) {
        $errors[] = 'Receiver email is required.';
    } elseif (!validate_email($receiver_email)) {
        $errors[] = 'Invalid receiver email format.';
    }
}

if (empty($cargo_type)) $errors[] = 'Cargo type is required.';
if (empty($weight) || $weight <= 0) $errors[] = 'Valid weight is required.';
if (empty($pickup_date)) $errors[] = 'Pickup date is required.';
if (empty($estimated_delivery_date)) $errors[] = 'Estimated delivery date is required.';
if (empty($currency)) $errors[] = 'Currency is required.';
if (empty($total_amount) || $total_amount <= 0) $errors[] = 'Valid total amount is required.';
if (empty($payment_status)) $errors[] = 'Payment Status is required.';

// If there are validation errors, show them and stop execution
if (!empty($errors)) {
    show_sweet_alert('error', 'Validation Error', implode('<br>', $errors));
    echo "</body></html>";
    exit;
}

try {
    // Start transaction
    $conn->begin_transaction();

    // Generate booking number
    $query = "SELECT booking_number FROM cargo_bookings ORDER BY booking_id DESC LIMIT 1";
    $result = $conn->query($query);
    
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        preg_match('/AWT(\d+)/', $row['booking_number'], $matches);
        $lastNumber = intval($matches[1]);
        $newNumber = $lastNumber + 1;
    } else {
        $newNumber = 1;
    }
    
    $booking_number = 'AWT' . str_pad($newNumber, 6, '0', STR_PAD_LEFT);

    // Debug values before insertion
    error_log("Values before insertion:");
    error_log("Booking Number: " . $booking_number);
    error_log("Receiver Name: " . $receiver_name);
    error_log("Receiver Phone: " . $receiver_phone);
    error_log("Receiver Email: " . $receiver_email);

    // Prepare the query
    $query = "INSERT INTO cargo_bookings (
        booking_number, 
        sender_customer_id, 
        sender_address_id, 
        receiver_customer_id, 
        receiver_address_id, 
        receiver_name, 
        receiver_phone, 
        receiver_email, 
        cargo_type, 
        weight,
        rate,
        dimensions, 
        special_instructions, 
        pickup_date, 
        estimated_delivery_date, 
        total_amount, 
        currency,
        payment_status
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }

    // Bind parameters - notice the corrected types string
    if (!$stmt->bind_param(
        'siiiissssssssssiss',  // Changed parameter types to match data types 'siiiiissssssssss'
        $booking_number,      // s - string
        $sender_customer_id,  // i - integer
        $sender_address_id,   // i - integer
        $receiver_customer_id,// i - integer
        $receiver_address_id, // i - integer
        $receiver_name,       // s - string
        $receiver_phone,      // s - string
        $receiver_email,      // s - string
        $cargo_type,         // s - string
        $weight,            // s - string (for decimal)
        $rate,              // s - string (for decimal)
        $dimensions,         // s - string
        $special_instructions,// s - string
        $pickup_date,        // s - string
        $estimated_delivery_date, // s - string
        $total_amount,       // i - integer
        $currency,           // s - string
        $payment_status      // s - string
    )) {
        throw new Exception("Binding parameters failed: " . $stmt->error);
    }

    // Execute the statement
    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }

    // Commit transaction
    $conn->commit();

    // Show success message and redirect
    show_sweet_alert(
        'success',
        'Success',
        'Cargo booking saved successfully!<br>Booking Number: ' . $booking_number,
        'all_cargo.php'
    );

} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    // Log the error
    error_log("Error in cargo booking: " . $e->getMessage());
    
    // Show error message
    show_sweet_alert(
        'error',
        'Error',
        'Error saving cargo booking: ' . htmlspecialchars($e->getMessage())
    );
} finally {
    // Clean up
    if (isset($stmt)) {
        $stmt->close();
    }
    $conn->close();
}
?>
</body>
</html>