<?php
// Prevent any output before headers
ob_start();

// Disable error reporting for production
error_reporting(0);
ini_set('display_errors', 0);

// Set JSON header
header('Content-Type: application/json');

// Include required files
require_once 'layouts/session.php';
require_once 'layouts/dbconn.php';

$statuses = [
    'pending' => 'Pending',
    'confirmed' => 'Confirmed',
    'picked_up' => 'Picked Up',
    'in_office' => 'In Office',
    'in_transit' => 'In Transit',
    'arrived_destination' => 'Arrived at Destination',
    'out_for_delivery' => 'Out for Delivery',
    'delivered' => 'Delivered',
    'failed_delivery' => 'Failed Delivery',
    'on_hold' => 'On Hold',
    'cancelled' => 'Cancelled',
    'returned' => 'Returned'
];

// Clean any existing output buffers
while (ob_get_level()) {
    ob_end_clean();
}

try {
    if (!isset($_POST['booking_id']) || !isset($_POST['booking_status'])) {
        throw new Exception('Required fields are missing');
    }

    $booking_id = intval($_POST['booking_id']);
    $new_status = $_POST['booking_status'];
    $status_notes = $_POST['status_notes'] ?? '';
    $current_user_id = $_SESSION['user_id'] ?? null;

    if (!$current_user_id) {
        throw new Exception('User session not found. Please log in again.');
    }

    // Validate booking exists
    $check_query = "SELECT booking_status FROM cargo_bookings WHERE booking_id = ?";
    $stmt = $conn->prepare($check_query);
    if (!$stmt) {
        throw new Exception('Database prepare error: ' . $conn->error);
    }
    
    $stmt->bind_param("i", $booking_id);
    if (!$stmt->execute()) {
        throw new Exception('Error checking booking: ' . $stmt->error);
    }
    
    $result = $stmt->get_result();
    if ($result->num_rows === 0) {
        throw new Exception('Booking not found');
    }
    
    $conn->begin_transaction();

    $update_query = "UPDATE cargo_bookings SET 
        booking_status = ?,
        status_notes = ?,
        last_status_update = CURRENT_TIMESTAMP,
        last_status_update_by = ?";

    if ($new_status === 'delivered') {
        $update_query .= ", actual_delivery_date = CURRENT_TIMESTAMP";
    }

    if ($new_status === 'failed_delivery') {
        $update_query .= ", delivery_attempts = delivery_attempts + 1, last_attempt_date = CURRENT_TIMESTAMP";
    }

    $update_query .= " WHERE booking_id = ?";

    $stmt = $conn->prepare($update_query);
    if (!$stmt) {
        throw new Exception('Database prepare error: ' . $conn->error);
    }

    $stmt->bind_param("ssii", $new_status, $status_notes, $current_user_id, $booking_id);
    if (!$stmt->execute()) {
        throw new Exception('Error updating status: ' . $stmt->error);
    }

    if ($stmt->affected_rows === 0) {
        throw new Exception('No changes were made to the booking');
    }

    $conn->commit();
    
    // Ensure clean output before JSON
    while (ob_get_level()) {
        ob_end_clean();
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Status updated successfully to ' . ($statuses[$new_status] ?? $new_status),
        'booking_id' => $booking_id
    ]);

} catch (Exception $e) {
    if ($conn && $conn->ping()) {
        $conn->rollback();
    }
    
    // Ensure clean output before JSON
    while (ob_get_level()) {
        ob_end_clean();
    }
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

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

// End and flush output buffer
if (ob_get_level()) {
    ob_end_flush();
}
exit();
?>
<?php include 'layouts/main.php'; ?>
<head>

    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Update Cargo Status')); ?>
    
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <?php include 'layouts/head-css.php'; ?>
     <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body>

    <!-- Begin page -->
    <div id="layout-wrapper">

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

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">

            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Cargo', 'title' => 'Update Status')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Update Cargo Status</h4>
                                </div>
                                <div class="card-body">
                                    <form action="update_cargo_status.php" method="post">
                                        <input type="hidden" name="booking_id" value="<?php echo $booking_id; ?>">
                                        
                                        <div class="row mb-3">
                                            <div class="col-lg-3">
                                                <label class="form-label">Booking Number</label>
                                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($booking['booking_number']); ?>" readonly>
                                            </div>
                                            <div class="col-lg-3">
                                                <label class="form-label">Current Status</label>
                                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($statuses[$booking['booking_status']]); ?>" readonly>
                                            </div>
                                            <div class="col-lg-6">
                                                <label class="form-label">New Status</label>
                                                <select name="booking_status" class="form-select" required>
                                                    <option value="">Select Status</option>
                                                    <?php foreach ($statuses as $value => $label): ?>
                                                        <option value="<?php echo $value; ?>" <?php echo ($booking['booking_status'] == $value) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($label); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Status Notes</label>
                                            <textarea name="status_notes" class="form-control" rows="4" placeholder="Enter any notes about this status update"><?php echo htmlspecialchars($booking['status_notes']); ?></textarea>
                                        </div>

                                        <div class="text-end">
                                            <a href="all_cargo.php" class="btn btn-light me-2">Cancel</a>
                                            <button type="submit" class="btn btn-primary">Update Status</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->

    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>

    <!-- prismjs plugin -->
    <script src="assets/libs/prismjs/prism.js"></script>

    <script src="assets/js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <!--select2 cdn-->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/js/pages/select2.init.js"></script>

</body>

</html>