<?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();
}

$user_id = $_SESSION['user_id'];

// Fetch user details
$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'];
}

// Get service types
$service_types = $conn->query("SELECT service_id, service_name, service_category, transit_days_min, transit_days_max 
                               FROM service_types WHERE is_active = 1 ORDER BY service_name");

// Get zones and locations
$zones = $conn->query("SELECT zone_id, zone_name, zone_code, description FROM zones WHERE is_active = 1 ORDER BY zone_name");
$locations = $conn->query("SELECT l.location_id, l.location_name, l.city, c.country_name, l.zone_id, z.zone_name
                          FROM locations l
                          INNER JOIN countries c ON l.country_id = c.country_id
                          INNER JOIN zones z ON l.zone_id = z.zone_id
                          WHERE l.is_active = 1 
                          ORDER BY z.zone_name, l.location_name");

// Get charge types for additional charges
$charge_types = $conn->query("SELECT charge_id, charge_code, charge_name, charge_type, default_amount, is_taxable 
                              FROM charge_types WHERE is_active = 1 ORDER BY charge_name");

// Get volumetric factor from settings
$volumetric_factor = 5000; // Default
$volumetric_result = $conn->query("SELECT setting_value FROM settings WHERE setting_key = 'volumetric_factor'");
if ($volumetric_result && $volumetric_result->num_rows > 0) {
    $volumetric_factor = intval($volumetric_result->fetch_assoc()['setting_value']);
}

// Handle AJAX requests for rate calculation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'calculate_rate') {
    header('Content-Type: application/json');
    
    $service_id = intval($_POST['service_id']);
    $origin_zone_id = intval($_POST['origin_zone_id']);
    $destination_zone_id = intval($_POST['destination_zone_id']);
    $weight = floatval($_POST['weight']);
    $length = floatval($_POST['length'] ?? 0);
    $width = floatval($_POST['width'] ?? 0);
    $height = floatval($_POST['height'] ?? 0);
    $declared_value = floatval($_POST['declared_value'] ?? 0);
    $customer_id = !empty($_POST['customer_id']) ? intval($_POST['customer_id']) : null;
    
    // Calculate volumetric weight
    $volumetric_weight = 0;
    if ($length > 0 && $width > 0 && $height > 0) {
        $volumetric_weight = ($length * $width * $height) / $volumetric_factor;
    }
    
    // Use higher of actual or volumetric weight
    $chargeable_weight = max($weight, $volumetric_weight);
    
    // Get applicable rate
    $rate_sql = "SELECT r.rate_per_kg, r.minimum_charge, r.fuel_surcharge_percent
                 FROM rate_cards r
                 WHERE r.service_id = ? 
                   AND r.origin_zone_id = ?
                   AND r.destination_zone_id = ?
                   AND r.weight_from <= ?
                   AND r.weight_to >= ?
                   AND r.is_active = 1
                   AND (r.customer_id = ? OR r.customer_id IS NULL)
                   AND r.effective_date <= CURDATE()
                   AND (r.expiry_date IS NULL OR r.expiry_date >= CURDATE())
                 ORDER BY r.customer_id DESC, r.effective_date DESC
                 LIMIT 1";
    
    $stmt_rate = $conn->prepare($rate_sql);
    $stmt_rate->bind_param("iiiddi", $service_id, $origin_zone_id, $destination_zone_id, 
                           $chargeable_weight, $chargeable_weight, $customer_id);
    $stmt_rate->execute();
    $rate_result = $stmt_rate->get_result();
    
    if ($rate_result->num_rows > 0) {
        $rate = $rate_result->fetch_assoc();
        
        // Calculate charges
        $freight_charges = max($chargeable_weight * $rate['rate_per_kg'], $rate['minimum_charge']);
        $fuel_surcharge = $freight_charges * ($rate['fuel_surcharge_percent'] / 100);
        $insurance_charges = $declared_value > 0 ? ($declared_value * 0.005) : 0; // 0.5% of declared value
        $handling_charges = $chargeable_weight >= 50 ? 500 : 0; // Flat handling fee for heavy items
        
        $subtotal = $freight_charges + $fuel_surcharge + $insurance_charges + $handling_charges;
        $tax_amount = $subtotal * 0.16; // 16% VAT
        $total_charges = $subtotal + $tax_amount;
        
        echo json_encode([
            'success' => true,
            'rate_found' => true,
            'calculation' => [
                'actual_weight' => $weight,
                'volumetric_weight' => $volumetric_weight,
                'chargeable_weight' => $chargeable_weight,
                'rate_per_kg' => $rate['rate_per_kg'],
                'minimum_charge' => $rate['minimum_charge'],
                'freight_charges' => $freight_charges,
                'fuel_surcharge_percent' => $rate['fuel_surcharge_percent'],
                'fuel_surcharge' => $fuel_surcharge,
                'insurance_charges' => $insurance_charges,
                'handling_charges' => $handling_charges,
                'subtotal' => $subtotal,
                'tax_amount' => $tax_amount,
                'total_charges' => $total_charges
            ]
        ]);
    } else {
        echo json_encode([
            'success' => true,
            'rate_found' => false,
            'message' => 'No rate found for the selected route and weight range.'
        ]);
    }
    exit();
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Rate Calculator - Freight Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .header-title h1 {
            font-size: 2rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .calculator-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 2rem;
            margin-bottom: 2rem;
        }
        
        .calculator-form {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .form-section {
            margin-bottom: 2rem;
        }
        
        .section-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-label {
            font-size: 0.875rem;
            font-weight: 500;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control {
            padding: 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 0.875rem;
            background: white;
            transition: all 0.2s;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #059669;
            box-shadow: 0 0 0 3px rgba(5, 150, 105, 0.1);
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            justify-content: center;
        }
        
        .btn-primary {
            background: #059669;
            color: white;
        }
        
        .btn-primary:hover {
            background: #047857;
        }
        
        .btn-secondary {
            background: #64748b;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #475569;
        }
        
        .results-section {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .calculation-details {
            display: none;
        }
        
        .calculation-details.show {
            display: block;
        }
        
        .rate-summary {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .rate-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.5rem 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .rate-item:last-child {
            border-bottom: none;
        }
        
        .rate-label {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .rate-value {
            font-weight: 600;
            color: #1e293b;
        }
        
        .total-amount {
            background: #059669;
            color: white;
            padding: 1rem;
            border-radius: 8px;
            text-align: center;
            font-size: 1.25rem;
            font-weight: 700;
            margin-top: 1rem;
        }
        
        .weight-comparison {
            background: #fef3c7;
            border: 1px solid #fbbf24;
            border-radius: 8px;
            padding: 1rem;
            margin: 1rem 0;
        }
        
        .weight-comparison h4 {
            color: #92400e;
            margin-bottom: 0.5rem;
        }
        
        .weight-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.25rem;
        }
        
        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
        
        .alert-info {
            background: #dbeafe;
            border: 1px solid #60a5fa;
            color: #1e40af;
        }
        
        .alert-warning {
            background: #fef3c7;
            border: 1px solid #fbbf24;
            color: #92400e;
        }
        
        .alert-danger {
            background: #fee2e2;
            border: 1px solid #f87171;
            color: #991b1b;
        }
        
        .service-info {
            background: #e0f2fe;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .service-info h4 {
            color: #0369a1;
            margin-bottom: 0.5rem;
        }
        
        .service-details {
            display: flex;
            justify-content: space-between;
            font-size: 0.875rem;
            color: #0369a1;
        }
        
        .quick-quotes {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-top: 2rem;
        }
        
        .quotes-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1rem;
        }
        
        .quote-card {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
        }
        
        .quote-service {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .quote-amount {
            font-size: 1.25rem;
            font-weight: 700;
            color: #059669;
            margin-bottom: 0.25rem;
        }
        
        .quote-transit {
            font-size: 0.75rem;
            color: #64748b;
        }
        
        .loading {
            text-align: center;
            padding: 2rem;
            color: #64748b;
        }
        
        .spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #059669;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .dimension-inputs {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 0.5rem;
        }
        
        .input-group {
            position: relative;
        }
        
        .input-addon {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            color: #64748b;
            font-size: 0.75rem;
        }
        
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .calculator-container {
                grid-template-columns: 1fr;
            }
            
            .header-content {
                flex-direction: column;
                text-align: center;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
            }
            
            .dimension-inputs {
                grid-template-columns: 1fr;
            }
            
            .quotes-grid {
                grid-template-columns: 1fr;
            }
        }
        
        .info-tooltip {
            position: relative;
            display: inline-block;
            cursor: help;
            margin-left: 4px;
        }
        
        .info-tooltip .tooltiptext {
            visibility: hidden;
            width: 200px;
            background-color: #333;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 5px;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            margin-left: -100px;
            opacity: 0;
            transition: opacity 0.3s;
            font-size: 0.75rem;
        }
        
        .info-tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }
    </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="header-content">
                            <div class="header-title">
                                <h1>Rate Calculator</h1>
                                <p>Calculate shipping rates and get instant quotes for your freight</p>
                            </div>
                        </div>
                    </div>

                    <!-- Calculator Container -->
                    <div class="calculator-container">
                        <!-- Rate Calculation Form -->
                        <div class="calculator-form">
                            <form id="rateCalculatorForm">
                                <!-- Service Selection -->
                                <div class="form-section">
                                    <h3 class="section-title">Service & Route</h3>
                                    
                                    <div class="form-grid">
                                        <div class="form-group">
                                            <label class="form-label">Service Type *</label>
                                            <select id="service_id" name="service_id" class="form-control" required>
                                                <option value="">Select Service</option>
                                                <?php while ($service = $service_types->fetch_assoc()): ?>
                                                <option value="<?php echo $service['service_id']; ?>" 
                                                        data-category="<?php echo $service['service_category']; ?>"
                                                        data-transit-min="<?php echo $service['transit_days_min']; ?>"
                                                        data-transit-max="<?php echo $service['transit_days_max']; ?>">
                                                    <?php echo htmlspecialchars($service['service_name']); ?> 
                                                    (<?php echo $service['service_category']; ?>)
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label class="form-label">Customer (Optional)</label>
                                            <select id="customer_id" name="customer_id" class="form-control">
                                                <option value="">Walk-in Customer</option>
                                                <!-- Customers will be loaded via JavaScript -->
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="form-grid">
                                        <div class="form-group">
                                            <label class="form-label">Origin Location *</label>
                                            <select id="origin_location" name="origin_location" class="form-control" required>
                                                <option value="">Select Origin</option>
                                                <?php 
                                                $locations->data_seek(0); // Reset result pointer
                                                while ($location = $locations->fetch_assoc()): 
                                                ?>
                                                <option value="<?php echo $location['location_id']; ?>" 
                                                        data-zone="<?php echo $location['zone_id']; ?>"
                                                        data-zone-name="<?php echo $location['zone_name']; ?>">
                                                    <?php echo htmlspecialchars($location['location_name'] . ' - ' . $location['city'] . ', ' . $location['country_name']); ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label class="form-label">Destination Location *</label>
                                            <select id="destination_location" name="destination_location" class="form-control" required>
                                                <option value="">Select Destination</option>
                                                <?php 
                                                $locations->data_seek(0); // Reset result pointer
                                                while ($location = $locations->fetch_assoc()): 
                                                ?>
                                                <option value="<?php echo $location['location_id']; ?>" 
                                                        data-zone="<?php echo $location['zone_id']; ?>"
                                                        data-zone-name="<?php echo $location['zone_name']; ?>">
                                                    <?php echo htmlspecialchars($location['location_name'] . ' - ' . $location['city'] . ', ' . $location['country_name']); ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Package Details -->
                                <div class="form-section">
                                    <h3 class="section-title">Package Information</h3>
                                    
                                    <div class="form-grid">
                                        <div class="form-group">
                                            <label class="form-label">
                                                Actual Weight (KG) *
                                                <span class="info-tooltip">ℹ
                                                    <span class="tooltiptext">Physical weight of the package in kilograms</span>
                                                </span>
                                            </label>
                                            <div class="input-group">
                                                <input type="number" id="weight" name="weight" class="form-control" 
                                                       step="0.1" min="0.1" required>
                                                <span class="input-addon">KG</span>
                                            </div>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label class="form-label">Declared Value (Optional)</label>
                                            <div class="input-group">
                                                <input type="number" id="declared_value" name="declared_value" class="form-control" 
                                                       step="0.01" min="0">
                                                <span class="input-addon">KSh</span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label class="form-label">
                                            Dimensions (CM) - For Volumetric Weight Calculation
                                            <span class="info-tooltip">ℹ
                                                <span class="tooltiptext">Length × Width × Height. Used to calculate volumetric weight for large but light packages</span>
                                            </span>
                                        </label>
                                        <div class="dimension-inputs">
                                            <div class="input-group">
                                                <input type="number" id="length" name="length" class="form-control" 
                                                       placeholder="Length" step="0.1" min="0">
                                                <span class="input-addon">CM</span>
                                            </div>
                                            <div class="input-group">
                                                <input type="number" id="width" name="width" class="form-control" 
                                                       placeholder="Width" step="0.1" min="0">
                                                <span class="input-addon">CM</span>
                                            </div>
                                            <div class="input-group">
                                                <input type="number" id="height" name="height" class="form-control" 
                                                       placeholder="Height" step="0.1" min="0">
                                                <span class="input-addon">CM</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Calculate Button -->
                                <div style="display: flex; gap: 1rem; justify-content: center;">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="bx bx-calculator"></i> Calculate Rate
                                    </button>
                                    <button type="button" id="clearForm" class="btn btn-secondary">
                                        <i class="bx bx-refresh"></i> Clear
                                    </button>
                                </div>
                            </form>
                        </div>
                        
                        <!-- Results Section -->
                        <div class="results-section">
                            <h3 class="section-title">Rate Calculation Results</h3>
                            
                            <div id="calculationResults">
                                <div class="alert alert-info">
                                    <i class="bx bx-info-circle"></i>
                                    Fill out the form on the left and click "Calculate Rate" to see pricing details.
                                </div>
                            </div>
                            
                            <div id="calculationDetails" class="calculation-details">
                                <!-- Dynamic content will be loaded here -->
                            </div>
                        </div>
                    </div>
                    
                    <!-- Quick Quotes Section -->
                    <div class="quick-quotes">
                        <h3 class="section-title">Popular Routes & Services</h3>
                        <p style="color: #64748b; margin-bottom: 1.5rem;">
                            Quick reference rates for common shipping routes. Actual rates may vary based on specific requirements.
                        </p>
                        
                        <div class="quotes-grid">
                            <div class="quote-card">
                                <div class="quote-service">Air Freight Express</div>
                                <div class="quote-amount">KSh 250/KG</div>
                                <div class="quote-transit">Nairobi → Kampala (1-2 days)</div>
                            </div>
                            
                            <div class="quote-card">
                                <div class="quote-service">Road Freight Standard</div>
                                <div class="quote-amount">KSh 85/KG</div>
                                <div class="quote-transit">Nairobi → Mombasa (2-3 days)</div>
                            </div>
                            
                            <div class="quote-card">
                                <div class="quote-service">Sea Freight LCL</div>
                                <div class="quote-amount">KSh 45/KG</div>
                                <div class="quote-transit">Mombasa → Dubai (14-21 days)</div>
                            </div>
                            
                            <div class="quote-card">
                                <div class="quote-service">Courier Service</div>
                                <div class="quote-amount">KSh 350/KG</div>
                                <div class="quote-transit">Same City (Same day)</div>
                            </div>
                        </div>
                        
                        <div class="alert alert-info" style="margin-top: 1.5rem;">
                            <strong>Note:</strong> These are reference rates only. Actual rates depend on specific weight ranges, 
                            package dimensions, declared value, and current fuel surcharge rates. 
                            Use the calculator above for accurate quotes.
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('rateCalculatorForm');
            const resultsDiv = document.getElementById('calculationResults');
            const detailsDiv = document.getElementById('calculationDetails');
            const clearBtn = document.getElementById('clearForm');
            
            // Volumetric factor from PHP
            const VOLUMETRIC_FACTOR = <?php echo $volumetric_factor; ?>;
            
            // Form submission
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                calculateRate();
            });
            
            // Clear form
            clearBtn.addEventListener('click', function() {
                form.reset();
                resultsDiv.innerHTML = `
                    <div class="alert alert-info">
                        <i class="bx bx-info-circle"></i>
                        Fill out the form and click "Calculate Rate" to see pricing details.
                    </div>
                `;
                detailsDiv.classList.remove('show');
            });
            
            // Real-time volumetric weight calculation
            const dimensionInputs = ['length', 'width', 'height'];
            dimensionInputs.forEach(inputId => {
                document.getElementById(inputId).addEventListener('input', updateVolumetricWeight);
            });
            
            function updateVolumetricWeight() {
                const length = parseFloat(document.getElementById('length').value) || 0;
                const width = parseFloat(document.getElementById('width').value) || 0;
                const height = parseFloat(document.getElementById('height').value) || 0;
                
                if (length > 0 && width > 0 && height > 0) {
                    const volumetricWeight = (length * width * height) / VOLUMETRIC_FACTOR;
                    
                    // Show volumetric weight info
                    const existingInfo = document.getElementById('volumetric-info');
                    if (existingInfo) {
                        existingInfo.remove();
                    }
                    
                    const dimensionsContainer = document.querySelector('.dimension-inputs').parentNode;
                    const info = document.createElement('div');
                    info.id = 'volumetric-info';
                    info.className = 'alert alert-info';
                    info.style.marginTop = '0.5rem';
                    info.innerHTML = `
                        <strong>Volumetric Weight:</strong> ${volumetricWeight.toFixed(2)} KG 
                        <br><small>Formula: (${length} × ${width} × ${height}) ÷ ${VOLUMETRIC_FACTOR}</small>
                    `;
                    dimensionsContainer.appendChild(info);
                }
            }
            
            async function calculateRate() {
                // Show loading
                resultsDiv.innerHTML = `
                    <div class="loading">
                        <div class="spinner"></div>
                        <p>Calculating rates...</p>
                    </div>
                `;
                
                // Get form data
                const formData = new FormData(form);
                formData.append('action', 'calculate_rate');
                
                // Get zone IDs from selected locations
                const originSelect = document.getElementById('origin_location');
                const destinationSelect = document.getElementById('destination_location');
                
                const originOption = originSelect.options[originSelect.selectedIndex];
                const destinationOption = destinationSelect.options[destinationSelect.selectedIndex];
                
                if (!originOption || !destinationOption) {
                    resultsDiv.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="bx bx-error"></i>
                            Please select both origin and destination locations.
                        </div>
                    `;
                    return;
                }
                
                formData.append('origin_zone_id', originOption.dataset.zone);
                formData.append('destination_zone_id', destinationOption.dataset.zone);
                
                try {
                    const response = await fetch('rate_calculator.php', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const data = await response.json();
                    
                    if (data.success) {
                        if (data.rate_found) {
                            displayRateResults(data.calculation);
                        } else {
                            resultsDiv.innerHTML = `
                                <div class="alert alert-warning">
                                    <i class="bx bx-error-circle"></i>
                                    <strong>No Rate Found</strong><br>
                                    ${data.message}<br><br>
                                    <small>Please contact our sales team for a custom quote or check if the selected route and weight range are covered by our services.</small>
                                </div>
                            `;
                        }
                    } else {
                        throw new Error('Calculation failed');
                    }
                } catch (error) {
                    console.error('Rate calculation error:', error);
                    resultsDiv.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="bx bx-error"></i>
                            <strong>Calculation Error</strong><br>
                            Unable to calculate rates at this time. Please try again or contact support.
                        </div>
                    `;
                }
            }
            
            function displayRateResults(calc) {
                // Get service info
                const serviceSelect = document.getElementById('service_id');
                const serviceOption = serviceSelect.options[serviceSelect.selectedIndex];
                
                const originSelect = document.getElementById('origin_location');
                const destinationSelect = document.getElementById('destination_location');
                
                const originText = originSelect.options[originSelect.selectedIndex].text;
                const destinationText = destinationSelect.options[destinationSelect.selectedIndex].text;
                
                let transitTime = '';
                if (serviceOption.dataset.transitMin && serviceOption.dataset.transitMax) {
                    const minDays = serviceOption.dataset.transitMin;
                    const maxDays = serviceOption.dataset.transitMax;
                    if (minDays === maxDays) {
                        transitTime = `${minDays} day${minDays > 1 ? 's' : ''}`;
                    } else {
                        transitTime = `${minDays}-${maxDays} days`;
                    }
                }
                
                // Weight comparison
                let weightWarning = '';
                if (calc.volumetric_weight > calc.actual_weight) {
                    weightWarning = `
                        <div class="weight-comparison">
                            <h4><i class="bx bx-info-circle"></i> Volumetric Weight Applied</h4>
                            <div class="weight-item">
                                <span>Actual Weight:</span>
                                <span>${calc.actual_weight} KG</span>
                            </div>
                            <div class="weight-item">
                                <span>Volumetric Weight:</span>
                                <span>${calc.volumetric_weight.toFixed(2)} KG</span>
                            </div>
                            <div class="weight-item">
                                <strong>Chargeable Weight:</strong>
                                <strong>${calc.chargeable_weight.toFixed(2)} KG</strong>
                            </div>
                            <small>Volumetric weight is used because the package is large relative to its actual weight.</small>
                        </div>
                    `;
                }
                
                resultsDiv.innerHTML = `
                    <div class="service-info">
                        <h4>${serviceOption.text}</h4>
                        <div class="service-details">
                            <span><strong>Route:</strong> ${originText.split(' - ')[0]} → ${destinationText.split(' - ')[0]}</span>
                            ${transitTime ? `<span><strong>Transit Time:</strong> ${transitTime}</span>` : ''}
                        </div>
                    </div>
                    
                    ${weightWarning}
                    
                    <div class="rate-summary">
                        <div class="rate-item">
                            <span class="rate-label">Freight Charges (${calc.chargeable_weight.toFixed(2)} KG × KSh ${calc.rate_per_kg}/KG)</span>
                            <span class="rate-value">KSh ${calc.freight_charges.toLocaleString(undefined, {minimumFractionDigits: 2})}</span>
                        </div>
                        
                        ${calc.fuel_surcharge > 0 ? `
                        <div class="rate-item">
                            <span class="rate-label">Fuel Surcharge (${calc.fuel_surcharge_percent}%)</span>
                            <span class="rate-value">KSh ${calc.fuel_surcharge.toLocaleString(undefined, {minimumFractionDigits: 2})}</span>
                        </div>` : ''}
                        
                        ${calc.insurance_charges > 0 ? `
                        <div class="rate-item">
                            <span class="rate-label">Insurance (0.5% of declared value)</span>
                            <span class="rate-value">KSh ${calc.insurance_charges.toLocaleString(undefined, {minimumFractionDigits: 2})}</span>
                        </div>` : ''}
                        
                        ${calc.handling_charges > 0 ? `
                        <div class="rate-item">
                            <span class="rate-label">Handling Fee</span>
                            <span class="rate-value">KSh ${calc.handling_charges.toLocaleString(undefined, {minimumFractionDigits: 2})}</span>
                        </div>` : ''}
                        
                        <div class="rate-item">
                            <span class="rate-label"><strong>Subtotal</strong></span>
                            <span class="rate-value"><strong>KSh ${calc.subtotal.toLocaleString(undefined, {minimumFractionDigits: 2})}</strong></span>
                        </div>
                        
                        <div class="rate-item">
                            <span class="rate-label">VAT (16%)</span>
                            <span class="rate-value">KSh ${calc.tax_amount.toLocaleString(undefined, {minimumFractionDigits: 2})}</span>
                        </div>
                    </div>
                    
                    <div class="total-amount">
                        <i class="bx bx-calculator"></i>
                        Total Amount: KSh ${calc.total_charges.toLocaleString(undefined, {minimumFractionDigits: 2})}
                    </div>
                    
                    <div style="display: flex; gap: 1rem; margin-top: 1rem; justify-content: center;">
                        <a href="create_shipment.php?prefill=1" class="btn btn-primary">
                            <i class="bx bx-plus"></i> Book This Shipment
                        </a>
                        <button onclick="window.print()" class="btn btn-secondary">
                            <i class="bx bx-printer"></i> Print Quote
                        </button>
                    </div>
                `;
                
                // Store calculation in session storage for booking
                sessionStorage.setItem('rateCalculation', JSON.stringify({
                    calculation: calc,
                    serviceId: serviceSelect.value,
                    serviceName: serviceOption.text,
                    originLocationId: document.getElementById('origin_location').value,
                    destinationLocationId: document.getElementById('destination_location').value,
                    weight: document.getElementById('weight').value,
                    dimensions: {
                        length: document.getElementById('length').value,
                        width: document.getElementById('width').value,
                        height: document.getElementById('height').value
                    },
                    declaredValue: document.getElementById('declared_value').value
                }));
            }
            
            // Load customers for dropdown (if needed)
            loadCustomers();
            
            async function loadCustomers() {
                try {
                    const response = await fetch('api/get_customers.php');
                    const customers = await response.json();
                    
                    const customerSelect = document.getElementById('customer_id');
                    customers.forEach(customer => {
                        const option = document.createElement('option');
                        option.value = customer.customer_id;
                        option.textContent = customer.customer_type === 'CORPORATE' 
                            ? customer.company_name 
                            : `${customer.first_name} ${customer.last_name}`;
                        customerSelect.appendChild(option);
                    });
                } catch (error) {
                    console.log('Could not load customers:', error);
                }
            }
        });
    </script>
</body>
</html>