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

// Set timezone
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'];
$shipment_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$shipment_id) {
    $_SESSION['error_message'] = 'Invalid shipment ID';
    header('Location: shipments.php');
    exit();
}

// Initialize variables
$error_message = '';
$success_message = '';
$shipment = null;
$customers = [];
$service_types = [];
$locations = [];

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_shipment'])) {
    try {
        // Validate required fields
        $required_fields = ['sender_name', 'sender_phone', 'sender_address', 'sender_city', 'sender_country',
                           'receiver_name', 'receiver_phone', 'receiver_address', 'receiver_city', 'receiver_country',
                           'service_id', 'origin_location_id', 'destination_location_id', 'pieces', 
                           'actual_weight', 'chargeable_weight', 'content_description'];
        
        foreach ($required_fields as $field) {
            if (empty($_POST[$field])) {
                throw new Exception("Field " . ucfirst(str_replace('_', ' ', $field)) . " is required");
            }
        }
        
        // Start transaction
        $conn->begin_transaction();
        
        // Calculate volumetric weight if dimensions provided
        $volumetric_weight = 0;
        if (!empty($_POST['dimensions_length']) && !empty($_POST['dimensions_width']) && !empty($_POST['dimensions_height'])) {
            $volumetric_factor = 5000; // Default volumetric factor
            $volumetric_weight = ($_POST['dimensions_length'] * $_POST['dimensions_width'] * $_POST['dimensions_height']) / $volumetric_factor;
        }
        
        // Update shipment
        $update_sql = "UPDATE shipments SET 
            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 = ?,
            special_instructions = ?, handling_instructions = ?,
            customs_declaration = ?, commercial_invoice_required = ?, duty_payment = ?,
            updated_by = ?, updated_at = CURRENT_TIMESTAMP
            WHERE shipment_id = ?";
        
        $stmt = $conn->prepare($update_sql);
        
        // Bind parameters
        $sender_customer_id = !empty($_POST['sender_customer_id']) ? $_POST['sender_customer_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;
        $customs_declaration = isset($_POST['customs_declaration']) ? 1 : 0;
        $commercial_invoice_required = isset($_POST['commercial_invoice_required']) ? 1 : 0;
        $declared_value = !empty($_POST['declared_value']) ? $_POST['declared_value'] : 0;
        
        $stmt->bind_param("issssssssssssssssssiiisiissdddddddsdssssiiii",
            $sender_customer_id, $_POST['sender_name'], $_POST['sender_company'], $_POST['sender_email'], $_POST['sender_phone'],
            $_POST['sender_address'], $_POST['sender_city'], $_POST['sender_state'], $_POST['sender_postal_code'], $_POST['sender_country'],
            $_POST['receiver_name'], $_POST['receiver_company'], $_POST['receiver_email'], $_POST['receiver_phone'],
            $_POST['receiver_address'], $_POST['receiver_city'], $_POST['receiver_state'], $_POST['receiver_postal_code'], $_POST['receiver_country'],
            $_POST['service_id'], $_POST['origin_location_id'], $_POST['destination_location_id'],
            $pickup_required, $pickup_date, $pickup_time_from, $pickup_time_to,
            $_POST['pieces'], $_POST['package_type'], $_POST['actual_weight'], $volumetric_weight, $_POST['chargeable_weight'],
            $_POST['dimensions_length'], $_POST['dimensions_width'], $_POST['dimensions_height'],
            $_POST['content_description'], $declared_value, $_POST['currency'],
            $_POST['special_instructions'], $_POST['handling_instructions'],
            $customs_declaration, $commercial_invoice_required, $_POST['duty_payment'],
            $user_id, $shipment_id
        );
        
        if (!$stmt->execute()) {
            throw new Exception("Error updating shipment: " . $stmt->error);
        }
        
        // Log the update
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values, logged_at) 
                   VALUES (?, 'UPDATE', 'shipments', ?, 'Shipment details updated', NOW())";
        $log_stmt = $conn->prepare($log_sql);
        $log_stmt->bind_param("ii", $user_id, $shipment_id);
        $log_stmt->execute();
        $log_stmt->close();
        
        $stmt->close();
        $conn->commit();
        
        $success_message = "Shipment updated successfully!";
        
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = $e->getMessage();
    }
}

// Fetch shipment details
$shipment_sql = "SELECT s.*, 
    st.service_name, st.service_code,
    ol.location_name as origin_location_name,
    dl.location_name as destination_location_name,
    c.customer_code, c.company_name, c.first_name as customer_first_name, c.last_name as customer_last_name
    FROM shipments s
    LEFT JOIN service_types st ON s.service_id = st.service_id
    LEFT JOIN locations ol ON s.origin_location_id = ol.location_id
    LEFT JOIN locations dl ON s.destination_location_id = dl.location_id
    LEFT JOIN customers c ON s.sender_customer_id = c.customer_id
    WHERE s.shipment_id = ?";

$stmt = $conn->prepare($shipment_sql);
$stmt->bind_param("i", $shipment_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = 'Shipment not found';
    header('Location: shipments.php');
    exit();
}

$shipment = $result->fetch_assoc();
$stmt->close();

// Fetch customers for dropdown
$customers_sql = "SELECT customer_id, customer_code, company_name, first_name, last_name, customer_type 
                 FROM customers WHERE status = 'ACTIVE' ORDER BY company_name, first_name";
$customers_result = $conn->query($customers_sql);
if ($customers_result) {
    while ($row = $customers_result->fetch_assoc()) {
        $customers[] = $row;
    }
}

// Fetch service types
$services_sql = "SELECT service_id, service_code, service_name, description, service_category 
                FROM service_types WHERE is_active = 1 ORDER BY service_name";
$services_result = $conn->query($services_sql);
if ($services_result) {
    while ($row = $services_result->fetch_assoc()) {
        $service_types[] = $row;
    }
}

// Fetch locations
$locations_sql = "SELECT l.location_id, l.location_code, l.location_name, l.city, c.country_name,
                         l.is_origin, l.is_destination
                 FROM locations l
                 LEFT JOIN countries c ON l.country_id = c.country_id
                 WHERE l.is_active = 1 
                 ORDER BY c.country_name, l.location_name";
$locations_result = $conn->query($locations_sql);
if ($locations_result) {
    while ($row = $locations_result->fetch_assoc()) {
        $locations[] = $row;
    }
}

?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Shipment - Freight Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    
    <style>
        .form-section {
            background: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-left: 4px solid #1e40af;
        }
        
        .section-title {
            font-size: 18px;
            font-weight: 600;
            color: #1e40af;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e5e7eb;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 8px;
            display: block;
        }
        
        .required {
            color: #dc2626;
        }
        
        .form-control, .form-select {
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 12px;
            font-size: 14px;
            transition: border-color 0.2s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #1e40af;
            box-shadow: 0 0 0 3px rgba(30, 64, 175, 0.1);
            outline: none;
        }
        
        .btn {
            padding: 12px 24px;
            border-radius: 8px;
            font-weight: 600;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-primary {
            background: #1e40af;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
        }
        
        .btn-secondary {
            background: #6b7280;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #4b5563;
        }
        
        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid transparent;
        }
        
        .alert-success {
            background: #f0fdf4;
            color: #166534;
            border-color: #bbf7d0;
        }
        
        .alert-danger {
            background: #fef2f2;
            color: #dc2626;
            border-color: #fecaca;
        }
        
        .shipment-header {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            color: white;
            padding: 25px;
            border-radius: 12px;
            margin-bottom: 30px;
        }
        
        .shipment-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }
        
        .info-item {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        .info-label {
            font-size: 12px;
            opacity: 0.8;
            margin-bottom: 5px;
        }
        
        .info-value {
            font-size: 16px;
            font-weight: 600;
        }
        
        .checkbox-wrapper {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .checkbox-wrapper input[type="checkbox"] {
            width: 18px;
            height: 18px;
            accent-color: #1e40af;
        }
        
        .form-text {
            font-size: 12px;
            color: #6b7280;
            margin-top: 5px;
        }
        
        .currency-input {
            position: relative;
        }
        
        .currency-symbol {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #6b7280;
            font-weight: 600;
        }
        
        .currency-input input {
            padding-left: 40px;
        }
        
        .dimensions-row {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 15px;
        }
        
        @media (max-width: 768px) {
            .shipment-info {
                flex-direction: column;
                text-align: center;
            }
            
            .dimensions-row {
                grid-template-columns: 1fr;
            }
            
            .form-section {
                padding: 15px;
            }
        }
        
        .select2-container--default .select2-selection--single {
            height: 48px !important;
            border: 1px solid #d1d5db !important;
            border-radius: 8px !important;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 46px !important;
            padding-left: 12px !important;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 46px !important;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Shipment Header -->
                    <div class="shipment-header">
                        <div class="shipment-info">
                            <div class="info-item">
                                <div class="info-label">Tracking Number</div>
                                <div class="info-value"><?php echo htmlspecialchars($shipment['tracking_number']); ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Status</div>
                                <div class="info-value"><?php echo ucfirst(strtolower(str_replace('_', ' ', $shipment['status']))); ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Service</div>
                                <div class="info-value"><?php echo htmlspecialchars($shipment['service_name']); ?></div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Booking Date</div>
                                <div class="info-value"><?php echo date('M j, Y', strtotime($shipment['booking_date'])); ?></div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Alerts -->
                    <?php if (!empty($success_message)): ?>
                    <div class="alert alert-success"><?php echo htmlspecialchars($success_message); ?></div>
                    <?php endif; ?>
                    
                    <?php if (!empty($error_message)): ?>
                    <div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
                    <?php endif; ?>
                    
                    <!-- Edit Form -->
                    <form method="POST" id="editShipmentForm">
                        
                        <!-- Customer Information -->
                        <div class="form-section">
                            <h3 class="section-title">Customer Information</h3>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="form-label">Associated Customer (Optional)</label>
                                        <select name="sender_customer_id" class="form-select" id="customerSelect">
                                            <option value="">Select Customer (Optional)</option>
                                            <?php foreach ($customers as $customer): ?>
                                            <option value="<?php echo $customer['customer_id']; ?>" 
                                                <?php echo ($customer['customer_id'] == $shipment['sender_customer_id']) ? 'selected' : ''; ?>>
                                                <?php if ($customer['customer_type'] === 'CORPORATE'): ?>
                                                    <?php echo htmlspecialchars($customer['company_name']); ?> (<?php echo htmlspecialchars($customer['customer_code']); ?>)
                                                <?php else: ?>
                                                    <?php echo htmlspecialchars($customer['first_name'] . ' ' . $customer['last_name']); ?> (<?php echo htmlspecialchars($customer['customer_code']); ?>)
                                                <?php endif; ?>
                                            </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="form-text">Link this shipment to an existing customer for billing purposes</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Sender Information -->
                        <div class="form-section">
                            <h3 class="section-title">Sender Information</h3>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Full Name <span class="required">*</span></label>
                                        <input type="text" name="sender_name" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['sender_name']); ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Company Name</label>
                                        <input type="text" name="sender_company" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['sender_company']); ?>">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Email Address</label>
                                        <input type="email" name="sender_email" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['sender_email']); ?>">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Phone Number <span class="required">*</span></label>
                                        <input type="tel" name="sender_phone" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['sender_phone']); ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="form-label">Address <span class="required">*</span></label>
                                        <textarea name="sender_address" class="form-control" rows="2" required><?php echo htmlspecialchars($shipment['sender_address']); ?></textarea>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">City <span class="required">*</span></label>
                                        <input type="text" name="sender_city" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['sender_city']); ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">State/Province</label>
                                        <input type="text" name="sender_state" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['sender_state']); ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">Postal Code</label>
                                        <input type="text" name="sender_postal_code" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['sender_postal_code']); ?>">
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="form-label">Country <span class="required">*</span></label>
                                        <input type="text" name="sender_country" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['sender_country']); ?>" required>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Receiver Information -->
                        <div class="form-section">
                            <h3 class="section-title">Receiver Information</h3>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Full Name <span class="required">*</span></label>
                                        <input type="text" name="receiver_name" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['receiver_name']); ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Company Name</label>
                                        <input type="text" name="receiver_company" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['receiver_company']); ?>">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Email Address</label>
                                        <input type="email" name="receiver_email" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['receiver_email']); ?>">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Phone Number <span class="required">*</span></label>
                                        <input type="tel" name="receiver_phone" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['receiver_phone']); ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="form-label">Address <span class="required">*</span></label>
                                        <textarea name="receiver_address" class="form-control" rows="2" required><?php echo htmlspecialchars($shipment['receiver_address']); ?></textarea>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">City <span class="required">*</span></label>
                                        <input type="text" name="receiver_city" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['receiver_city']); ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">State/Province</label>
                                        <input type="text" name="receiver_state" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['receiver_state']); ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">Postal Code</label>
                                        <input type="text" name="receiver_postal_code" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['receiver_postal_code']); ?>">
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="form-label">Country <span class="required">*</span></label>
                                        <input type="text" name="receiver_country" class="form-control" 
                                               value="<?php echo htmlspecialchars($shipment['receiver_country']); ?>" required>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Service & Route Information -->
                        <div class="form-section">
                            <h3 class="section-title">Service & Route Information</h3>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">Service Type <span class="required">*</span></label>
                                        <select name="service_id" class="form-select" required>
                                            <option value="">Select Service</option>
                                            <?php foreach ($service_types as $service): ?>
                                            <option value="<?php echo $service['service_id']; ?>" 
                                                <?php echo ($service['service_id'] == $shipment['service_id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($service['service_name']); ?> (<?php echo htmlspecialchars($service['service_category']); ?>)
                                            </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">Origin Location <span class="required">*</span></label>
                                        <select name="origin_location_id" class="form-select" required>
                                            <option value="">Select Origin</option>
                                            <?php foreach ($locations as $location): ?>
                                            <?php if ($location['is_origin']): ?>
                                            <option value="<?php echo $location['location_id']; ?>" 
                                                <?php echo ($location['location_id'] == $shipment['origin_location_id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($location['location_name'] . ', ' . $location['country_name']); ?>
                                            </option>
                                            <?php endif; ?>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">Destination Location <span class="required">*</span></label>
                                        <select name="destination_location_id" class="form-select" required>
                                            <option value="">Select Destination</option>
                                            <?php foreach ($locations as $location): ?>
                                            <?php if ($location['is_destination']): ?>
                                            <option value="<?php echo $location['location_id']; ?>" 
                                                <?php echo ($location['location_id'] == $shipment['destination_location_id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($location['location_name'] . ', ' . $location['country_name']); ?>
                                            </option>
                                            <?php endif; ?>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Pickup Information -->
                        <div class="form-section">
                            <h3 class="section-title">Pickup Information</h3>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <div class="checkbox-wrapper">
                                            <input type="checkbox" name="pickup_required" id="pickupRequired" 
                                                   <?php echo $shipment['pickup_required'] ? 'checked' : ''; ?>>
                                            <label for="pickupRequired" class="form-label">Pickup Required</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4" id="pickupDateGroup" style="<?php echo $shipment['pickup_required'] ? '' : 'display:none;'; ?>">
                                    <div class="form-group">
                                        <label class="form-label">Pickup Date</label>
                                        <input type="date" name="pickup_date" class="form-control" 
                                               value="<?php echo $shipment['pickup_date']; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4" id="pickupTimeFromGroup" style="<?php echo $shipment['pickup_required'] ? '' : 'display:none;'; ?>">
                                    <div class="form-group">
                                        <label class="form-label">Pickup Time From</label>
                                        <input type="time" name="pickup_time_from" class="form-control" 
                                               value="<?php echo $shipment['pickup_time_from']; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4" id="pickupTimeToGroup" style="<?php echo $shipment['pickup_required'] ? '' : 'display:none;'; ?>">
                                    <div class="form-group">
                                        <label class="form-label">Pickup Time To</label>
                                        <input type="time" name="pickup_time_to" class="form-control" 
                                               value="<?php echo $shipment['pickup_time_to']; ?>">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Package Information -->
                        <div class="form-section">
                            <h3 class="section-title">Package Information</h3>
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label">Number of Pieces <span class="required">*</span></label>
                                        <input type="number" name="pieces" class="form-control" min="1" 
                                               value="<?php echo $shipment['pieces']; ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label">Package Type</label>
                                        <select name="package_type" class="form-select">
                                            <option value="BOX" <?php echo ($shipment['package_type'] === 'BOX') ? 'selected' : ''; ?>>Box</option>
                                            <option value="ENVELOPE" <?php echo ($shipment['package_type'] === 'ENVELOPE') ? 'selected' : ''; ?>>Envelope</option>
                                            <option value="PALLET" <?php echo ($shipment['package_type'] === 'PALLET') ? 'selected' : ''; ?>>Pallet</option>
                                            <option value="TUBE" <?php echo ($shipment['package_type'] === 'TUBE') ? 'selected' : ''; ?>>Tube</option>
                                            <option value="BAG" <?php echo ($shipment['package_type'] === 'BAG') ? 'selected' : ''; ?>>Bag</option>
                                            <option value="OTHER" <?php echo ($shipment['package_type'] === 'OTHER') ? 'selected' : ''; ?>>Other</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label">Actual Weight (KG) <span class="required">*</span></label>
                                        <input type="number" name="actual_weight" class="form-control" step="0.01" min="0.01" 
                                               value="<?php echo $shipment['actual_weight']; ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label class="form-label">Chargeable Weight (KG) <span class="required">*</span></label>
                                        <input type="number" name="chargeable_weight" class="form-control" step="0.01" min="0.01" 
                                               value="<?php echo $shipment['chargeable_weight']; ?>" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-12">
                                    <h4 style="margin: 20px 0 15px 0; color: #374151; font-size: 16px;">Package Dimensions (Optional)</h4>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">Length (CM)</label>
                                        <input type="number" name="dimensions_length" class="form-control" step="0.01" min="0" 
                                               value="<?php echo $shipment['dimensions_length']; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">Width (CM)</label>
                                        <input type="number" name="dimensions_width" class="form-control" step="0.01" min="0" 
                                               value="<?php echo $shipment['dimensions_width']; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">Height (CM)</label>
                                        <input type="number" name="dimensions_height" class="form-control" step="0.01" min="0" 
                                               value="<?php echo $shipment['dimensions_height']; ?>">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Content & Value Information -->
                        <div class="form-section">
                            <h3 class="section-title">Content & Value Information</h3>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="form-label">Content Description <span class="required">*</span></label>
                                        <textarea name="content_description" class="form-control" rows="3" 
                                                  placeholder="Describe the contents of the package..." required><?php echo htmlspecialchars($shipment['content_description']); ?></textarea>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Declared Value</label>
                                        <div class="currency-input">
                                            <span class="currency-symbol"><?php echo htmlspecialchars($shipment['currency'] ?: 'KES'); ?></span>
                                            <input type="number" name="declared_value" class="form-control" step="0.01" min="0" 
                                                   value="<?php echo $shipment['declared_value']; ?>">
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Currency</label>
                                        <select name="currency" class="form-select" id="currencySelect">
                                            <option value="KES" <?php echo ($shipment['currency'] === 'KES') ? 'selected' : ''; ?>>KES - Kenyan Shilling</option>
                                            <option value="USD" <?php echo ($shipment['currency'] === 'USD') ? 'selected' : ''; ?>>USD - US Dollar</option>
                                            <option value="EUR" <?php echo ($shipment['currency'] === 'EUR') ? 'selected' : ''; ?>>EUR - Euro</option>
                                            <option value="GBP" <?php echo ($shipment['currency'] === 'GBP') ? 'selected' : ''; ?>>GBP - British Pound</option>
                                            <option value="UGX" <?php echo ($shipment['currency'] === 'UGX') ? 'selected' : ''; ?>>UGX - Ugandan Shilling</option>
                                            <option value="TZS" <?php echo ($shipment['currency'] === 'TZS') ? 'selected' : ''; ?>>TZS - Tanzanian Shilling</option>
                                            <option value="RWF" <?php echo ($shipment['currency'] === 'RWF') ? 'selected' : ''; ?>>RWF - Rwandan Franc</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Special Instructions -->
                        <div class="form-section">
                            <h3 class="section-title">Special Instructions & Customs</h3>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Special Instructions</label>
                                        <textarea name="special_instructions" class="form-control" rows="3" 
                                                  placeholder="Any special handling instructions..."><?php echo htmlspecialchars($shipment['special_instructions']); ?></textarea>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-label">Handling Instructions</label>
                                        <textarea name="handling_instructions" class="form-control" rows="3" 
                                                  placeholder="Specific handling requirements..."><?php echo htmlspecialchars($shipment['handling_instructions']); ?></textarea>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <div class="checkbox-wrapper">
                                            <input type="checkbox" name="customs_declaration" id="customsDeclaration" 
                                                   <?php echo $shipment['customs_declaration'] ? 'checked' : ''; ?>>
                                            <label for="customsDeclaration" class="form-label">Customs Declaration Required</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <div class="checkbox-wrapper">
                                            <input type="checkbox" name="commercial_invoice_required" id="commercialInvoice" 
                                                   <?php echo $shipment['commercial_invoice_required'] ? 'checked' : ''; ?>>
                                            <label for="commercialInvoice" class="form-label">Commercial Invoice Required</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="form-label">Duty Payment</label>
                                        <select name="duty_payment" class="form-select">
                                            <option value="SENDER" <?php echo ($shipment['duty_payment'] === 'SENDER') ? 'selected' : ''; ?>>Sender Pays</option>
                                            <option value="RECEIVER" <?php echo ($shipment['duty_payment'] === 'RECEIVER') ? 'selected' : ''; ?>>Receiver Pays</option>
                                            <option value="THIRD_PARTY" <?php echo ($shipment['duty_payment'] === 'THIRD_PARTY') ? 'selected' : ''; ?>>Third Party</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Form Actions -->
                        <div class="form-section">
                            <div class="d-flex justify-content-between">
                                <a href="view_shipment.php?id=<?php echo $shipment_id; ?>" class="btn btn-secondary">
                                    <i class="bx bx-arrow-back"></i> Cancel
                                </a>
                                <button type="submit" name="update_shipment" class="btn btn-primary">
                                    <i class="bx bx-save"></i> Update Shipment
                                </button>
                            </div>
                        </div>
                        
                    </form>
                    
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <!-- Select2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            
            // Initialize Select2 for better dropdowns
            $('#customerSelect, .form-select').select2({
                theme: 'default',
                width: '100%'
            });
            
            // Handle pickup required checkbox
            const pickupRequiredCheckbox = document.getElementById('pickupRequired');
            const pickupFields = ['pickupDateGroup', 'pickupTimeFromGroup', 'pickupTimeToGroup'];
            
            pickupRequiredCheckbox.addEventListener('change', function() {
                pickupFields.forEach(fieldId => {
                    const field = document.getElementById(fieldId);
                    if (field) {
                        field.style.display = this.checked ? 'block' : 'none';
                    }
                });
            });
            
            // Update currency symbol when currency changes
            const currencySelect = document.getElementById('currencySelect');
            const currencySymbol = document.querySelector('.currency-symbol');
            
            if (currencySelect && currencySymbol) {
                currencySelect.addEventListener('change', function() {
                    const currencySymbols = {
                        'KES': 'KSh',
                        'USD': ',
                        'EUR': '€',
                        'GBP': '£',
                        'UGX': 'USh',
                        'TZS': 'TSh',
                        'RWF': 'RF'
                    };
                    currencySymbol.textContent = currencySymbols[this.value] || this.value;
                });
            }
            
            // Form validation and submission
            const form = document.getElementById('editShipmentForm');
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                
                // Show confirmation dialog
                Swal.fire({
                    title: 'Update Shipment?',
                    text: 'Are you sure you want to update this shipment with the new information?',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#1e40af',
                    cancelButtonColor: '#6b7280',
                    confirmButtonText: 'Yes, Update',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Show loading
                        Swal.fire({
                            title: 'Updating Shipment...',
                            text: 'Please wait while we update the shipment information.',
                            allowOutsideClick: false,
                            allowEscapeKey: false,
                            showConfirmButton: false,
                            didOpen: () => {
                                Swal.showLoading();
                            }
                        });
                        
                        // Submit the form
                        form.submit();
                    }
                });
            });
            
            // Show success/error messages with SweetAlert
            <?php if (!empty($success_message)): ?>
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: '<?php echo addslashes($success_message); ?>',
                confirmButtonColor: '#1e40af',
                timer: 3000,
                timerProgressBar: true
            });
            <?php endif; ?>
            
            <?php if (!empty($error_message)): ?>
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: '<?php echo addslashes($error_message); ?>',
                confirmButtonColor: '#dc2626'
            });
            <?php endif; ?>
            
            // Auto-calculate chargeable weight based on volumetric weight
            const dimensionInputs = document.querySelectorAll('input[name^="dimensions_"]');
            const actualWeightInput = document.querySelector('input[name="actual_weight"]');
            const chargeableWeightInput = document.querySelector('input[name="chargeable_weight"]');
            
            function calculateChargeableWeight() {
                const length = parseFloat(document.querySelector('input[name="dimensions_length"]').value) || 0;
                const width = parseFloat(document.querySelector('input[name="dimensions_width"]').value) || 0;
                const height = parseFloat(document.querySelector('input[name="dimensions_height"]').value) || 0;
                const actualWeight = parseFloat(actualWeightInput.value) || 0;
                
                if (length && width && height) {
                    const volumetricWeight = (length * width * height) / 5000;
                    const chargeableWeight = Math.max(actualWeight, volumetricWeight);
                    chargeableWeightInput.value = chargeableWeight.toFixed(2);
                    
                    // Show volumetric weight info
                    const info = document.getElementById('volumetricWeightInfo');
                    if (info) {
                        info.textContent = `Volumetric Weight: ${volumetricWeight.toFixed(2)} kg`;
                    }
                } else if (actualWeight) {
                    chargeableWeightInput.value = actualWeight.toFixed(2);
                }
            }
            
            // Add event listeners for weight calculation
            dimensionInputs.forEach(input => {
                input.addEventListener('input', calculateChargeableWeight);
            });
            
            if (actualWeightInput) {
                actualWeightInput.addEventListener('input', calculateChargeableWeight);
            }
            
            // Add volumetric weight info display
            const chargeableWeightGroup = chargeableWeightInput.closest('.form-group');
            if (chargeableWeightGroup) {
                const infoDiv = document.createElement('div');
                infoDiv.id = 'volumetricWeightInfo';
                infoDiv.className = 'form-text';
                chargeableWeightGroup.appendChild(infoDiv);
            }
            
            // Form field validation
            const requiredFields = document.querySelectorAll('input[required], select[required], textarea[required]');
            requiredFields.forEach(field => {
                field.addEventListener('blur', function() {
                    if (!this.value.trim()) {
                        this.style.borderColor = '#dc2626';
                        this.style.boxShadow = '0 0 0 3px rgba(220, 38, 38, 0.1)';
                    } else {
                        this.style.borderColor = '#10b981';
                        this.style.boxShadow = '0 0 0 3px rgba(16, 185, 129, 0.1)';
                    }
                });
                
                field.addEventListener('input', function() {
                    if (this.value.trim()) {
                        this.style.borderColor = '#d1d5db';
                        this.style.boxShadow = 'none';
                    }
                });
            });
            
            // Phone number formatting
            const phoneInputs = document.querySelectorAll('input[type="tel"]');
            phoneInputs.forEach(input => {
                input.addEventListener('input', function() {
                    // Remove non-numeric characters except + and spaces
                    let value = this.value.replace(/[^\d+\s-]/g, '');
                    this.value = value;
                });
            });
            
            // Email validation
            const emailInputs = document.querySelectorAll('input[type="email"]');
            emailInputs.forEach(input => {
                input.addEventListener('blur', function() {
                    if (this.value && !isValidEmail(this.value)) {
                        this.style.borderColor = '#dc2626';
                        Swal.fire({
                            toast: true,
                            position: 'top-end',
                            icon: 'warning',
                            title: 'Invalid Email Format',
                            showConfirmButton: false,
                            timer: 3000
                        });
                    }
                });
            });
            
            function isValidEmail(email) {
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                return emailRegex.test(email);
            }
            
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php
// Close database connection
if ($conn) {
    $conn->close();
}
?>