<?php
// Require authentication
require_once 'includes/auth.php';
requireAuth();

// Get order ID from URL
$orderId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($orderId <= 0) {
    header('Location: orders.php');
    exit;
}

// Fetch order data
require_once '../database/config.php';
$db = Database::getInstance()->getConnection();

try {
    // Get order details
    $stmt = $db->prepare("
        SELECT * FROM orders WHERE id = ?
    ");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) {
        header('Location: orders.php');
        exit;
    }
    
    // Get order items with product images
    $stmt = $db->prepare("
        SELECT 
            oi.*,
            (SELECT image_path FROM product_images WHERE product_id = oi.product_id ORDER BY is_featured DESC, sort_order ASC LIMIT 1) as product_image
        FROM order_items oi
        WHERE oi.order_id = ?
    ");
    $stmt->execute([$orderId]);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get customer stats (total orders and spend)
    $stmt = $db->prepare("
        SELECT COUNT(*) as total_orders, SUM(total_amount) as total_spent 
        FROM orders 
        WHERE customer_id = ?
    ");
    $stmt->execute([$order['customer_id']]);
    $customerStats = $stmt->fetch(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    error_log('Order detail error: ' . $e->getMessage());
    header('Location: orders.php');
    exit;
}

// Helper functions for badges and icons
function getPaymentStatusClass($status) {
    switch ($status) {
        case 'paid': return 'bg-success-subtle text-success';
        case 'pending': return 'bg-warning-subtle text-warning';
        case 'refunded': return 'bg-danger-subtle text-danger';
        case 'partially_refunded': return 'bg-info-subtle text-info';
        case 'voided': return 'bg-secondary-subtle text-secondary';
        default: return 'bg-secondary-subtle text-secondary';
    }
}

function getPaymentStatusIcon($status) {
    switch ($status) {
        case 'paid': return 'fas fa-check-circle';
        case 'pending': return 'fas fa-clock';
        case 'refunded': return 'fas fa-undo';
        case 'partially_refunded': return 'fas fa-adjust';
        case 'voided': return 'fas fa-ban';
        default: return 'fas fa-circle';
    }
}

function getFulfillmentStatusClass($status) {
    switch ($status) {
        case 'fulfilled': return 'bg-success-subtle text-success';
        case 'unfulfilled': return 'bg-warning-subtle text-warning';
        case 'partial': return 'bg-info-subtle text-info';
        case 'scheduled': return 'bg-primary-subtle text-primary';
        case 'on_hold': return 'bg-danger-subtle text-danger';
        default: return 'bg-secondary-subtle text-secondary';
    }
}

function getFulfillmentStatusIcon($status) {
    switch ($status) {
        case 'fulfilled': return 'fas fa-check-circle';
        case 'unfulfilled': return 'fas fa-circle';
        case 'partial': return 'fas fa-box-open';
        case 'scheduled': return 'fas fa-calendar-alt';
        case 'on_hold': return 'fas fa-times-circle';
        default: return 'fas fa-circle';
    }
}
?>
<?php include 'header.php'; ?>

<div class="page-wrapper">
    <!-- Page Content-->
    <div class="page-content">
        <div class="container-fluid">
            <!-- Order Header -->
            <div class="row">
                <div class="col-12">
                    <div class="page-title-box d-flex justify-content-between align-items-center">
                        <div>
                            <h4 class="page-title mb-1">Order <?php echo htmlspecialchars($order['order_number']); ?></h4>
                            <p class="text-muted mb-0">
                                <span class="badge <?php echo getPaymentStatusClass($order['payment_status']); ?> me-2">
                                    <i class="<?php echo getPaymentStatusIcon($order['payment_status']); ?> me-1"></i>
                                    <?php echo ucfirst(str_replace('_', ' ', $order['payment_status'])); ?>
                                </span>
                                <span class="badge <?php echo getFulfillmentStatusClass($order['fulfillment_status']); ?> me-2">
                                    <i class="<?php echo getFulfillmentStatusIcon($order['fulfillment_status']); ?> me-1"></i>
                                    <?php echo ucfirst(str_replace('_', ' ', $order['fulfillment_status'])); ?>
                                </span>
                                <span class="text-muted"><?php echo date('F j, Y \a\t g:i A', strtotime($order['created_at'])); ?> from Online Store</span>
                            </p>
                        </div>
                        <div>
                            <div class="dropdown d-inline-block me-2">
                                <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                    More actions
                                </button>
                                <ul class="dropdown-menu dropdown-menu-end">
                                    <li><a class="dropdown-item" href="#" id="printOrderAction"><i class="fas fa-print me-2"></i>Print order</a></li>
                                    <li><a class="dropdown-item" href="#" id="printPackingSlipAction"><i class="fas fa-file-invoice me-2"></i>Print packing slip</a></li>
                                    <li><a class="dropdown-item" href="#"><i class="fas fa-envelope me-2"></i>Email invoice</a></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item" href="#"><i class="fas fa-archive me-2"></i>Archive order</a></li>
                                    <li><a class="dropdown-item text-danger" href="#" id="cancelOrderAction"><i class="fas fa-times-circle me-2"></i>Cancel order</a></li>
                                </ul>
                            </div>
                             <!-- TOP HEADER ACTIONS (Synced with Card Header) -->
                             <!-- STATE: UNFULFILLED -->
                             <?php if ($order['fulfillment_status'] === 'unfulfilled' && $order['delivery_status'] !== 'cancelled'): ?>
                                <button type="button" class="btn btn-warning btn-sm" id="holdOrderBtnTop">
                                    <i class="fas fa-pause me-1"></i> Hold
                                </button>
                                <button type="button" class="btn btn-danger btn-sm" id="refundOrderBtnTop">
                                    <i class="fas fa-undo me-1"></i> Refund
                                </button>
                                <button type="button" class="btn btn-primary btn-sm" id="headerFulfillBtn">
                                     <i class="fas fa-box-open me-1"></i> Fulfill Order
                                </button>
                             
                             <!-- STATE: FULFILLED (But not In Transit) -->
                             <?php elseif ($order['fulfillment_status'] === 'fulfilled' && $order['delivery_status'] === 'processing'): ?>
                                <button type="button" class="btn btn-outline-dark btn-sm" id="headerPrintSlipBtn">
                                    <i class="fas fa-print me-1"></i> Print Packing Slip
                                </button>
                                <button type="button" class="btn btn-info btn-sm text-white" id="headerAddTrackingBtn">
                                    <i class="fas fa-truck me-1"></i> Add Tracking
                                </button>

                             <!-- STATE: IN TRANSIT / DELIVERED -->
                             <?php elseif ($order['delivery_status'] === 'in_transit' || $order['delivery_status'] === 'delivered'): ?>
                                <button type="button" class="btn btn-outline-dark btn-sm" onclick="window.open('print-label.php?id=<?php echo $orderId; ?>', '_blank', 'width=400,height=600')">
                                    <i class="fas fa-print me-1"></i> Print Label
                                </button>
                                 <button type="button" class="btn btn-outline-secondary btn-sm" id="headerEditTrackingBtn" data-tracking="<?php echo htmlspecialchars($order['tracking_number'] ?? ''); ?>">
                                    <i class="fas fa-pen me-1"></i> Edit Tracking
                                </button>
                             <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <!-- Left Column -->
                <div class="col-lg-8">
                    <!-- Items -->
                    <div class="card">
                        <div class="card-header bg-light">
                            <div class="row align-items-center mb-4">
                    <div class="col">
                        <h5 class="card-title fw-semibold">Order Items (<?php echo count($items); ?>)</h5>
                    </div>
                    <div class="col-auto">
                        <span class="badge bg-<?php echo ($order['fulfillment_status'] === 'fulfilled') ? 'success' : 'warning'; ?>-subtle text-<?php echo ($order['fulfillment_status'] === 'fulfilled') ? 'success' : 'warning'; ?> px-2 py-1 fs-6">
                            <?php echo ucfirst($order['fulfillment_status']); ?>
                        </span>
                    </div>
                </div>

                <!-- Product List -->
                <!-- Header Actions -->
                <div class="d-flex text-end pt-3 gap-2 border-top">
                     <!-- STATE: UNFULFILLED -->
                     <?php if ($order['fulfillment_status'] === 'unfulfilled' && $order['delivery_status'] !== 'cancelled'): ?>
                        <button type="button" class="btn btn-warning btn-sm" id="holdOrderBtn">
                            <i class="fas fa-pause me-1"></i> Hold
                        </button>
                        <button type="button" class="btn btn-danger btn-sm" id="refundOrderBtn">
                            <i class="fas fa-undo me-1"></i> Refund
                        </button>
                        <button type="button" class="btn btn-primary btn-sm" id="simpleFulfillBtn">
                             <i class="fas fa-box-open me-1"></i> Fulfill Order
                        </button>
                     
                     <!-- STATE: FULFILLED -->
                     <?php elseif ($order['fulfillment_status'] === 'fulfilled' && $order['delivery_status'] === 'processing'): ?>
                        <button type="button" class="btn btn-outline-dark btn-sm" id="printPackingSlipAction">
                            <i class="fas fa-print me-1"></i> Print Packing Slip
                        </button>
                        <button type="button" class="btn btn-info btn-sm text-white" id="addTrackingBtn">
                            <i class="fas fa-truck me-1"></i> Add Tracking
                        </button>

                     <!-- STATE: IN TRANSIT / DELIVERED -->
                     <?php elseif ($order['delivery_status'] === 'in_transit' || $order['delivery_status'] === 'delivered'): ?>
                        <button type="button" class="btn btn-outline-dark btn-sm" id="printLabelBtn" onclick="window.open('print-label.php?id=<?php echo $orderId; ?>', '_blank', 'width=400,height=600')">
                            <i class="fas fa-print me-1"></i> Print Label
                        </button>
                         <button type="button" class="btn btn-outline-secondary btn-sm" id="editTrackingBtn" data-tracking="<?php echo htmlspecialchars($order['tracking_number'] ?? ''); ?>">
                            <i class="fas fa-pen me-1"></i> Edit Tracking
                        </button>
                     <?php endif; ?>
                </div>
                            </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-borderless mb-0">
                                    <tbody>
                                        <?php foreach ($items as $item): ?>
                                        <tr class="border-bottom">
                                            <td style="width: 60px;">
                                                <img src="<?php echo htmlspecialchars($item['product_image'] ?? 'assets/images/products/01.png'); ?>" 
                                                     alt="" height="50" class="rounded">
                                            </td>
                                            <td>
                                                <h6 class="mb-0"><?php echo htmlspecialchars($item['product_title']); ?></h6>
                                                <?php if ($item['sku']): ?>
                                                    <small class="text-muted">SKU: <?php echo htmlspecialchars($item['sku']); ?></small><br>
                                                <?php endif; ?>
                                                <?php if ($item['variant_title']): ?>
                                                    <small class="text-muted">Variant: <?php echo htmlspecialchars($item['variant_title']); ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <p class="mb-0 fw-semibold">$<?php echo number_format($item['unit_price'], 2); ?> × <?php echo $item['quantity']; ?></p>
                                            </td>
                                            <td class="text-end">
                                                <p class="mb-0 fw-bold">$<?php echo number_format($item['total_price'], 2); ?></p>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                        </div>
                    </div>

                    <!-- Payment Status -->
                    <div class="card">
                        <div class="card-header bg-light">
                            <div class="d-flex justify-content-between align-items-center">
                                <h5 class="card-title mb-0">Payment</h5>
                                <span class="badge <?php echo getPaymentStatusClass($order['payment_status']); ?>">
                                    <i class="<?php echo getPaymentStatusIcon($order['payment_status']); ?> me-1"></i>
                                    <?php echo ucfirst(str_replace('_', ' ', $order['payment_status'])); ?>
                                </span>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="d-flex align-items-center mb-3">
                                <div class="flex-shrink-0">
                                    <i class="fas fa-credit-card fs-2 text-primary"></i>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <p class="mb-0 fw-semibold">
                                        <?php echo $order['payment_method'] ? htmlspecialchars($order['payment_method']) : 'Payment Method'; ?>
                                    </p>
                                    <small class="text-muted">
                                        $<?php echo number_format($order['total_amount'], 2); ?> 
                                        <?php echo $order['payment_status'] === 'paid' ? 'paid' : 'due'; ?> 
                                        on <?php echo date('F j, Y', strtotime($order['created_at'])); ?>
                                    </small>
                                </div>
                            </div>
                            <?php if ($order['payment_transaction_id']): ?>
                            <div class="bg-light p-3 rounded">
                                <div class="d-flex justify-content-between mb-1">
                                    <span class="text-muted">Transaction ID:</span>
                                    <span class="fw-semibold"><?php echo htmlspecialchars($order['payment_transaction_id']); ?></span>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Fulfillment Status -->
                    <div class="card">
                        <div class="card-header bg-light">
                            <div class="d-flex justify-content-between align-items-center">
                                <h5 class="card-title mb-0">Fulfillment</h5>
                                <span class="badge <?php echo getFulfillmentStatusClass($order['fulfillment_status']); ?>">
                                    <i class="<?php echo getFulfillmentStatusIcon($order['fulfillment_status']); ?> me-1"></i>
                                    <?php echo ucfirst(str_replace('_', ' ', $order['fulfillment_status'])); ?>
                                </span>
                            </div>
                        </div>
                        <div class="card-body">
                            <?php if ($order['fulfillment_status'] === 'unfulfilled'): ?>
                            <div class="alert alert-warning mb-3" role="alert">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                <strong>Action required:</strong> This order needs to be fulfilled.
                            </div>
                            <?php endif; ?>
                            
                            <!-- Timeline Progress -->
                            <div class="position-relative m-4">
                                <div class="progress" role="progressbar" style="height: 2px;">
                                    <?php
                                    $progress = 0;
                                    if ($order['fulfillment_status'] === 'fulfilled') $progress = 100;
                                    elseif ($order['fulfillment_status'] === 'partial') $progress = 50;
                                    elseif ($order['fulfillment_status'] === 'unfulfilled') $progress = 0;
                                    
                                    // Override based on delivery status if available
                                    if ($order['delivery_status'] === 'delivered') $progress = 100;
                                    elseif ($order['delivery_status'] === 'in_transit') $progress = 66;
                                    elseif ($order['delivery_status'] === 'processing') $progress = 33;
                                    ?>
                                    <div class="progress-bar bg-primary" style="width: <?php echo $progress; ?>%"></div>
                                </div>
                                <div class="position-absolute top-0 start-0 translate-middle bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                    <i class="fas fa-check"></i>
                                </div>
                                <div class="position-absolute top-0 start-50 translate-middle <?php echo $progress >= 50 ? 'bg-primary text-white' : 'bg-light text-muted'; ?> rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                    <i class="fas fa-truck"></i>
                                </div>
                                <div class="position-absolute top-0 start-100 translate-middle <?php echo $progress >= 100 ? 'bg-primary text-white' : 'bg-light text-muted'; ?> rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                    <i class="fas fa-box-open"></i>
                                </div>
                            </div>
                            <div class="row mt-4">
                                <div class="col-4 text-start">
                                    <h6 class="mb-1">Order Placed</h6>
                                    <p class="mb-0 text-muted small"><?php echo date('M d, g:i A', strtotime($order['created_at'])); ?></p>
                                </div>
                                <div class="col-4 text-center">
                                    <h6 class="mb-1">In Transit</h6>
                                    <p class="mb-0 text-muted small">
                                        <?php echo ($order['delivery_status'] === 'in_transit' || $order['delivery_status'] === 'delivered') ? 'Processing' : 'Pending'; ?>
                                    </p>
                                </div>
                                <div class="col-4 text-end">
                                    <h6 class="mb-1">Delivered</h6>
                                    <p class="mb-0 text-muted small">
                                        <?php echo $order['delivery_status'] === 'delivered' ? 'Delivered' : 'Pending'; ?>
                                    </p>
                                </div>
                            </div>
                            
                            <?php if ($order['tracking_number']): ?>
                            <div class="mt-3 p-3 bg-light rounded">
                                <p class="mb-1 fw-semibold">Tracking Number</p>
                                <p class="mb-0 font-monospace"><?php echo htmlspecialchars($order['tracking_number']); ?></p>
                            </div>
                            <?php else: ?>
                            <div class="mt-3">
                                <button class="btn btn-outline-primary btn-sm" id="addTrackingBtn">
                                    <i class="fas fa-plus me-1"></i>Add tracking number
                                </button>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Timeline -->
                    <div class="card">
                        <div class="card-header bg-light">
                            <h5 class="card-title mb-0">Timeline</h5>
                        </div>
                        <div class="card-body">
                            <div class="border-start border-3 border-primary ps-3">
                                <div class="mb-4">
                                    <div class="d-flex align-items-center mb-2">
                                        <div class="bg-primary rounded-circle me-2" style="width: 10px; height: 10px; margin-left: -19px;"></div>
                                        <h6 class="mb-0">Order created</h6>
                                    </div>
                                    <p class="text-muted mb-1"><?php echo date('F j, Y \a\t g:i A', strtotime($order['created_at'])); ?></p>
                                    <p class="mb-0">Order was created by <?php echo htmlspecialchars($order['customer_first_name']); ?></p>
                                </div>
                                <?php if ($order['payment_status'] === 'paid'): ?>
                                <div class="mb-4">
                                    <div class="d-flex align-items-center mb-2">
                                        <div class="bg-success rounded-circle me-2" style="width: 10px; height: 10px; margin-left: -19px;"></div>
                                        <h6 class="mb-0">Payment received</h6>
                                    </div>
                                    <p class="text-muted mb-1"><?php echo date('F j, Y \a\t g:i A', strtotime($order['created_at'])); ?></p>
                                    <p class="mb-0">$<?php echo number_format($order['total_amount'], 2); ?> paid</p>
                                </div>
                                <?php endif; ?>

                                <!-- DYNAMIC SYSTEM LOGS -->
                                <?php
                                if (!empty($order['notes'])) {
                                    $logs = explode("\n", $order['notes']);
                                    foreach ($logs as $log) {
                                        $log = trim($log);
                                        if (empty($log)) continue;

                                        // Try to parse timestamp: [Jan 01, 2024 10:00 AM] Message
                                        if (preg_match('/^\[(.*?)\] (.*)$/', $log, $matches)) {
                                            $timestamp = $matches[1];
                                            $message = $matches[2];
                                            
                                            // Determine Icon and Color based on content
                                            $icon = 'circle'; 
                                            $color = 'secondary';
                                            
                                            if (stripos($message, 'fulfilled') !== false) { $icon = 'box'; $color = 'info'; }
                                            elseif (stripos($message, 'In Transit') !== false) { $icon = 'route'; $color = 'primary'; } // Specific check for Status Change
                                            elseif (stripos($message, 'tracking') !== false) { $icon = 'truck'; $color = 'primary'; }
                                            elseif (stripos($message, 'hold') !== false) { $icon = 'pause'; $color = 'warning'; }
                                            elseif (stripos($message, 'refunded') !== false) { $icon = 'undo'; $color = 'danger'; }
                                            elseif (stripos($message, 'cancelled') !== false) { $icon = 'times-circle'; $color = 'danger'; }
                                            elseif (stripos($message, 'note') !== false) { $icon = 'comment'; $color = 'secondary'; }

                                            echo '
                                            <div class="mb-4">
                                                <div class="d-flex align-items-center mb-2">
                                                    <div class="bg-'.$color.' rounded-circle me-2 d-flex align-items-center justify-content-center text-white" style="width: 20px; height: 20px; margin-left: -24px; font-size: 10px;">
                                                        <i class="fas fa-'.$icon.'"></i>
                                                    </div>
                                                    <h6 class="mb-0">'.htmlspecialchars($message).'</h6>
                                                </div>
                                                <p class="text-muted mb-1">'.$timestamp.'</p>
                                            </div>';
                                        }
                                    }
                                }
                                ?>
                            </div>
                            
                            <!-- Add Note Section -->
                            <div class="mt-4 pt-3 border-top">
                                <button class="btn btn-outline-secondary btn-sm" id="addNoteBtn">
                                    <i class="fas fa-comment me-1"></i>Add note
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Right Sidebar -->
                <div class="col-lg-4">
                    <!-- Customer Card -->
                    <div class="card">
                        <div class="card-header bg-light">
                            <h5 class="card-title mb-0">Customer</h5>
                        </div>
                        <div class="card-body">
                            <div class="d-flex align-items-center mb-3">
                                <img src="assets/images/users/avatar-1.jpg" alt="" class="rounded-circle me-3" width="48" height="48">
                                <div>
                                    <h6 class="mb-0"><?php echo htmlspecialchars($order['customer_first_name'] . ' ' . $order['customer_last_name']); ?></h6>
                                    <small class="text-muted">
                                        <?php echo $customerStats['total_orders']; ?> orders • $<?php echo number_format($customerStats['total_spent'], 2); ?>
                                    </small>
                                </div>
                            </div>
                            <div class="mb-3">
                                <p class="mb-1 text-muted small">CONTACT INFORMATION</p>
                                <p class="mb-1"><i class="fas fa-envelope text-muted me-2"></i><?php echo htmlspecialchars($order['customer_email']); ?></p>
                                <?php if ($order['customer_phone']): ?>
                                <p class="mb-0"><i class="fas fa-phone text-muted me-2"></i><?php echo htmlspecialchars($order['customer_phone']); ?></p>
                                <?php endif; ?>
                            </div>
                            <div class="d-grid gap-2">
                                <button class="btn btn-outline-primary btn-sm">
                                    <i class="fas fa-envelope me-1"></i>Email customer
                                </button>
                                <a href="customers.php" class="btn btn-outline-secondary btn-sm">
                                    View customer details
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Shipping Address -->
                    <div class="card">
                        <div class="card-header bg-light d-flex justify-content-between align-items-center">
                            <h5 class="card-title mb-0">Shipping address</h5>
                            <a href="#" class="text-primary small"><i class="fas fa-edit me-1"></i>Edit</a>
                        </div>
                        <div class="card-body">
                            <p class="mb-1 fw-semibold"><?php echo htmlspecialchars($order['customer_first_name'] . ' ' . $order['customer_last_name']); ?></p>
                            <p class="mb-1"><?php echo htmlspecialchars($order['shipping_address_line1']); ?></p>
                            <?php if ($order['shipping_address_line2']): ?>
                                <p class="mb-1"><?php echo htmlspecialchars($order['shipping_address_line2']); ?></p>
                            <?php endif; ?>
                            <p class="mb-1">
                                <?php echo htmlspecialchars($order['shipping_city']); ?>, 
                                <?php echo htmlspecialchars($order['shipping_state']); ?> 
                                <?php echo htmlspecialchars($order['shipping_postal_code']); ?>
                            </p>
                            <p class="mb-3"><?php echo htmlspecialchars($order['shipping_country']); ?></p>
                            <a href="#" class="text-primary small">
                                <i class="fas fa-map-marker-alt me-1"></i>View map
                            </a>
                        </div>
                    </div>

                    <!-- Billing Address -->
                    <div class="card">
                        <div class="card-header bg-light d-flex justify-content-between align-items-center">
                            <h5 class="card-title mb-0">Billing address</h5>
                            <a href="#" class="text-primary small"><i class="fas fa-edit me-1"></i>Edit</a>
                        </div>
                        <div class="card-body">
                            <?php if ($order['billing_address_line1']): ?>
                                <p class="mb-1 fw-semibold"><?php echo htmlspecialchars($order['customer_first_name'] . ' ' . $order['customer_last_name']); ?></p>
                                <p class="mb-1"><?php echo htmlspecialchars($order['billing_address_line1']); ?></p>
                                <?php if ($order['billing_address_line2']): ?>
                                    <p class="mb-1"><?php echo htmlspecialchars($order['billing_address_line2']); ?></p>
                                <?php endif; ?>
                                <p class="mb-1">
                                    <?php echo htmlspecialchars($order['billing_city']); ?>, 
                                    <?php echo htmlspecialchars($order['billing_state']); ?> 
                                    <?php echo htmlspecialchars($order['billing_postal_code']); ?>
                                </p>
                                <p class="mb-0"><?php echo htmlspecialchars($order['billing_country']); ?></p>
                            <?php else: ?>
                                <p class="mb-0 text-muted">Same as shipping address</p>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Order Summary -->
                    <div class="card">
                        <div class="card-header bg-light">
                            <h5 class="card-title mb-0">Summary</h5>
                        </div>
                        <div class="card-body">
                            <div class="d-flex justify-content-between mb-2">
                                <span class="text-muted">Subtotal</span>
                                <span class="fw-semibold">$<?php echo number_format($order['subtotal'], 2); ?></span>
                            </div>
                            <div class="d-flex justify-content-between mb-2">
                                <span class="text-muted">Discount</span>
                                <span class="text-success fw-semibold">-$<?php echo number_format($order['discount_amount'], 2); ?></span>
                            </div>
                            <div class="d-flex justify-content-between mb-2">
                                <span class="text-muted">Shipping</span>
                                <span class="fw-semibold">$<?php echo number_format($order['shipping_cost'], 2); ?></span>
                            </div>
                            <div class="d-flex justify-content-between mb-3">
                                <span class="text-muted">Tax</span>
                                <span class="fw-semibold">$<?php echo number_format($order['tax_amount'], 2); ?></span>
                            </div>
                            <hr>
                            <div class="d-flex justify-content-between mb-2">
                                <h5 class="mb-0">Total</h5>
                                <h5 class="mb-0">$<?php echo number_format($order['total_amount'], 2); ?></h5>
                            </div>
                            <div class="d-flex justify-content-between">
                                <span class="text-muted">Paid by customer</span>
                                <span class="text-success fw-bold">$<?php echo $order['payment_status'] === 'paid' ? number_format($order['total_amount'], 2) : '0.00'; ?></span>
                            </div>
                        </div>
                    </div>

                    <!-- Tags -->
                    <div class="card">
                        <div class="card-header bg-light">
                            <h5 class="card-title mb-0">Tags</h5>
                        </div>
                        <div class="card-body">
                            <div class="d-flex flex-wrap gap-2">
                                <span class="badge bg-secondary-subtle text-secondary">Online Store</span>
                            </div>
                            <button class="btn btn-outline-secondary btn-sm mt-3 w-100">
                                <i class="fas fa-plus me-1"></i>Add tags
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div><!-- container -->
    </div>
    <!-- end page content -->
</div>
<!-- end page-wrapper -->

    <!-- Cancel Order Modal -->
    <div class="modal fade" id="cancelOrderModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title text-danger">Cancel Order</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to cancel this order?</p>
                    <p class="text-muted small">This will mark the delivery status as "Cancelled" and unfulfill items.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-danger" id="confirmCancelBtn">Cancel Order</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Note Modal -->
    <div class="modal fade" id="addNoteModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Note</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <textarea class="form-control" id="orderNoteInput" rows="4" placeholder="Enter note details..."></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveNoteBtn">Save Note</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Tracking Modal -->
    <div class="modal fade" id="addTrackingModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Tracking Number</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="trackingNumberInput" class="form-label">Tracking Number</label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="trackingNumberInput" placeholder="Enter or generate tracking number">
                            <button class="btn btn-outline-secondary" type="button" id="generateTrackingBtn">Generate</button>
                        </div>
                        <div class="form-text">Click "Generate" to create a random tracking code.</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveTrackingBtn">Save Tracking</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Simple Fulfill Order Modal -->
    <div class="modal fade" id="simpleFulfillModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title text-primary">Fulfill Order</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Mark these items as <strong>Fulfilled</strong>?</p>
                    <p class="text-muted small">
                        This indicates you have packed the order.<br>
                        Next, you will be able to print the packing slip and add tracking.
                    </p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="confirmSimpleFulfillBtn">Confirm Fulfillment</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Create Shipping Label Modal -->
    <div class="modal fade" id="shippingLabelModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Create Shipping Label</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to create a shipping label?</p>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-1"></i> This will generate a preview label and open your print dialog.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-success" id="confirmShippingLabelBtn">Create & Print Label</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Script -->
    <script>
        const ORDER_ID = <?php echo $orderId; ?>;
    </script>
    
<?php 
$extra_scripts = '<script src="assets/js/order-details.js?v=' . time() . '"></script>';
include 'footer.php'; 
?>
