<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

// Handle form submission
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Generate tracking number
        $tracking_stmt = $conn->prepare("CALL GenerateTrackingNumber()");
        $tracking_stmt->execute();
        $tracking_result = $tracking_stmt->get_result();
        $tracking_number = $tracking_result->fetch_assoc()['tracking_number'];
        $tracking_stmt->close();
        
        // Calculate volumetric weight if dimensions provided
        $volumetric_weight = 0;
        if (!empty($_POST['dimensions_length']) && !empty($_POST['dimensions_width']) && !empty($_POST['dimensions_height'])) {
            $vol_stmt = $conn->prepare("CALL CalculateVolumetricWeight(?, ?, ?, @volumetric_weight)");
            $vol_stmt->bind_param("ddd", $_POST['dimensions_length'], $_POST['dimensions_width'], $_POST['dimensions_height']);
            $vol_stmt->execute();
            $vol_stmt->close();
            
            $vol_result = $conn->query("SELECT @volumetric_weight as volumetric_weight");
            $volumetric_weight = $vol_result->fetch_assoc()['volumetric_weight'];
        }
        
        // Calculate chargeable weight (higher of actual or volumetric)
        $chargeable_weight = max(floatval($_POST['actual_weight'] ?? 0), $volumetric_weight);
        
        // Calculate freight charges based on simplified pricing logic
        $freight_charges = 0;
        $fixed_amount = floatval($_POST['fixed_amount'] ?? 0);
        $rate_per_kg = floatval($_POST['rate_per_kg'] ?? 0);
        
        if ($fixed_amount > 0) {
            $freight_charges = $fixed_amount;
        } elseif ($rate_per_kg > 0) {
            $freight_charges = $chargeable_weight * $rate_per_kg;
        } else {
            throw new Exception("Please provide either a fixed amount or rate per kg for pricing.");
        }
        
        // Calculate tax
        $tax_rate = floatval($_POST['tax_rate'] ?? 0);
        $tax_amount = $freight_charges * ($tax_rate / 100);
        $total_charges = $freight_charges + $tax_amount;
        
        // Set other charges to 0 for simplicity
        $fuel_surcharge = 0;
        $insurance_charges = 0;
        $handling_charges = 0;
        $customs_charges = 0;
        $other_charges = 0;
        
        // Handle customer creation if sender_customer_id is not provided
        $sender_customer_id = !empty($_POST['sender_customer_id']) ? (int)$_POST['sender_customer_id'] : null;
        if ($sender_customer_id === null) {
            // Generate unique customer code
            $customer_code = 'CUST-' . date('Ymd') . '-' . substr(str_shuffle('0123456789'), 0, 4);
            
            // Determine customer type
            $customer_type = !empty($_POST['sender_company']) ? 'CORPORATE' : 'INDIVIDUAL';
            
            // Split sender_name into first_name and last_name if INDIVIDUAL
            $first_name = null;
            $last_name = null;
            if ($customer_type === 'INDIVIDUAL') {
                $name_parts = explode(' ', trim($_POST['sender_name'] ?? ''), 2);
                $first_name = $name_parts[0] ?? '';
                $last_name = isset($name_parts[1]) ? $name_parts[1] : '';
            }
            
            // Prepare customer data
            $company_name = $_POST['sender_company'] ?? null;
            $email = $_POST['sender_email'] ?? null;
            $phone = $_POST['sender_phone'] ?? '';
            $address_line1 = $_POST['sender_address'] ?? '';
            $address_line2 = null; // Not in form
            $city = $_POST['sender_city'] ?? '';
            $state = $_POST['sender_state'] ?? null;
            $postal_code = $_POST['sender_postal_code'] ?? null;
            $country = $_POST['sender_country'] ?? '';
            $is_credit_customer = 0;
            $credit_limit = 0.00;
            $payment_terms = 0;
            $customer_status = 'ACTIVE';
            
            // Insert into customers table
            $customer_sql = "INSERT INTO customers (
                customer_code, customer_type, company_name, first_name, last_name,
                email, phone, address_line1, address_line2, city, state, postal_code, country,
                is_credit_customer, credit_limit, payment_terms, status, created_by
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $customer_stmt = $conn->prepare($customer_sql);
            $customer_stmt->bind_param(
                "sssssssssssssidsii",
                $customer_code, $customer_type, $company_name, $first_name, $last_name,
                $email, $phone, $address_line1, $address_line2, $city, $state,
                $postal_code, $country, $is_credit_customer, $credit_limit,
                $payment_terms, $customer_status, $user_id
            );

            if (!$customer_stmt->execute()) {
                throw new Exception("Error creating customer: " . $conn->error);
            }
            
            $sender_customer_id = $conn->insert_id;
            $customer_stmt->close();
        }
        
        // Prepare shipment data - FIXED to match database columns exactly
        $reference_number = !empty($_POST['reference_number']) ? $_POST['reference_number'] : null;
        $customer_reference = !empty($_POST['customer_reference']) ? $_POST['customer_reference'] : null;
        $sender_name = $_POST['sender_name'] ?? '';
        $sender_company = !empty($_POST['sender_company']) ? $_POST['sender_company'] : null;
        $sender_email = !empty($_POST['sender_email']) ? $_POST['sender_email'] : null;
        $sender_phone = $_POST['sender_phone'] ?? '';
        $sender_address = $_POST['sender_address'] ?? '';
        $sender_city = $_POST['sender_city'] ?? '';
        $sender_state = !empty($_POST['sender_state']) ? $_POST['sender_state'] : null;
        $sender_postal_code = !empty($_POST['sender_postal_code']) ? $_POST['sender_postal_code'] : null;
        $sender_country = $_POST['sender_country'] ?? '';
        $receiver_name = $_POST['receiver_name'] ?? '';
        $receiver_company = !empty($_POST['receiver_company']) ? $_POST['receiver_company'] : null;
        $receiver_email = !empty($_POST['receiver_email']) ? $_POST['receiver_email'] : null;
        $receiver_phone = $_POST['receiver_phone'] ?? '';
        $receiver_address = $_POST['receiver_address'] ?? '';
        $receiver_city = $_POST['receiver_city'] ?? '';
        $receiver_state = !empty($_POST['receiver_state']) ? $_POST['receiver_state'] : null;
        $receiver_postal_code = !empty($_POST['receiver_postal_code']) ? $_POST['receiver_postal_code'] : null;
        $receiver_country = $_POST['receiver_country'] ?? '';
        $service_id = !empty($_POST['service_id']) ? (int)$_POST['service_id'] : null;
        $origin_location_id = !empty($_POST['origin_location_id']) ? (int)$_POST['origin_location_id'] : null;
        $destination_location_id = !empty($_POST['destination_location_id']) ? (int)$_POST['destination_location_id'] : null;
        $pickup_required = isset($_POST['pickup_required']) ? 1 : 0;
        $pickup_date = !empty($_POST['pickup_date']) ? $_POST['pickup_date'] : null;
        $pickup_time_from = !empty($_POST['pickup_time_from']) ? $_POST['pickup_time_from'] : null;
        $pickup_time_to = !empty($_POST['pickup_time_to']) ? $_POST['pickup_time_to'] : null;
        $pieces = !empty($_POST['pieces']) ? (int)$_POST['pieces'] : 1;
        $package_type = !empty($_POST['package_type']) ? $_POST['package_type'] : 'BOX';
        $actual_weight = !empty($_POST['actual_weight']) ? (float)$_POST['actual_weight'] : 0.0;
        $dimensions_length = !empty($_POST['dimensions_length']) ? (float)$_POST['dimensions_length'] : null;
        $dimensions_width = !empty($_POST['dimensions_width']) ? (float)$_POST['dimensions_width'] : null;
        $dimensions_height = !empty($_POST['dimensions_height']) ? (float)$_POST['dimensions_height'] : null;
        $content_description = $_POST['content_description'] ?? '';
        $declared_value = !empty($_POST['declared_value']) ? (float)$_POST['declared_value'] : 0.00;
        $currency = !empty($_POST['currency']) ? $_POST['currency'] : 'KES';
        $special_instructions = !empty($_POST['special_instructions']) ? $_POST['special_instructions'] : null;
        $status = 'DRAFT';
        $payment_status = 'PENDING';
        $customs_status = 'PENDING';
        
        // FIXED INSERT - Exactly 49 columns and 49 parameters
        $insert_sql = "INSERT INTO shipments (
            tracking_number, reference_number, customer_reference, sender_customer_id,
            sender_name, sender_company, sender_email, sender_phone, sender_address, 
            sender_city, sender_state, sender_postal_code, sender_country,
            receiver_name, receiver_company, receiver_email, receiver_phone, receiver_address,
            receiver_city, receiver_state, receiver_postal_code, receiver_country,
            service_id, origin_location_id, destination_location_id,
            pickup_required, pickup_date, pickup_time_from, pickup_time_to,
            pieces, package_type, actual_weight, volumetric_weight, chargeable_weight,
            dimensions_length, dimensions_width, dimensions_height,
            content_description, declared_value, currency,
            freight_charges, fuel_surcharge, insurance_charges, handling_charges, 
            customs_charges, other_charges, tax_amount, total_charges,
            status, payment_status, customs_status, special_instructions, created_by
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt = $conn->prepare($insert_sql);
        
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        // FIXED bind_param - Exactly 53 parameters to match 53 placeholders
        $stmt->bind_param(
            "sssissssssssssssssssssiisssisddddddsssdsdddddddsssssi",
            $tracking_number, $reference_number, $customer_reference, $sender_customer_id,
            $sender_name, $sender_company, $sender_email, $sender_phone, $sender_address,
            $sender_city, $sender_state, $sender_postal_code, $sender_country,
            $receiver_name, $receiver_company, $receiver_email, $receiver_phone, $receiver_address,
            $receiver_city, $receiver_state, $receiver_postal_code, $receiver_country,
            $service_id, $origin_location_id, $destination_location_id,
            $pickup_required, $pickup_date, $pickup_time_from, $pickup_time_to,
            $pieces, $package_type, $actual_weight, $volumetric_weight, $chargeable_weight,
            $dimensions_length, $dimensions_width, $dimensions_height,
            $content_description, $declared_value, $currency,
            $freight_charges, $fuel_surcharge, $insurance_charges, $handling_charges,
            $customs_charges, $other_charges, $tax_amount, $total_charges,
            $status, $payment_status, $customs_status, $special_instructions, $user_id
        );

        if ($stmt->execute()) {
            $shipment_id = $conn->insert_id;
            
            // Create initial tracking event
            $event_sql = "INSERT INTO tracking_events (shipment_id, event_type, event_status, event_description, location, created_by) 
                         VALUES (?, 'BOOKED', 'DRAFT', 'Shipment created and saved as draft', ?, ?)";
            $event_stmt = $conn->prepare($event_sql);
            $location = $sender_city . ', ' . $sender_country;
            $event_stmt->bind_param("isi", $shipment_id, $location, $user_id);
            $event_stmt->execute();
            $event_stmt->close();
            
            $success_message = "Shipment created successfully! Tracking Number: " . $tracking_number . 
                             " | Total Charges: " . $currency . " " . number_format($total_charges, 2);
        } else {
            $error_message = "Error creating shipment: " . $stmt->error;
        }
        
        $stmt->close();
        
    } catch (Exception $e) {
        $error_message = "Error: " . $e->getMessage();
    }
}

// Fetch service types
$service_types = $conn->query("SELECT * FROM service_types WHERE is_active = 1 ORDER BY service_name");

// Fetch locations
$locations = $conn->query("SELECT l.*, c.country_name FROM locations l 
                          JOIN countries c ON l.country_id = c.country_id 
                          WHERE l.is_active = 1 ORDER BY l.location_name");

// Fetch customers
$customers = $conn->query("SELECT customer_id, customer_code, customer_type, company_name, first_name, last_name 
                          FROM customers WHERE status = 'ACTIVE' ORDER BY company_name, first_name");

// Fetch countries
$countries = $conn->query("SELECT * FROM countries WHERE is_active = 1 ORDER BY country_name");

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Shipment - Freight Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .page-header {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .form-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .form-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            border-radius: 12px 12px 0 0;
        }
        
        .form-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .form-body {
            padding: 2rem;
        }
        
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #1e40af;
            box-shadow: 0 0 0 3px rgba(30, 64, 175, 0.1);
        }
        
        .btn-primary {
            background: #1e40af;
            border-color: #1e40af;
            padding: 0.75rem 2rem;
            font-weight: 600;
            border-radius: 8px;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
            border-color: #1d4ed8;
        }
        
        .btn-secondary {
            background: #64748b;
            border-color: #64748b;
            padding: 0.75rem 2rem;
            font-weight: 600;
            border-radius: 8px;
        }
        
        .alert {
            border-radius: 8px;
            border: none;
            font-weight: 500;
        }
        
        .section-divider {
            border-top: 2px solid #e2e8f0;
            margin: 2rem 0;
            padding-top: 2rem;
        }
        
        .charges-summary {
            background: #f0f9ff;
            border: 2px solid #bae6fd;
            border-radius: 8px;
            padding: 1.5rem;
            margin-top: 1rem;
        }
        
        .charges-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.5rem;
        }
        
        .charges-total {
            font-weight: 700;
            font-size: 1.125rem;
            border-top: 2px solid #0369a1;
            padding-top: 0.5rem;
            margin-top: 0.5rem;
        }
        
        .required {
            color: #dc2626;
        }
        
        .pricing-input-group {
            background: #fafafa;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .pricing-note {
            font-size: 0.875rem;
            color: #64748b;
            font-style: italic;
            margin-top: 0.5rem;
        }
        
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .form-body {
                padding: 1rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h2 class="mb-2">Create New Shipment</h2>
                                <p class="mb-0">Enter shipment details to generate booking and tracking number</p>
                            </div>
                            <div class="d-none d-md-block">
                                <div class="text-end">
                                    <div style="font-size: 0.9rem; opacity: 0.8;">Today's Date</div>
                                    <div style="font-size: 1.1rem; font-weight: 600;"><?php echo date('M j, Y'); ?></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="bx bx-check-circle me-2"></i><?php echo $success_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if ($error_message): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="bx bx-error-circle me-2"></i><?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Shipment Form -->
                    <form method="POST" id="shipmentForm">
                        <!-- Sender Information -->
                        <div class="form-card">
                            <div class="form-header">
                                <h3 class="form-title">Sender Information</h3>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Select Existing Customer (Optional)</label>
                                        <select class="form-select" name="sender_customer_id" id="senderCustomer">
                                            <option value="">-- Select Customer --</option>
                                            <?php while($customer = $customers->fetch_assoc()): ?>
                                            <option value="<?php echo $customer['customer_id']; ?>">
                                                <?php echo $customer['customer_type'] == 'CORPORATE' ? $customer['company_name'] : $customer['first_name'] . ' ' . $customer['last_name']; ?>
                                                (<?php echo $customer['customer_code']; ?>)
                                            </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Reference Number (Optional)</label>
                                        <input type="text" class="form-control" name="reference_number" placeholder="Internal reference">
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Sender Name <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="sender_name" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Company Name</label>
                                        <input type="text" class="form-control" name="sender_company">
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Email</label>
                                        <input type="email" class="form-control" name="sender_email">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Phone <span class="required">*</span></label>
                                        <input type="tel" class="form-control" name="sender_phone" required>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Address <span class="required">*</span></label>
                                    <textarea class="form-control" name="sender_address" rows="2" required></textarea>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">City <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="sender_city" required>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">State/Province</label>
                                        <input type="text" class="form-control" name="sender_state">
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Postal Code</label>
                                        <input type="text" class="form-control" name="sender_postal_code">
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Country <span class="required">*</span></label>
                                        <select class="form-select" name="sender_country" required>
                                            <option value="">-- Select Country --</option>
                                            <?php 
                                            $countries->data_seek(0);
                                            while($country = $countries->fetch_assoc()): 
                                            ?>
                                            <option value="<?php echo $country['country_name']; ?>"><?php echo $country['country_name']; ?></option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Receiver Information -->
                        <div class="form-card">
                            <div class="form-header">
                                <h3 class="form-title">Receiver Information</h3>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Customer Reference</label>
                                        <input type="text" class="form-control" name="customer_reference" placeholder="Customer's reference number">
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Receiver Name <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="receiver_name" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Company Name</label>
                                        <input type="text" class="form-control" name="receiver_company">
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Email</label>
                                        <input type="email" class="form-control" name="receiver_email">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Phone <span class="required">*</span></label>
                                        <input type="tel" class="form-control" name="receiver_phone" required>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Address <span class="required">*</span></label>
                                    <textarea class="form-control" name="receiver_address" rows="2" required></textarea>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">City <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="receiver_city" required>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">State/Province</label>
                                        <input type="text" class="form-control" name="receiver_state">
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Postal Code</label>
                                        <input type="text" class="form-control" name="receiver_postal_code">
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Country <span class="required">*</span></label>
                                        <select class="form-select" name="receiver_country" required>
                                            <option value="">-- Select Country --</option>
                                            <?php 
                                            $countries->data_seek(0);
                                            while($country = $countries->fetch_assoc()): 
                                            ?>
                                            <option value="<?php echo $country['country_name']; ?>"><?php echo $country['country_name']; ?></option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Service and Route -->
                        <div class="form-card">
                            <div class="form-header">
                                <h3 class="form-title">Service and Route</h3>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Service Type <span class="required">*</span></label>
                                        <select class="form-select" name="service_id" required>
                                            <option value="">-- Select Service --</option>
                                            <?php while($service = $service_types->fetch_assoc()): ?>
                                            <option value="<?php echo $service['service_id']; ?>">
                                                <?php echo $service['service_name']; ?> 
                                                (<?php echo $service['transit_days_min']; ?>-<?php echo $service['transit_days_max']; ?> days)
                                            </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Origin Location <span class="required">*</span></label>
                                        <select class="form-select" name="origin_location_id" required>
                                            <option value="">-- Select Origin --</option>
                                            <?php 
                                            $locations->data_seek(0);
                                            while($location = $locations->fetch_assoc()): 
                                            ?>
                                            <option value="<?php echo $location['location_id']; ?>">
                                                <?php echo $location['location_name']; ?> (<?php echo $location['country_name']; ?>)
                                            </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Destination Location <span class="required">*</span></label>
                                        <select class="form-select" name="destination_location_id" required>
                                            <option value="">-- Select Destination --</option>
                                            <?php 
                                            $locations->data_seek(0);
                                            while($location = $locations->fetch_assoc()): 
                                            ?>
                                            <option value="<?php echo $location['location_id']; ?>">
                                                <?php echo $location['location_name']; ?> (<?php echo $location['country_name']; ?>)
                                            </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <!-- Pickup Options -->
                                <div class="section-divider">
                                    <h5>Pickup Options</h5>
                                    <div class="row">
                                        <div class="col-md-3 mb-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="pickup_required" id="pickupRequired">
                                                <label class="form-check-label" for="pickupRequired">
                                                    Pickup Required
                                                </label>
                                            </div>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <label class="form-label">Pickup Date</label>
                                            <input type="date" class="form-control" name="pickup_date">
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <label class="form-label">Pickup Time From</label>
                                            <input type="time" class="form-control" name="pickup_time_from">
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <label class="form-label">Pickup Time To</label>
                                            <input type="time" class="form-control" name="pickup_time_to">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Package Details -->
                        <div class="form-card">
                            <div class="form-header">
                                <h3 class="form-title">Package Details</h3>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Number of Pieces <span class="required">*</span></label>
                                        <input type="number" class="form-control" name="pieces" min="1" value="1" required>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Package Type</label>
                                        <select class="form-select" name="package_type">
                                            <option value="BOX">Box</option>
                                            <option value="ENVELOPE">Envelope</option>
                                            <option value="PALLET">Pallet</option>
                                            <option value="TUBE">Tube</option>
                                            <option value="OTHER">Other</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Actual Weight (KG) <span class="required">*</span></label>
                                        <input type="number" class="form-control" name="actual_weight" step="0.01" min="0.01" required>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Declared Value</label>
                                        <input type="number" class="form-control" name="declared_value" step="0.01" min="0">
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Length (CM)</label>
                                        <input type="number" class="form-control" name="dimensions_length" step="0.1" min="0">
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Width (CM)</label>
                                        <input type="number" class="form-control" name="dimensions_width" step="0.1" min="0">
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Height (CM)</label>
                                        <input type="number" class="form-control" name="dimensions_height" step="0.1" min="0">
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Content Description <span class="required">*</span></label>
                                    <textarea class="form-control" name="content_description" rows="3" required 
                                              placeholder="Describe the contents of the shipment"></textarea>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Special Instructions</label>
                                    <textarea class="form-control" name="special_instructions" rows="2" 
                                              placeholder="Any special handling instructions"></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Pricing -->
                        <div class="form-card">
                            <div class="form-header">
                                <h3 class="form-title">Pricing</h3>
                            </div>
                            <div class="form-body">
                                <div class="row mb-3">
                                    <div class="col-md-4">
                                        <label class="form-label">Currency <span class="required">*</span></label>
                                        <select class="form-select" name="currency" id="currency" required>
                                            <option value="KES" selected>KES - Kenyan Shilling</option>
                                            <option value="USD">USD - US Dollar</option>
                                            <option value="EUR">EUR - Euro</option>
                                            <option value="GBP">GBP - British Pound</option>
                                            <option value="UGX">UGX - Ugandan Shilling</option>
                                            <option value="TZS">TZS - Tanzanian Shilling</option>
                                            <option value="RWF">RWF - Rwandan Franc</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Tax Rate %</label>
                                        <input type="number" class="form-control" name="tax_rate" id="taxRate" 
                                               step="0.1" min="0" max="100" value="16" placeholder="16">
                                    </div>
                                </div>
                                
                                <!-- Pricing Options -->
                                <div class="pricing-input-group">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Fixed Amount</label>
                                            <input type="number" class="form-control" name="fixed_amount" id="fixedAmount" 
                                                   step="0.01" min="0" placeholder="e.g. 5000.00">
                                            <div class="pricing-note">Use this for a flat rate regardless of weight</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Rate per KG</label>
                                            <input type="number" class="form-control" name="rate_per_kg" id="ratePerKg" 
                                                   step="0.01" min="0" placeholder="e.g. 150.00">
                                            <div class="pricing-note">Will be multiplied by chargeable weight</div>
                                        </div>
                                    </div>
                                    <div class="alert alert-info mb-0">
                                        <strong>Pricing Logic:</strong> If you enter a Fixed Amount, it will be used as the base charge. 
                                        If Fixed Amount is empty, the Rate per KG will be multiplied by the chargeable weight. 
                                        At least one pricing method must be provided.
                                    </div>
                                </div>
                                
                                <!-- Charges Summary -->
                                <div class="charges-summary" id="chargesSummary">
                                    <h5 style="margin-bottom: 1rem; color: #0369a1;">Total Charges</h5>
                                    <div class="charges-row">
                                        <span>Base Charges:</span>
                                        <span id="baseCharges">KSh 0.00</span>
                                    </div>
                                    <div class="charges-row">
                                        <span>Tax (<span id="taxRateDisplay">16</span>%):</span>
                                        <span id="taxDisplay">KSh 0.00</span>
                                    </div>
                                    <div class="charges-row charges-total">
                                        <span>TOTAL AMOUNT:</span>
                                        <span id="totalCharges">KSh 0.00</span>
                                    </div>
                                    <div style="margin-top: 1rem; font-size: 0.875rem; color: #64748b;">
                                        <strong>Chargeable Weight:</strong> <span id="weightDisplay">0.00</span> kg | 
                                        <strong>Currency:</strong> <span id="currencyDisplay">KES</span> |
                                        <strong>Pricing Method:</strong> <span id="pricingMethodDisplay">None Selected</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Form Actions -->
                        <div class="form-card">
                            <div class="form-body">
                                <div class="d-flex justify-content-between">
                                    <a href="shipments.php" class="btn btn-secondary">
                                        Cancel
                                    </a>
                                    <div>
                                        <button type="submit" class="btn btn-primary me-2">
                                            Create Shipment
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
document.addEventListener('DOMContentLoaded', function() {
    
    // Get form elements
    var fixedInput = document.getElementById('fixedAmount');
    var rateInput = document.getElementById('ratePerKg');
    var taxInput = document.getElementById('taxRate');
    var currencySelect = document.getElementById('currency');
    var weightInput = document.querySelector('input[name="actual_weight"]');
    
    // Get display elements
    var baseDisplay = document.getElementById('baseCharges');
    var taxDisplay = document.getElementById('taxDisplay');
    var totalDisplay = document.getElementById('totalCharges');
    var currencyDisplay = document.getElementById('currencyDisplay');
    var taxRateDisplay = document.getElementById('taxRateDisplay');
    var methodDisplay = document.getElementById('pricingMethodDisplay');
    var weightDisplay = document.getElementById('weightDisplay');
    
    function updateCalculation() {
        console.log('Calculating...');
        
        // Get values
        var fixed = parseFloat(fixedInput.value) || 0;
        var rate = parseFloat(rateInput.value) || 0;
        var weight = parseFloat(weightInput.value) || 0;
        var taxRate = parseFloat(taxInput.value) || 0;
        var currency = currencySelect.value;
        
        // Calculate base charge
        var baseCharge = 0;
        var method = 'None';
        
        if (fixed > 0) {
            baseCharge = fixed;
            method = 'Fixed Amount';
        } else if (rate > 0 && weight > 0) {
            baseCharge = rate * weight;
            method = 'Rate per KG';
        }
        
        // Calculate tax and total
        var taxAmount = baseCharge * (taxRate / 100);
        var total = baseCharge + taxAmount;
        
        // Get currency symbol
        var symbol = 'KSh';
        if (currency === 'USD') symbol = '$';
        else if (currency === 'EUR') symbol = '€';
        else if (currency === 'GBP') symbol = '£';
        
        // Update displays
        if (baseDisplay) baseDisplay.textContent = symbol + ' ' + baseCharge.toFixed(2);
        if (taxDisplay) taxDisplay.textContent = symbol + ' ' + taxAmount.toFixed(2);
        if (totalDisplay) totalDisplay.textContent = symbol + ' ' + total.toFixed(2);
        if (currencyDisplay) currencyDisplay.textContent = currency;
        if (taxRateDisplay) taxRateDisplay.textContent = taxRate.toFixed(1);
        if (methodDisplay) methodDisplay.textContent = method;
        if (weightDisplay) weightDisplay.textContent = weight.toFixed(2);
        
        console.log('Updated - Base: ' + baseCharge + ', Tax: ' + taxAmount + ', Total: ' + total);
    }
    
    // Add event listeners
    if (fixedInput) {
        fixedInput.addEventListener('input', updateCalculation);
        fixedInput.addEventListener('keyup', updateCalculation);
    }
    
    if (rateInput) {
        rateInput.addEventListener('input', updateCalculation);
        rateInput.addEventListener('keyup', updateCalculation);
    }
    
    if (taxInput) {
        taxInput.addEventListener('input', updateCalculation);
        taxInput.addEventListener('keyup', updateCalculation);
    }
    
    if (currencySelect) {
        currencySelect.addEventListener('change', updateCalculation);
    }
    
    if (weightInput) {
        weightInput.addEventListener('input', updateCalculation);
        weightInput.addEventListener('keyup', updateCalculation);
    }
    
    // Initial calculation
    setTimeout(function() {
        updateCalculation();
    }, 500);
    
    console.log('Pricing calculator initialized');
});
</script>
    <script src="assets/js/app.js"></script>
</body>
</html>