<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/menu_config.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'];
$order_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$order_id) {
    header('Location: all_orders.php');
    exit();
}

// 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();

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    header('Content-Type: application/json');
    
    $response = ['success' => false, 'message' => 'Unknown error'];
    
    try {
        if ($_POST['action'] == 'add_payment') {
            $amount = floatval($_POST['amount']);
            $payment_method_id = intval($_POST['payment_method_id']);
            $transaction_reference = $_POST['transaction_reference'] ?? '';
            
            // Get order info
            $order_sql = "SELECT customer_id, balance_amount, total_amount, paid_amount FROM orders WHERE order_id = ?";
            $stmt = $conn->prepare($order_sql);
            $stmt->bind_param("i", $order_id);
            $stmt->execute();
            $order_info = $stmt->get_result()->fetch_assoc();
            
            if ($amount > 0 && $amount <= $order_info['balance_amount']) {
                $conn->begin_transaction();
                
                // Insert payment
                $payment_sql = "INSERT INTO payments (order_id, customer_id, payment_method_id, amount, transaction_reference, processed_by, status) 
                               VALUES (?, ?, ?, ?, ?, ?, 'COMPLETED')";
                $stmt = $conn->prepare($payment_sql);
                $stmt->bind_param("iiidsi", $order_id, $order_info['customer_id'], $payment_method_id, $amount, $transaction_reference, $user_id);
                $stmt->execute();
                
                // Update order
                $new_paid = $order_info['paid_amount'] + $amount;
                $new_balance = $order_info['total_amount'] - $new_paid;
                $payment_status = $new_balance <= 0 ? 'PAID' : 'PARTIAL';
                
                $update_sql = "UPDATE orders SET paid_amount = ?, balance_amount = ?, payment_status = ?, updated_by = ? WHERE order_id = ?";
                $stmt = $conn->prepare($update_sql);
                $stmt->bind_param("ddsii", $new_paid, $new_balance, $payment_status, $user_id, $order_id);
                $stmt->execute();
                
                // Log activity
                $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values, ip_address) 
                               VALUES (?, 'UPDATE', 'PAYMENT', ?, ?, ?)";
                $stmt = $conn->prepare($activity_sql);
                $log_data = json_encode(['amount' => $amount, 'method' => $payment_method_id]);
                $ip_address = $_SERVER['REMOTE_ADDR'];
                $stmt->bind_param("isss", $user_id, $order_id, $log_data, $ip_address);
                $stmt->execute();
                
                $conn->commit();
                $response = [
                    'success' => true, 
                    'message' => 'Payment of KES ' . number_format($amount, 2) . ' added successfully!',
                    'new_balance' => $new_balance,
                    'new_paid' => $new_paid,
                    'payment_status' => $payment_status
                ];
            } else {
                $response = ['success' => false, 'message' => 'Invalid payment amount!'];
            }
        }
        
        elseif ($_POST['action'] == 'update_status') {
            $new_status = $_POST['new_status'];
            $status_notes = $_POST['status_notes'] ?? '';
            $update_items = isset($_POST['update_items']) ? true : false;
            
            $conn->begin_transaction();
            
            // Get current status
            $current_sql = "SELECT status FROM orders WHERE order_id = ?";
            $stmt = $conn->prepare($current_sql);
            $stmt->bind_param("i", $order_id);
            $stmt->execute();
            $current_status = $stmt->get_result()->fetch_assoc()['status'];
            
            // Update order status
            $update_sql = "UPDATE orders SET status = ?, updated_by = ?, updated_at = NOW() WHERE order_id = ?";
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("sii", $new_status, $user_id, $order_id);
            $stmt->execute();
            
            // Update items if requested
            if ($update_items) {
                $item_status = match($new_status) {
                    'PENDING' => 'PENDING',
                    'IN_PROGRESS' => 'IN_PROGRESS',
                    'READY', 'DELIVERED' => 'COMPLETED',
                    'CANCELLED' => 'CANCELLED',
                    default => 'PENDING'
                };
                
                $update_items_sql = "UPDATE order_items SET status = ? WHERE order_id = ? AND status NOT IN ('DAMAGED', 'LOST')";
                $stmt = $conn->prepare($update_items_sql);
                $stmt->bind_param("si", $item_status, $order_id);
                $stmt->execute();
            }
            
            // Log status history
            $history_sql = "INSERT INTO order_status_history (order_id, old_status, new_status, changed_by, change_reason) 
                           VALUES (?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($history_sql);
            $stmt->bind_param("issis", $order_id, $current_status, $new_status, $user_id, $status_notes);
            $stmt->execute();
            
            // Update delivery dates
            if ($new_status == 'READY' || $new_status == 'DELIVERED') {
                $delivery_sql = "UPDATE orders SET actual_delivery = NOW() WHERE order_id = ?";
                $stmt = $conn->prepare($delivery_sql);
                $stmt->bind_param("i", $order_id);
                $stmt->execute();
            }
            
            $conn->commit();
            $response = [
                'success' => true, 
                'message' => 'Order status updated to ' . $new_status . ' successfully!' . ($update_items ? ' Items also updated.' : ''),
                'new_status' => $new_status,
                'items_updated' => $update_items
            ];
        }
        
        elseif ($_POST['action'] == 'send_sms') {
            $phone = $_POST['customer_phone'];
            $message = $_POST['message'];
            $message_type = $_POST['message_type'] ?? 'custom';
            
            // Simple SMS simulation - replace with actual SMS integration
            $response = [
                'success' => true,
                'message' => 'SMS sent successfully to ' . $phone
            ];
            
            // Log SMS activity
            $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values, ip_address) 
                           VALUES (?, 'CREATE', 'SMS', ?, ?, ?)";
            $stmt = $conn->prepare($activity_sql);
            $log_data = json_encode(['phone' => $phone, 'type' => $message_type, 'length' => strlen($message)]);
            $ip_address = $_SERVER['REMOTE_ADDR'];
            $stmt->bind_param("isss", $user_id, $order_id, $log_data, $ip_address);
            $stmt->execute();
        }
        
    } catch (Exception $e) {
        if ($conn->inTransaction()) {
            $conn->rollback();
        }
        $response = ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
    
    echo json_encode($response);
    exit();
}

// Fetch complete order details
$sql_order = "SELECT o.*, 
                     c.first_name, c.last_name, c.phone, c.email, c.address, c.customer_code,
                     creator.full_name as created_by_name,
                     assignee.full_name as assigned_to_name,
                     updater.full_name as updated_by_name
              FROM orders o
              LEFT JOIN customers c ON o.customer_id = c.customer_id
              LEFT JOIN users creator ON o.created_by = creator.user_id
              LEFT JOIN users assignee ON o.assigned_to = assignee.user_id  
              LEFT JOIN users updater ON o.updated_by = updater.user_id
              WHERE o.order_id = ?";

$stmt_order = $conn->prepare($sql_order);
$stmt_order->bind_param("i", $order_id);
$stmt_order->execute();
$order = $stmt_order->get_result()->fetch_assoc();

if (!$order) {
    header('Location: all_orders.php?error=Order not found');
    exit();
}

// Fetch order items
$sql_items = "SELECT oi.*, s.service_name, s.unit, sc.category_name
              FROM order_items oi
              LEFT JOIN services s ON oi.service_id = s.service_id
              LEFT JOIN service_categories sc ON s.category_id = sc.category_id
              WHERE oi.order_id = ?
              ORDER BY oi.item_id";

$stmt_items = $conn->prepare($sql_items);
$stmt_items->bind_param("i", $order_id);
$stmt_items->execute();
$order_items = $stmt_items->get_result();

// Fetch payment methods
$sql_payment_methods = "SELECT * FROM payment_methods WHERE is_active = 1 ORDER BY sort_order";
$payment_methods = $conn->query($sql_payment_methods);

// Fetch payments for this order
$sql_payments = "SELECT p.*, pm.method_name, u.full_name as processed_by_name
                 FROM payments p
                 LEFT JOIN payment_methods pm ON p.payment_method_id = pm.method_id
                 LEFT JOIN users u ON p.processed_by = u.user_id
                 WHERE p.order_id = ?
                 ORDER BY p.created_at DESC";

$stmt_payments = $conn->prepare($sql_payments);
$stmt_payments->bind_param("i", $order_id);
$stmt_payments->execute();
$payments = $stmt_payments->get_result();

// Fetch status history
$sql_history = "SELECT h.*, u.full_name as changed_by_name
                FROM order_status_history h
                LEFT JOIN users u ON h.changed_by = u.user_id
                WHERE h.order_id = ?
                ORDER BY h.changed_at DESC";

$stmt_history = $conn->prepare($sql_history);
$stmt_history->bind_param("i", $order_id);
$stmt_history->execute();
$status_history = $stmt_history->get_result();

// Fetch delivery information
$sql_delivery = "SELECT od.*, dr.route_name, dr.delivery_fee as route_fee
                 FROM order_deliveries od
                 LEFT JOIN delivery_routes dr ON od.route_id = dr.route_id
                 WHERE od.order_id = ?";
$stmt_delivery = $conn->prepare($sql_delivery);
$stmt_delivery->bind_param("i", $order_id);
$stmt_delivery->execute();
$delivery_info = $stmt_delivery->get_result()->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Order #' . $order['order_number'])); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- SweetAlert2 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.32/dist/sweetalert2.min.css">
    
    <style>
        body { 
            background-color: #f8fafc; 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content { padding: 1.5rem; }
        
        .order-header {
            background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .order-info-card, .action-card, .data-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .card-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            border-radius: 12px 12px 0 0;
        }
        
        .card-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .card-body { padding: 1.5rem; }
        
        .status-badge {
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-size: 0.875rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-in_progress { background: #dbeafe; color: #1d4ed8; }
        .status-ready { background: #d1fae5; color: #065f46; }
        .status-delivered { background: #dcfce7; color: #166534; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        .status-completed { background: #dcfce7; color: #166534; }
        .status-damaged { background: #fee2e2; color: #991b1b; }
        .status-lost { background: #fee2e2; color: #991b1b; }
        
        .payment-pending { background: #fef3c7; color: #92400e; }
        .payment-partial { background: #fed7aa; color: #9a3412; }
        .payment-paid { background: #dcfce7; color: #166534; }
        .payment-refunded { background: #fee2e2; color: #991b1b; }
        
        .priority-normal { background: #f1f5f9; color: #475569; }
        .priority-high { background: #fed7aa; color: #9a3412; }
        .priority-urgent { background: #fee2e2; color: #991b1b; }
        
        .action-btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
            transition: all 0.2s ease;
            border: none;
            cursor: pointer;
            font-size: 0.875rem;
            width: 100%;
            text-align: center;
        }
        
        .btn-primary { background: #3b82f6; color: white; }
        .btn-success { background: #059669; color: white; }
        .btn-warning { background: #d97706; color: white; }
        .btn-info { background: #0891b2; color: white; }
        .btn-secondary { background: #64748b; color: white; }
        
        .action-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            color: white;
            text-decoration: none;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover { background: #f8fafc; }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
        }
        
        .info-item { display: flex; flex-direction: column; }
        
        .info-label {
            font-size: 0.75rem;
            font-weight: 600;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 0.25rem;
        }
        
        .info-value {
            font-weight: 600;
            color: #1e293b;
        }
        
        /* Custom SweetAlert2 Styling */
        .swal2-popup {
            border-radius: 12px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        .swal2-title {
            font-size: 1.25rem;
            font-weight: 600;
        }
        
        .swal2-input, .swal2-textarea, .swal2-select {
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            margin: 0.25rem 0;
        }
        
        .swal2-input:focus, .swal2-textarea:focus, .swal2-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .swal2-confirm {
            background: #3b82f6 !important;
            border-radius: 8px;
            font-weight: 600;
            padding: 0.75rem 1.5rem;
        }
        
        .swal2-cancel {
            background: #64748b !important;
            border-radius: 8px;
            font-weight: 600;
            padding: 0.75rem 1.5rem;
        }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 9999;
        }
        
        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f4f6;
            border-top: 4px solid #3b82f6;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        @media (max-width: 768px) {
            .page-content { padding: 1rem; }
            .order-header { padding: 1rem; }
            .card-header, .card-body { padding: 1rem; }
            .info-grid { grid-template-columns: 1fr; }
        }
        
        @media print {
            body { background: white; }
            .no-print { display: none !important; }
            .order-header { background: #3b82f6 !important; color: white !important; }
        }
    </style>
</head>

<body>
    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-spinner"></div>
    </div>

    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Order Header -->
                    <div class="order-header">
                        <div class="d-flex justify-content-between align-items-start flex-wrap">
                            <div>
                                <h1 style="font-size: 2rem; font-weight: 700; margin-bottom: 0.5rem;">
                                    Order #<?php echo $order['order_number']; ?>
                                </h1>
                                <div class="d-flex flex-wrap align-items-center gap-3">
                                    <span class="status-badge status-<?php echo strtolower($order['status']); ?>" id="orderStatusBadge">
                                        <?php echo $order['status']; ?>
                                    </span>
                                    <?php if ($order['payment_status'] !== 'PAID'): ?>
                                    <span class="status-badge payment-<?php echo strtolower($order['payment_status']); ?>" id="paymentStatusBadge">
                                        Payment: <?php echo str_replace('_', ' ', $order['payment_status']); ?>
                                    </span>
                                    <?php endif; ?>
                                    <span class="status-badge priority-<?php echo strtolower($order['priority']); ?>">
                                        <?php echo $order['priority']; ?> Priority
                                    </span>
                                </div>
                            </div>
                            <div class="text-end">
                                <div style="font-size: 1.5rem; font-weight: 700; margin-bottom: 0.25rem;">
                                    KES <?php echo number_format($order['total_amount'], 2); ?>
                                </div>
                                <div style="opacity: 0.8;">
                                    <?php echo date('M j, Y g:i A', strtotime($order['order_date'])); ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Left Column -->
                        <div class="col-xl-8">
                            
                            <!-- Customer Information -->
                            <div class="order-info-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="ph-user-circle"></i>Customer Information
                                    </h3>
                                </div>
                                <div class="card-body">
                                    <div class="info-grid">
                                        <div class="info-item">
                                            <span class="info-label">Customer Name</span>
                                            <span class="info-value"><?php echo $order['first_name'] . ' ' . $order['last_name']; ?></span>
                                        </div>
                                        <div class="info-item">
                                            <span class="info-label">Customer Code</span>
                                            <span class="info-value"><?php echo $order['customer_code']; ?></span>
                                        </div>
                                        <div class="info-item">
                                            <span class="info-label">Phone Number</span>
                                            <span class="info-value"><?php echo $order['phone']; ?></span>
                                        </div>
                                        <div class="info-item">
                                            <span class="info-label">Email</span>
                                            <span class="info-value"><?php echo $order['email'] ?: 'Not provided'; ?></span>
                                        </div>
                                        <div class="info-item">
                                            <span class="info-label">Address</span>
                                            <span class="info-value"><?php echo $order['address'] ?: 'Not provided'; ?></span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Order Items -->
                            <div class="data-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="ph-package"></i>Order Items
                                    </h3>
                                </div>
                                <div class="card-body p-0">
                                    <table class="data-table">
                                        <thead>
                                            <tr>
                                                <th>Service</th>
                                                <th>Category</th>
                                                <th>Description</th>
                                                <th>Qty</th>
                                                <th>Unit Price</th>
                                                <th>Total</th>
                                                <th>Status</th>
                                            </tr>
                                        </thead>
                                        <tbody id="orderItemsTable">
                                            <?php while ($item = $order_items->fetch_assoc()): ?>
                                            <tr>
                                                <td style="font-weight: 600;"><?php echo $item['service_name']; ?></td>
                                                <td>
                                                    <span class="status-badge" style="font-size: 0.75rem; background: #f3f4f6; color: #374151;">
                                                        <?php echo $item['category_name']; ?>
                                                    </span>
                                                </td>
                                                <td><?php echo $item['item_description'] ?: '-'; ?></td>
                                                <td style="font-weight: 600;"><?php echo $item['quantity']; ?></td>
                                                <td>KES <?php echo number_format($item['unit_price'], 2); ?></td>
                                                <td style="font-weight: 600; color: #059669;">
                                                    KES <?php echo number_format($item['total_price'], 2); ?>
                                                </td>
                                                <td>
                                                    <span class="status-badge status-<?php echo strtolower($item['status']); ?>" style="font-size: 0.75rem;">
                                                        <?php echo $item['status']; ?>
                                                    </span>
                                                    <?php if ($item['status'] === 'DAMAGED' || $item['status'] === 'LOST'): ?>
                                                    <div style="margin-top: 2px;">
                                                        <small style="color: #dc2626; font-weight: 600;">⚠ Requires Action</small>
                                                    </div>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                        <tfoot>
                                            <tr style="background: #f8fafc; font-weight: 600;">
                                                <td colspan="5" style="text-align: right; padding: 1rem;">TOTAL:</td>
                                                <td style="color: #059669; font-size: 1.1rem;">
                                                    KES <?php echo number_format($order['total_amount'], 2); ?>
                                                </td>
                                                <td></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>

                            <!-- Payment History -->
                            <div class="data-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="ph-credit-card"></i>Payment History
                                    </h3>
                                </div>
                                <div class="card-body p-0">
                                    <div id="paymentHistoryContainer">
                                        <?php if ($payments->num_rows > 0): ?>
                                            <table class="data-table">
                                                <thead>
                                                    <tr>
                                                        <th>Payment #</th>
                                                        <th>Amount</th>
                                                        <th>Method</th>
                                                        <th>Reference</th>
                                                        <th>Date</th>
                                                        <th>Processed By</th>
                                                        <th>Status</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
    <?php while ($payment = $payments->fetch_assoc()): ?>
        <tr>
            <td style="font-weight: 600;"><?php echo $payment['payment_number']; ?></td>
            <td style="font-weight: 600; color: #059669;">
                KES <?php echo number_format($payment['amount'], 2); ?>
            </td>
            <td><?php echo $payment['method_name']; ?></td>
            <td><?php echo $payment['transaction_reference'] ?: '-'; ?></td>
            <td><?php echo date('M j, Y g:i A', strtotime($payment['payment_date'])); ?></td>
            <td><?php echo $payment['processed_by_name']; ?></td>
            <td>
                <span class="status-badge status-<?php echo strtolower($payment['status']); ?>" style="font-size: 0.75rem;">
                    <?php echo $payment['status']; ?>
                </span>
            </td>
        </tr>
    <?php endwhile; ?>
</tbody>

                                            </table>
                                        <?php else: ?>
                                            <div class="card-body text-center" style="color: #64748b;">
                                                <i class="ph-credit-card" style="font-size: 3rem; opacity: 0.3; margin-bottom: 1rem; display: block;"></i>
                                                No payments recorded yet
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Status History -->
                            <div class="data-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="ph-clock-clockwise"></i>Status History
                                    </h3>
                                </div>
                                <div class="card-body p-0">
                                    <div id="statusHistoryContainer">
                                        <?php if ($status_history->num_rows > 0): ?>
                                            <table class="data-table">
                                                <thead>
                                                    <tr>
                                                        <th>From</th>
                                                        <th>To</th>
                                                        <th>Changed By</th>
                                                        <th>Reason</th>
                                                        <th>Date</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php while ($history = $status_history->fetch_assoc()): ?>
                                                    <tr>
                                                        <td>
                                                            <?php if ($history['old_status']): ?>
                                                                <span class="status-badge status-<?php echo strtolower($history['old_status']); ?>" style="font-size: 0.75rem;">
                                                                    <?php echo $history['old_status']; ?>
                                                                </span>
                                                            <?php else: ?>
                                                                <span style="color: #64748b;">-</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <span class="status-badge status-<?php echo strtolower($history['new_status']); ?>" style="font-size: 0.75rem;">
                                                                <?php echo $history['new_status']; ?>
                                                            </span>
                                                        </td>
                                                        <td style="font-weight: 600;"><?php echo $history['changed_by_name']; ?></td>
                                                        <td><?php echo $history['change_reason'] ?: '-'; ?></td>
                                                        <td><?php echo date('M j, Y g:i A', strtotime($history['changed_at'])); ?></td>
                                                    </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        <?php else: ?>
                                            <div class="card-body text-center" style="color: #64748b;">
                                                <i class="ph-clock-clockwise" style="font-size: 3rem; opacity: 0.3; margin-bottom: 1rem; display: block;"></i>
                                                No status changes recorded yet
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Right Column - Actions & Details -->
                        <div class="col-xl-4">
                            
                            <!-- Quick Actions -->
                            <div class="action-card no-print">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="ph-lightning"></i>Quick Actions
                                    </h3>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex flex-column gap-2">
                                        <?php if ($order['balance_amount'] > 0): ?>
                                        <button class="action-btn btn-primary" onclick="showAddPaymentModal()">
                                            <i class="ph-plus me-2"></i>Add Payment
                                        </button>
                                        <?php endif; ?>
                                        
                                        <button class="action-btn btn-info" onclick="showUpdateStatusModal()">
                                            <i class="ph-arrows-clockwise me-2"></i>Update Status
                                        </button>
                                        
                                        <button class="action-btn btn-success" onclick="generateReceipt()">
                                            <i class="ph-receipt me-2"></i>Generate Receipt
                                        </button>
                                        
                                        <button class="action-btn btn-warning" onclick="generateTicket()">
                                            <i class="ph-ticket me-2"></i>Order Ticket
                                        </button>
                                        
                                        <button class="action-btn btn-info" onclick="showSendSmsModal()">
                                            <i class="ph-chat-text me-2"></i>Send SMS
                                        </button>
                                        
                                        <a href="edit_order.php?id=<?php echo $order_id; ?>" class="action-btn btn-secondary">
                                            <i class="ph-pencil me-2"></i>Edit Order
                                        </a>
                                        
                                        <button class="action-btn btn-secondary" onclick="printOrder()">
                                            <i class="ph-printer me-2"></i>Print Order
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- Order Summary -->
                            <div class="order-info-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="ph-calculator"></i>Order Summary
                                    </h3>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <span>Subtotal:</span>
                                        <span style="font-weight: 600;">KES <?php echo number_format($order['subtotal'], 2); ?></span>
                                    </div>
                                    
                                    <?php if ($order['discount_amount'] > 0): ?>
                                    <div class="d-flex justify-content-between align-items-center mb-3" style="color: #dc2626;">
                                        <span>Discount:</span>
                                        <span style="font-weight: 600;">-KES <?php echo number_format($order['discount_amount'], 2); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($order['tax_amount'] > 0): ?>
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <span>Tax:</span>
                                        <span style="font-weight: 600;">KES <?php echo number_format($order['tax_amount'], 2); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <hr style="margin: 1rem 0; border-color: #e2e8f0;">
                                    
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <span style="font-size: 1.1rem; font-weight: 600;">Total Amount:</span>
                                        <span style="font-size: 1.25rem; font-weight: 700; color: #059669;">
                                            KES <?php echo number_format($order['total_amount'], 2); ?>
                                        </span>
                                    </div>
                                    
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <span>Paid Amount:</span>
                                        <span style="font-weight: 600; color: #059669;" id="paidAmountDisplay">KES <?php echo number_format($order['paid_amount'], 2); ?></span>
                                    </div>
                                    
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span>Balance:</span>
                                        <span style="font-weight: 600; color: <?php echo $order['balance_amount'] > 0 ? '#dc2626' : '#059669'; ?>;" id="balanceAmountDisplay">
                                            KES <?php echo number_format($order['balance_amount'], 2); ?>
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <!-- Order Details -->
                            <div class="order-info-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="ph-info"></i>Order Details
                                    </h3>
                                </div>
                                <div class="card-body">
                                    <div class="info-grid">
                                        <div class="info-item">
                                            <span class="info-label">Order Date</span>
                                            <span class="info-value"><?php echo date('M j, Y g:i A', strtotime($order['order_date'])); ?></span>
                                        </div>
                                        
                                        <?php if ($order['pickup_date']): ?>
                                        <div class="info-item">
                                            <span class="info-label">Pickup Date</span>
                                            <span class="info-value"><?php echo date('M j, Y', strtotime($order['pickup_date'])); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($order['delivery_date']): ?>
                                        <div class="info-item">
                                            <span class="info-label">Delivery Date</span>
                                            <span class="info-value"><?php echo date('M j, Y', strtotime($order['delivery_date'])); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($order['estimated_delivery']): ?>
                                        <div class="info-item">
                                            <span class="info-label">Estimated Delivery</span>
                                            <span class="info-value"><?php echo date('M j, Y g:i A', strtotime($order['estimated_delivery'])); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <div class="info-item">
                                            <span class="info-label">Total Pieces</span>
                                            <span class="info-value"><?php echo $order['total_pieces']; ?></span>
                                        </div>
                                        
                                        <div class="info-item">
                                            <span class="info-label">Created By</span>
                                            <span class="info-value"><?php echo $order['created_by_name']; ?></span>
                                        </div>
                                        
                                        <?php if ($order['assigned_to_name']): ?>
                                        <div class="info-item">
                                            <span class="info-label">Assigned To</span>
                                            <span class="info-value"><?php echo $order['assigned_to_name']; ?></span>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <?php if ($order['special_instructions']): ?>
                                    <div class="mt-4">
                                        <span class="info-label">Special Instructions</span>
                                        <div style="background: #f8fafc; padding: 1rem; border-radius: 8px; margin-top: 0.5rem;">
                                            <?php echo nl2br(htmlspecialchars($order['special_instructions'])); ?>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($order['customer_notes']): ?>
                                    <div class="mt-3">
                                        <span class="info-label">Customer Notes</span>
                                        <div style="background: #f0fdf4; padding: 1rem; border-radius: 8px; margin-top: 0.5rem;">
                                            <?php echo nl2br(htmlspecialchars($order['customer_notes'])); ?>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($order['internal_notes']): ?>
                                    <div class="mt-3">
                                        <span class="info-label">Internal Notes</span>
                                        <div style="background: #fef3c7; padding: 1rem; border-radius: 8px; margin-top: 0.5rem;">
                                            <?php echo nl2br(htmlspecialchars($order['internal_notes'])); ?>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Delivery Information -->
                            <?php if ($delivery_info): ?>
                            <div class="order-info-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="ph-truck"></i>Delivery Information
                                    </h3>
                                </div>
                                <div class="card-body">
                                    <div class="info-grid">
                                        <div class="info-item">
                                            <span class="info-label">Route</span>
                                            <span class="info-value"><?php echo $delivery_info['route_name'] ?: 'Not specified'; ?></span>
                                        </div>
                                        
                                        <div class="info-item">
                                            <span class="info-label">Delivery Fee</span>
                                            <span class="info-value">KES <?php echo number_format($delivery_info['delivery_fee'], 2); ?></span>
                                        </div>
                                        
                                        <div class="info-item">
                                            <span class="info-label">Status</span>
                                            <span class="status-badge status-<?php echo strtolower($delivery_info['delivery_status']); ?>" style="font-size: 0.75rem;">
                                                <?php echo str_replace('_', ' ', $delivery_info['delivery_status']); ?>
                                            </span>
                                        </div>
                                        
                                        <?php if ($delivery_info['driver_name']): ?>
                                        <div class="info-item">
                                            <span class="info-label">Driver</span>
                                            <span class="info-value"><?php echo $delivery_info['driver_name']; ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($delivery_info['driver_phone']): ?>
                                        <div class="info-item">
                                            <span class="info-label">Driver Phone</span>
                                            <span class="info-value"><?php echo $delivery_info['driver_phone']; ?></span>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <?php if ($delivery_info['delivery_address']): ?>
                                    <div class="mt-3">
                                        <span class="info-label">Delivery Address</span>
                                        <div style="background: #f8fafc; padding: 1rem; border-radius: 8px; margin-top: 0.5rem;">
                                            <?php echo nl2br(htmlspecialchars($delivery_info['delivery_address'])); ?>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </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.7.32/dist/sweetalert2.all.min.js"></script>
    
    <script>
    // Order data for JavaScript
    const orderData = {
        id: <?php echo $order_id; ?>,
        number: '<?php echo $order['order_number']; ?>',
        customer_name: '<?php echo $order['first_name'] . ' ' . $order['last_name']; ?>',
        phone: '<?php echo $order['phone']; ?>',
        status: '<?php echo $order['status']; ?>',
        balance: <?php echo $order['balance_amount']; ?>,
        total: <?php echo $order['total_amount']; ?>,
        paid: <?php echo $order['paid_amount']; ?>
    };
    
    // Payment methods data
    <?php 
    $payment_methods->data_seek(0);
    $methods = [];
    while ($method = $payment_methods->fetch_assoc()) {
        $methods[] = $method;
    }
    ?>
    const paymentMethods = <?php echo json_encode($methods); ?>;
    
    // Show loading overlay
    function showLoading() {
        document.getElementById('loadingOverlay').style.display = 'flex';
    }
    
    // Hide loading overlay
    function hideLoading() {
        document.getElementById('loadingOverlay').style.display = 'none';
    }
    
    // Add Payment Modal
    async function showAddPaymentModal() {
        const { value: formValues } = await Swal.fire({
            title: '<strong>Add Payment</strong>',
            html: `
                <div style="text-align: left; margin-bottom: 1rem;">
                    <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Amount (KES)</label>
                    <input id="swal-amount" class="swal2-input" type="number" step="0.01" max="${orderData.balance}" value="${orderData.balance}" placeholder="Enter amount" style="margin: 0; width: 100%;">
                    <small style="color: #64748b; font-size: 0.75rem;">Balance: KES ${orderData.balance.toLocaleString()}</small>
                </div>
                <div style="text-align: left; margin-bottom: 1rem;">
                    <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Payment Method</label>
                    <select id="swal-method" class="swal2-select" style="margin: 0; width: 100%;">
                        <option value="">Select Payment Method</option>
                        ${paymentMethods.map(method => 
                            `<option value="${method.method_id}">${method.method_name}</option>`
                        ).join('')}
                    </select>
                </div>
                <div style="text-align: left;">
                    <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Transaction Reference (Optional)</label>
                    <input id="swal-reference" class="swal2-input" type="text" placeholder="Enter reference number" style="margin: 0; width: 100%;">
                </div>
            `,
            focusConfirm: false,
            showCancelButton: true,
            confirmButtonText: '<i class="ph-plus"></i> Add Payment',
            cancelButtonText: 'Cancel',
            width: '500px',
            customClass: {
                confirmButton: 'btn btn-primary',
                cancelButton: 'btn btn-secondary'
            },
            preConfirm: () => {
                const amount = document.getElementById('swal-amount').value;
                const method = document.getElementById('swal-method').value;
                const reference = document.getElementById('swal-reference').value;
                
                if (!amount || amount <= 0) {
                    Swal.showValidationMessage('Please enter a valid amount');
                    return false;
                }
                
                if (!method) {
                    Swal.showValidationMessage('Please select a payment method');
                    return false;
                }
                
                if (parseFloat(amount) > orderData.balance) {
                    Swal.showValidationMessage('Amount cannot exceed balance');
                    return false;
                }
                
                return {
                    amount: parseFloat(amount),
                    payment_method_id: parseInt(method),
                    transaction_reference: reference
                };
            }
        });
        
        if (formValues) {
            await processPayment(formValues);
        }
    }
    
    // Process Payment
    async function processPayment(paymentData) {
        showLoading();
        
        try {
            const formData = new FormData();
            formData.append('action', 'add_payment');
            formData.append('amount', paymentData.amount);
            formData.append('payment_method_id', paymentData.payment_method_id);
            formData.append('transaction_reference', paymentData.transaction_reference);
            
            const response = await fetch(window.location.href, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            });
            
            const result = await response.json();
            
            hideLoading();
            
            if (result.success) {
                await Swal.fire({
                    icon: 'success',
                    title: 'Payment Added!',
                    text: result.message,
                    timer: 3000,
                    timerProgressBar: true,
                    showConfirmButton: false
                });
                
                // Update UI
                updatePaymentDisplay(result);
                
                // Refresh page to show updated data
                setTimeout(() => {
                    window.location.reload();
                }, 1500);
            } else {
                throw new Error(result.message);
            }
            
        } catch (error) {
            hideLoading();
            await Swal.fire({
                icon: 'error',
                title: 'Payment Failed',
                text: error.message || 'An error occurred while processing the payment'
            });
        }
    }
    
    // Update Status Modal
    async function showUpdateStatusModal() {
        const statusOptions = [
            { value: 'PENDING', text: 'Pending', disabled: orderData.status === 'PENDING' },
            { value: 'IN_PROGRESS', text: 'In Progress', disabled: orderData.status === 'IN_PROGRESS' },
            { value: 'READY', text: 'Ready', disabled: orderData.status === 'READY' },
            { value: 'DELIVERED', text: 'Delivered', disabled: orderData.status === 'DELIVERED' },
            { value: 'CANCELLED', text: 'Cancelled', disabled: orderData.status === 'CANCELLED' }
        ];
        
        const { value: formValues } = await Swal.fire({
            title: '<strong>Update Order Status</strong>',
            html: `
                <div style="text-align: left; margin-bottom: 1rem;">
                    <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Current Status</label>
                    <input class="swal2-input" type="text" value="${orderData.status}" readonly style="background: #f8fafc; margin: 0; width: 100%;">
                </div>
                <div style="text-align: left; margin-bottom: 1rem;">
                    <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">New Status</label>
                    <select id="swal-status" class="swal2-select" style="margin: 0; width: 100%;">
                        <option value="">Select New Status</option>
                        ${statusOptions.map(option => 
                            `<option value="${option.value}" ${option.disabled ? 'disabled' : ''}>${option.text}</option>`
                        ).join('')}
                    </select>
                </div>
                <div style="text-align: left; margin-bottom: 1rem;">
                    <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Reason/Notes (Optional)</label>
                    <textarea id="swal-notes" class="swal2-textarea" placeholder="Enter reason for status change" style="margin: 0; width: 100%;"></textarea>
                </div>
                <div style="text-align: left;">
                    <label style="display: flex; align-items: center; gap: 0.5rem;">
                        <input id="swal-update-items" type="checkbox" checked style="margin: 0;">
                        <span style="font-weight: 600;">Also update all order items status</span>
                    </label>
                    <small style="color: #64748b; font-size: 0.75rem;">When checked, all order items will be updated to match the new order status</small>
                </div>
            `,
            focusConfirm: false,
            showCancelButton: true,
            confirmButtonText: '<i class="ph-arrows-clockwise"></i> Update Status',
            cancelButtonText: 'Cancel',
            width: '500px',
            preConfirm: () => {
                const status = document.getElementById('swal-status').value;
                const notes = document.getElementById('swal-notes').value;
                const updateItems = document.getElementById('swal-update-items').checked;
                
                if (!status) {
                    Swal.showValidationMessage('Please select a new status');
                    return false;
                }
                
                return {
                    new_status: status,
                    status_notes: notes,
                    update_items: updateItems
                };
            }
        });
        
        if (formValues) {
            // Confirmation dialog
            const confirmed = await Swal.fire({
                icon: 'question',
                title: 'Confirm Status Change',
                text: `Are you sure you want to change the order status to ${formValues.new_status}?`,
                showCancelButton: true,
                confirmButtonText: 'Yes, Update Status',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#3b82f6'
            });
            
            if (confirmed.isConfirmed) {
                await updateOrderStatus(formValues);
            }
        }
    }
    
    // Update Order Status
    async function updateOrderStatus(statusData) {
        showLoading();
        
        try {
            const formData = new FormData();
            formData.append('action', 'update_status');
            formData.append('new_status', statusData.new_status);
            formData.append('status_notes', statusData.status_notes);
            if (statusData.update_items) {
                formData.append('update_items', '1');
            }
            
            const response = await fetch(window.location.href, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            });
            
            const result = await response.json();
            
            hideLoading();
            
            if (result.success) {
                await Swal.fire({
                    icon: 'success',
                    title: 'Status Updated!',
                    text: result.message,
                    timer: 3000,
                    timerProgressBar: true,
                    showConfirmButton: false
                });
                
                // Update UI
                updateStatusDisplay(result.new_status);
                
                // Refresh page to show updated data
                setTimeout(() => {
                    window.location.reload();
                }, 1500);
            } else {
                throw new Error(result.message);
            }
            
        } catch (error) {
            hideLoading();
            await Swal.fire({
                icon: 'error',
                title: 'Update Failed',
                text: error.message || 'An error occurred while updating the status'
            });
        }
    }
    
    // Send SMS Modal
    async function showSendSmsModal() {
        const messageTemplates = {
            'status_update': `Hi ${orderData.customer_name}, your order ${orderData.number} status has been updated to ${orderData.status}. Thank you for choosing Amina Laundry & Carpet Cleaning.`,
            'payment_reminder': `Hi ${orderData.customer_name}, this is a reminder that order ${orderData.number} has a pending balance of KES ${orderData.balance.toLocaleString()}. Please settle at your convenience.`,
            'pickup_reminder': `Hi ${orderData.customer_name}, your order ${orderData.number} is ready for pickup. Please collect it at your convenience. Amina Laundry & Carpet Cleaning.`,
            'delivery_notification': `Hi ${orderData.customer_name}, your order ${orderData.number} is out for delivery and will arrive shortly. Thank you for choosing Amina Laundry & Carpet Cleaning.`
        };
        
        const { value: formValues } = await Swal.fire({
            title: '<strong>Send SMS to Customer</strong>',
            html: `
                <div style="text-align: left; margin-bottom: 1rem;">
                    <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Customer</label>
                    <input class="swal2-input" type="text" value="${orderData.customer_name} (${orderData.phone})" readonly style="background: #f8fafc; margin: 0; width: 100%;">
                </div>
                <div style="text-align: left; margin-bottom: 1rem;">
                    <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Message Type</label>
                    <select id="swal-message-type" class="swal2-select" style="margin: 0; width: 100%;" onchange="updateSmsTemplate()">
                        <option value="">Select Message Type</option>
                        <option value="status_update">Order Status Update</option>
                        <option value="payment_reminder">Payment Reminder</option>
                        <option value="pickup_reminder">Pickup Reminder</option>
                        <option value="delivery_notification">Delivery Notification</option>
                        <option value="custom">Custom Message</option>
                    </select>
                </div>
                <div style="text-align: left;">
                    <label style="display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151;">Message</label>
                    <textarea id="swal-message" class="swal2-textarea" maxlength="160" placeholder="Enter your message here" style="margin: 0; width: 100%;" oninput="updateCharCount()"></textarea>
                    <small style="color: #64748b; font-size: 0.75rem;"><span id="char-count">0</span>/160 characters</small>
                </div>
            `,
            focusConfirm: false,
            showCancelButton: true,
            confirmButtonText: '<i class="ph-chat-text"></i> Send SMS',
            cancelButtonText: 'Cancel',
            width: '500px',
            didOpen: () => {
                window.updateSmsTemplate = function() {
                    const type = document.getElementById('swal-message-type').value;
                    const messageArea = document.getElementById('swal-message');
                    if (messageTemplates[type]) {
                        messageArea.value = messageTemplates[type];
                    } else {
                        messageArea.value = '';
                    }
                    updateCharCount();
                };
                
                window.updateCharCount = function() {
                    const message = document.getElementById('swal-message').value;
                    document.getElementById('char-count').textContent = message.length;
                };
            },
            preConfirm: () => {
                const messageType = document.getElementById('swal-message-type').value;
                const message = document.getElementById('swal-message').value.trim();
                
                if (!messageType) {
                    Swal.showValidationMessage('Please select a message type');
                    return false;
                }
                
                if (!message) {
                    Swal.showValidationMessage('Please enter a message');
                    return false;
                }
                
                if (message.length > 160) {
                    Swal.showValidationMessage('Message cannot exceed 160 characters');
                    return false;
                }
                
                return {
                    message_type: messageType,
                    message: message,
                    customer_phone: orderData.phone
                };
            }
        });
        
        if (formValues) {
            await sendSmsMessage(formValues);
        }
    }
    
    // Send SMS Message
    async function sendSmsMessage(smsData) {
        showLoading();
        
        try {
            const formData = new FormData();
            formData.append('action', 'send_sms');
            formData.append('message_type', smsData.message_type);
            formData.append('message', smsData.message);
            formData.append('customer_phone', smsData.customer_phone);
            
            const response = await fetch(window.location.href, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            });
            
            const result = await response.json();
            
            hideLoading();
            
            if (result.success) {
                await Swal.fire({
                    icon: 'success',
                    title: 'SMS Sent!',
                    text: result.message,
                    timer: 3000,
                    timerProgressBar: true,
                    showConfirmButton: false
                });
            } else {
                throw new Error(result.message);
            }
            
        } catch (error) {
            hideLoading();
            await Swal.fire({
                icon: 'error',
                title: 'SMS Failed',
                text: error.message || 'An error occurred while sending the SMS'
            });
        }
    }
    
    // Update Payment Display
    function updatePaymentDisplay(paymentData) {
        // Update balance display
        const balanceDisplay = document.getElementById('balanceAmountDisplay');
        if (balanceDisplay) {
            balanceDisplay.textContent = `KES ${paymentData.new_balance.toLocaleString()}`;
            balanceDisplay.style.color = paymentData.new_balance > 0 ? '#dc2626' : '#059669';
        }
        
        // Update paid amount display
        const paidDisplay = document.getElementById('paidAmountDisplay');
        if (paidDisplay) {
            paidDisplay.textContent = `KES ${paymentData.new_paid.toLocaleString()}`;
        }
        
        // Update payment status badge
        const paymentBadge = document.getElementById('paymentStatusBadge');
        if (paymentBadge && paymentData.payment_status === 'PAID') {
            paymentBadge.style.display = 'none';
        }
        
        // Update order data
        orderData.balance = paymentData.new_balance;
        orderData.paid = paymentData.new_paid;
    }
    
    // Update Status Display
    function updateStatusDisplay(newStatus) {
        const statusBadge = document.getElementById('orderStatusBadge');
        if (statusBadge) {
            statusBadge.textContent = newStatus;
            statusBadge.className = `status-badge status-${newStatus.toLowerCase()}`;
        }
        
        orderData.status = newStatus;
    }
    
    // Generate Receipt
    function generateReceipt() {
        const Toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 2000,
            timerProgressBar: true
        });
        
        Toast.fire({
            icon: 'info',
            title: 'Opening receipt...'
        });
        
        window.open(`generate_receipt.php?order_id=${orderData.id}`, '_blank');
    }
    
    // Generate Order Ticket
    function generateTicket() {
        const Toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 2000,
            timerProgressBar: true
        });
        
        Toast.fire({
            icon: 'info',
            title: 'Opening order ticket...'
        });
        
        window.open(`generate_ticket.php?order_id=${orderData.id}`, '_blank');
    }
    
    // Print Order with confirmation
    async function printOrder() {
        const result = await Swal.fire({
            title: 'Print Order',
            text: 'Are you ready to print this order?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: '<i class="ph-printer"></i> Yes, Print',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#3b82f6'
        });
        
        if (result.isConfirmed) {
            window.print();
        }
    }
    
    // Keyboard shortcuts with SweetAlert notifications
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + P for print
        if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
            e.preventDefault();
            printOrder();
        }
        
        // Ctrl/Cmd + S for status update
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            showUpdateStatusModal();
        }
        
        // Ctrl/Cmd + M for SMS
        if ((e.ctrlKey || e.metaKey) && e.key === 'm') {
            e.preventDefault();
            showSendSmsModal();
        }
        
        // Ctrl/Cmd + R for receipt
        if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
            e.preventDefault();
            generateReceipt();
        }
        
        // Ctrl/Cmd + T for ticket
        if ((e.ctrlKey || e.metaKey) && e.key === 't') {
            e.preventDefault();
            generateTicket();
        }
    });
    
    // Show keyboard shortcuts help
    function showKeyboardShortcuts() {
        Swal.fire({
            title: '<strong>Keyboard Shortcuts</strong>',
            html: `
                <div style="text-align: left; font-size: 0.9rem; line-height: 1.6;">
                    <div style="margin-bottom: 0.5rem;"><strong>Ctrl + P:</strong> Print Order</div>
                    <div style="margin-bottom: 0.5rem;"><strong>Ctrl + S:</strong> Update Status</div>
                    <div style="margin-bottom: 0.5rem;"><strong>Ctrl + M:</strong> Send SMS</div>
                    <div style="margin-bottom: 0.5rem;"><strong>Ctrl + R:</strong> Generate Receipt</div>
                    <div style="margin-bottom: 0.5rem;"><strong>Ctrl + T:</strong> Generate Ticket</div>
                    <div><strong>Escape:</strong> Close dialogs</div>
                </div>
            `,
            icon: 'info',
            confirmButtonText: 'Got it!',
            width: '400px'
        });
    }
    
    // Toast notification helper
    function showToast(icon, message, position = 'top-end') {
        const Toast = Swal.mixin({
            toast: true,
            position: position,
            showConfirmButton: false,
            timer: 3000,
            timerProgressBar: true,
            didOpen: (toast) => {
                toast.addEventListener('mouseenter', Swal.stopTimer);
                toast.addEventListener('mouseleave', Swal.resumeTimer);
            }
        });
        
        Toast.fire({
            icon: icon,
            title: message
        });
    }
    
    // Network status handling
    window.addEventListener('online', function() {
        showToast('success', 'Connection restored');
    });
    
    window.addEventListener('offline', function() {
        showToast('warning', 'No internet connection');
    });
    
    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        // Show welcome message for first-time users
        if (localStorage.getItem('order_view_help_shown') !== 'true') {
            setTimeout(() => {
                Swal.fire({
                    title: '<strong>Order Management</strong>',
                    html: `
                        <div style="text-align: left;">
                            <p>Welcome to the order management interface! Here you can:</p>
                            <ul style="margin: 1rem 0; padding-left: 1.5rem; text-align: left;">
                                <li>Add payments and track balances</li>
                                <li>Update order status and items</li>
                                <li>Generate receipts and tickets</li>
                                <li>Send SMS notifications to customers</li>
                            </ul>
                            <p>Use keyboard shortcuts for quick actions. Press <strong>F1</strong> anytime for help.</p>
                        </div>
                    `,
                    icon: 'info',
                    confirmButtonText: "Let's get started!",
                    footer: '<a href="#" onclick="showKeyboardShortcuts()" style="color: #3b82f6;">View keyboard shortcuts</a>',
                    width: '500px'
                });
                localStorage.setItem('order_view_help_shown', 'true');
            }, 2000);
        }
        
        // F1 for help
        document.addEventListener('keydown', function(e) {
            if (e.key === 'F1') {
                e.preventDefault();
                showKeyboardShortcuts();
            }
        });
        
        // Show success message if payment was just added
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('payment_added')) {
            showToast('success', 'Payment added successfully!');
            // Clean URL
            window.history.replaceState({}, document.title, window.location.pathname + '?id=' + orderData.id);
        }
    });
    
    // Auto-refresh order status every 30 seconds (optional)
    let autoRefreshEnabled = false;
    
    function toggleAutoRefresh() {
        autoRefreshEnabled = !autoRefreshEnabled;
        
        if (autoRefreshEnabled) {
            showToast('info', 'Auto-refresh enabled');
            
            const interval = setInterval(async function() {
                if (!autoRefreshEnabled) {
                    clearInterval(interval);
                    return;
                }
                
                try {
                    // Simple status check - you can implement this endpoint
                    const response = await fetch(`check_order_status.php?id=${orderData.id}`);
                    if (response.ok) {
                        const data = await response.json();
                        if (data.status !== orderData.status) {
                            showToast('info', `Order status changed to ${data.status}`);
                            updateStatusDisplay(data.status);
                        }
                    }
                } catch (error) {
                    console.log('Auto-refresh failed:', error);
                }
            }, 30000);
        } else {
            showToast('info', 'Auto-refresh disabled');
        }
    }
    
    // Error handling helper
    function handleApiError(error) {
        console.error('API Error:', error);
        
        let message = 'An unexpected error occurred';
        if (error.message) {
            message = error.message;
        }
        
        Swal.fire({
            icon: 'error',
            title: 'Oops...',
            text: message,
            footer: 'Please try again or contact support if the problem persists',
            confirmButtonColor: '#3b82f6'
        });
    }
    
    // Confirmation helper for destructive actions
    async function confirmDestructiveAction(title, text, confirmText = 'Yes, proceed') {
        return await Swal.fire({
            title: title,
            text: text,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc2626',
            cancelButtonColor: '#64748b',
            confirmButtonText: confirmText,
            cancelButtonText: 'Cancel'
        });
    }
    
    // Format currency helper
    function formatCurrency(amount) {
        return new Intl.NumberFormat('en-KE', {
            style: 'currency',
            currency: 'KES',
            minimumFractionDigits: 2
        }).format(amount);
    }
    
    // Success celebration helper
    function celebrateSuccess(title, message) {
        Swal.fire({
            title: title,
            text: message,
            icon: 'success',
            showClass: {
                popup: 'animate__animated animate__bounceIn'
            },
            hideClass: {
                popup: 'animate__animated animate__bounceOut'
            },
            timer: 3000,
            timerProgressBar: true,
            confirmButtonColor: '#059669'
        });
    }
    
    // Initialize tooltips for action buttons
    document.querySelectorAll('.action-btn').forEach(btn => {
        btn.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-2px)';
        });
        
        btn.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
        });
    });
    
    // Add loading states to buttons during operations
    function setButtonLoading(buttonSelector, isLoading) {
        const button = document.querySelector(buttonSelector);
        if (!button) return;
        
        if (isLoading) {
            button.disabled = true;
            button.innerHTML = '<i class="ph-spinner ph-spin"></i> Processing...';
        } else {
            button.disabled = false;
            // Reset original content - you might want to store this
        }
    }
    
    // Context menu for additional options (right-click)
    document.addEventListener('contextmenu', function(e) {
        if (e.target.closest('.order-header')) {
            e.preventDefault();
            
            Swal.fire({
                title: 'Quick Actions',
                showCancelButton: true,
                showDenyButton: true,
                showConfirmButton: true,
                confirmButtonText: 'Update Status',
                denyButtonText: 'Send SMS',
                cancelButtonText: 'Generate Receipt'
            }).then((result) => {
                if (result.isConfirmed) {
                    showUpdateStatusModal();
                } else if (result.isDenied) {
                    showSendSmsModal();
                } else if (result.dismiss === Swal.DismissReason.cancel) {
                    generateReceipt();
                }
            });
        }
    });
    </script>
    
    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>