<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
date_default_timezone_set('Asia/Vientiane');

// Check role for packer
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'packer') {
    header('Location: ../login.php');
    exit;
}

require_once __DIR__ . '/../../include/con_data.php';

// Check if shops list or user details are needed, but for now we query freely (or filter by shop if applicable).
$current_shop_id = $_SESSION['shop_id'] ?? null;

// Handle AJAX status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_status') {
    header('Content-Type: application/json');
    $order_id = $_POST['order_id'] ?? '';
    $status_type = $_POST['status_type'] ?? '';
    $new_status = $_POST['new_status'] ?? '';

    // Allowed values
    $allowed_columns = [
        'pack_status' => ['ແພັກແລ້ວ', 'ຍັງບໍ່ໄດ້ແພັກ'],
        'shipping_status' => ['ເຄື່ອງອອກແລ້ວ', 'ເຄື່ອງຍັງບໍ່ທັນອອກ'],
        'shop_bill_status' => ['ແຈ້ງບິນແລ້ວ', 'ຍັງບໍ່ທັນແຈ້ງບິນ'],
        'transport_bill_status' => ['ແຈ້ງບິນແລ້ວ', 'ຍັງບໍ່ທັນແຈ້ງບິນ']
    ];

    if (array_key_exists($status_type, $allowed_columns) && in_array($new_status, $allowed_columns[$status_type])) {
        // Build the update query
        $update_query = "UPDATE orders SET `$status_type` = :new_status";

        // If shipping status becomes "ເຄື່ອງອອກແລ້ວ", we can update shipping_date
        if ($status_type === 'shipping_status' && $new_status === 'ເຄື່ອງອອກແລ້ວ') {
            $update_query .= ", shipping_date = NOW()";
        } else if ($status_type === 'shipping_status' && $new_status === 'ເຄື່ອງຍັງບໍ່ທັນອອກ') {
            $update_query .= ", shipping_date = NULL";
        }

        $update_query .= " WHERE OR_id = :order_id";

        if ($current_shop_id) {
            $update_query .= " AND shop_id = :shop_id";
        }

        try {
            $stmt = $pdo->prepare($update_query);
            $params = [
                ':new_status' => $new_status,
                ':order_id' => $order_id
            ];
            if ($current_shop_id) {
                $params[':shop_id'] = $current_shop_id;
            }
            $stmt->execute($params);
            echo json_encode(['success' => true]);
            exit;
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
            exit;
        }
    }
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

// Handle AJAX get order details
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'get_order_details') {
    header('Content-Type: application/json');
    $order_id = $_GET['order_id'] ?? '';

    if (empty($order_id)) {
        echo json_encode(['success' => false, 'message' => 'Order ID is required']);
        exit;
    }

    try {
        $query = "SELECT o.*, c.name AS CU_name, c.phone AS CU_phone,
                         sc.company_name AS shipping_company, sb.branch_name AS shipping_branch 
                  FROM orders o 
                  LEFT JOIN customers c ON o.customer_id = c.CU_id 
                  LEFT JOIN shipping_companies sc ON o.shipping_company_id = sc.SC_id
                  LEFT JOIN shipping_branches sb ON o.shipping_branch_id = sb.SB_id
                  WHERE o.OR_id = :order_id";
        if ($current_shop_id) {
            $query .= " AND o.shop_id = :shop_id";
        }

        $stmt = $pdo->prepare($query);
        $params = [':order_id' => $order_id];
        if ($current_shop_id) {
            $params[':shop_id'] = $current_shop_id;
        }
        $stmt->execute($params);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$order) {
            echo json_encode(['success' => false, 'message' => 'Order not found']);
            exit;
        }

        // Fetch order items
        $item_query = "SELECT * FROM order_items WHERE order_id = :internal_order_id";
        $item_stmt = $pdo->prepare($item_query);
        $item_stmt->execute([':internal_order_id' => $order['id']]);
        $items = $item_stmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode([
            'success' => true,
            'order' => $order,
            'items' => $items
        ]);
        exit;
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        exit;
    }
}

// Fetch Data form submission variables
$search_id = $_GET['search_id'] ?? '';
$filter_date = $_GET['filter_date'] ?? '';

// Build Query
$query = "SELECT o.*, c.name AS CU_name, c.phone AS CU_phone FROM orders o LEFT JOIN customers c ON o.customer_id = c.CU_id WHERE 1=1";
$params = [];

if ($current_shop_id) {
    $query .= " AND o.shop_id = :shop_id";
    $params[':shop_id'] = $current_shop_id;
}

if ($search_id !== '') {
    $query .= " AND o.OR_id LIKE :search_id";
    $params[':search_id'] = '%' . $search_id . '%';
}
if ($filter_date !== '') {
    $query .= " AND DATE(o.created_at) = :filter_date";
    $params[':filter_date'] = $filter_date;
}

$query .= " ORDER BY o.created_at DESC LIMIT 100";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

function getStatusBtnClass($currentVal, $activeVal)
{
    if ($currentVal === $activeVal) {
        return 'active';
    }
    return 'inactive';
}

function getStatusLabel($type, $val)
{
    $labels = [
        'pack_status' => [
            'ຍັງບໍ່ໄດ້ແພັກ' => '<i class="fas fa-box-open"></i> ກຳລັງແພັກ',
            'ແພັກແລ້ວ' => '<i class="fas fa-box"></i> ແພັກແລ້ວ'
        ],
        'shipping_status' => [
            'ເຄື່ອງຍັງບໍ່ທັນອອກ' => '<i class="fas fa-truck-loading"></i> ລໍຖ້າອອກ',
            'ເຄື່ອງອອກແລ້ວ' => '<i class="fas fa-truck"></i> ເຄື່ອງອອກແລ້ວ'
        ],
        'shop_bill_status' => [
            'ຍັງບໍ່ທັນແຈ້ງບິນ' => '<i class="fas fa-file-invoice"></i> ແຈ້ງບິນຮ້ານ',
            'ແຈ້ງບິນແລ້ວ' => '<i class="fas fa-check-circle"></i> ແຈ້ງບິນຮ້ານສຳເລັດ'
        ],
        'transport_bill_status' => [
            'ຍັງບໍ່ທັນແຈ້ງບິນ' => '<i class="fas fa-file-invoice"></i> ແຈ້ງຂົນສົ່ງ',
            'ແຈ້ງບິນແລ້ວ' => '<i class="fas fa-check-circle"></i> ແຈ້ງຂົນສົ່ງສຳເລັດ'
        ]
    ];
    return $labels[$type][$val] ?? $val;
}

?>
<!DOCTYPE html>
<html lang="lo" data-theme="dark">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>ລະບົບແພັກເຄື່ອງ</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@300;400;500;600;700&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="icon" type="image/png" href="../img/logo/muanjai_logo.png">
    <style>
        :root {
            --bg-primary: #0f0f23;
            --bg-secondary: #1a1a2e;
            --card-bg: rgba(255, 255, 255, 0.05);
            --border-color: rgba(193, 153, 42, 0.2);
            --text-primary: #ffffff;
            --text-secondary: rgba(255, 255, 255, 0.6);
            --accent: #c1992a;
            --accent-hover: #e8c547;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
            --info: #3b82f6;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Noto Sans Lao', sans-serif;
            -webkit-tap-highlight-color: transparent;
        }

        body {
            background-color: var(--bg-primary);
            color: var(--text-primary);
            padding-bottom: 40px;
        }

        /* Top Bar */
        .top-nav {
            background: var(--bg-secondary);
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid var(--border-color);
            position: sticky;
            top: 0;
            z-index: 100;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
        }

        .top-nav h2 {
            font-size: 18px;
            font-weight: 600;
            color: var(--accent);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logout-btn {
            color: #ef4444;
            text-decoration: none;
            font-weight: 500;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 8px 12px;
            background: rgba(239, 68, 68, 0.1);
            border-radius: 8px;
            transition: all 0.2s ease;
        }

        .logout-btn:active {
            transform: scale(0.95);
        }

        /* Main Container */
        .container {
            padding: 15px;
            max-width: 800px;
            margin: 0 auto;
        }

        /* Filter Section */
        .filter-section {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }

        .filter-row {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 6px;
        }

        .form-group label {
            font-size: 13px;
            color: var(--text-secondary);
            font-weight: 500;
        }

        .form-control {
            background: rgba(0, 0, 0, 0.2);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            padding: 12px 15px;
            border-radius: 10px;
            font-size: 15px;
            outline: none;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            border-color: var(--accent);
            box-shadow: 0 0 0 2px rgba(193, 153, 42, 0.2);
        }

        .filter-actions {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-top: 5px;
        }

        .btn {
            padding: 12px;
            border-radius: 10px;
            font-size: 15px;
            font-weight: 600;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.2s ease;
        }

        .btn-search {
            background: var(--accent);
            color: white;
            box-shadow: 0 4px 15px rgba(193, 153, 42, 0.3);
        }

        .btn-clear {
            background: transparent;
            border: 1px solid var(--border-color);
            color: var(--text-secondary);
        }

        .btn:active {
            transform: scale(0.98);
        }

        /* Order List */
        .order-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        /* Order Card */
        .order-card {
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
            animation: fadeIn 0.4s ease forwards;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .order-header {
            padding: 15px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: rgba(0, 0, 0, 0.1);
        }

        .order-id {
            font-size: 18px;
            font-weight: 700;
            color: var(--accent);
        }

        .order-date {
            font-size: 12px;
            color: var(--text-secondary);
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .order-body {
            padding: 15px 20px;
        }

        .customer-info {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
            font-size: 15px;
        }

        .customer-info i {
            color: var(--accent);
            background: rgba(193, 153, 42, 0.1);
            padding: 8px;
            border-radius: 8px;
        }

        .order-status-badge {
            display: inline-block;
            padding: 4px 10px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 20px;
            font-size: 12px;
            margin-top: 5px;
            color: var(--text-secondary);
        }

        .order-status-badge.completed {
            background: rgba(16, 185, 129, 0.15);
            color: var(--success);
            border: 1px solid rgba(16, 185, 129, 0.3);
        }

        /* Action Buttons Grid */
        .order-actions {
            padding: 15px 20px 20px;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
        }

        .status-btn {
            padding: 14px 10px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            border: 1px solid var(--border-color);
            background: rgba(255, 255, 255, 0.03);
            color: var(--text-secondary);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 8px;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
        }

        .status-btn i {
            font-size: 18px;
            margin-bottom: 2px;
        }

        /* ACTIVE STATUS DESIGN */
        .status-btn.active {
            background: rgba(16, 185, 129, 0.15);
            border-color: var(--success);
            color: var(--success);
            box-shadow: 0 0 15px rgba(16, 185, 129, 0.2);
            transform: translateY(-2px);
        }

        .status-btn.active::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
            transform: translateX(-100%);
            animation: shimmer 2s infinite;
        }

        @keyframes shimmer {
            100% {
                transform: translateX(100%);
            }
        }

        /* SPINNER ON LOAD */
        .spinner {
            display: none;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
            position: absolute;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .status-btn.loading {
            pointer-events: none;
            opacity: 0.7;
        }

        .status-btn.loading span,
        .status-btn.loading i {
            visibility: hidden;
        }

        .status-btn.loading .spinner {
            display: block;
        }

        /* Active Effect on touch */
        .status-btn:active {
            transform: scale(0.95);
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: var(--text-secondary);
        }

        .empty-state i {
            font-size: 40px;
            margin-bottom: 15px;
            color: var(--border-color);
        }

        /* Order Details Modal Styles */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            backdrop-filter: blur(5px);
            z-index: 1000;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }

        .modal-overlay.active {
            opacity: 1;
            visibility: visible;
        }

        .modal-container {
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 20px;
            width: 100%;
            max-width: 600px;
            max-height: 90vh;
            display: flex;
            flex-direction: column;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
            transform: translateY(20px) scale(0.95);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .modal-overlay.active .modal-container {
            transform: translateY(0) scale(1);
        }

        .modal-header {
            padding: 20px 24px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 20px 20px 0 0;
        }

        .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .modal-close {
            background: transparent;
            border: none;
            color: var(--text-secondary);
            font-size: 20px;
            cursor: pointer;
            transition: color 0.2s;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }

        .modal-close:hover {
            color: var(--danger);
            background: rgba(239, 68, 68, 0.1);
        }

        .modal-body {
            padding: 24px;
            overflow-y: auto;
            flex: 1;
        }

        .detail-section {
            margin-bottom: 24px;
            padding-bottom: 24px;
            border-bottom: 1px dashed var(--border-color);
        }

        .detail-section:last-child {
            margin-bottom: 0;
            padding-bottom: 0;
            border-bottom: none;
        }

        .detail-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 12px;
            font-size: 15px;
        }

        .detail-row:last-child {
            margin-bottom: 0;
        }

        .detail-label {
            color: var(--text-secondary);
        }

        .detail-value {
            color: var(--text-primary);
            font-weight: 500;
            text-align: right;
        }

        .item-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .item-row {
            display: flex;
            justify-content: space-between;
            background: rgba(255, 255, 255, 0.03);
            padding: 12px;
            border-radius: 12px;
            border: 1px solid var(--border-color);
        }

        .item-name {
            font-weight: 500;
            margin-bottom: 4px;
        }

        .item-qty {
            color: var(--text-secondary);
            font-size: 13px;
        }

        .item-subtotal {
            font-weight: 600;
            color: var(--accent);
        }

        .btn-expand {
            background: rgba(193, 153, 42, 0.1);
            color: var(--accent);
            border: 1px solid rgba(193, 153, 42, 0.3);
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-expand:hover {
            background: var(--accent);
            color: #fff;
            transform: scale(1.05);
        }

        .btn-expand i {
            font-size: 14px;
        }
    </style>
</head>

<body>

    <div class="top-nav">
        <h2><i class="fas fa-boxes"></i> ລະບົບແພັກເຄື່ອງ</h2>
        <a href="../../logout.php" class="logout-btn">
            ອອກຈາກລະບົບ <i class="fas fa-sign-out-alt"></i>
        </a>
    </div>

    <div class="container">
        <!-- Filter Form -->
        <div class="filter-section">
            <form action="" method="GET">
                <div class="filter-row">
                    <div class="form-group">
                        <label>ເລກບິນ (Order ID)</label>
                        <input type="text" name="search_id" class="form-control" placeholder="ຄົ້ນຫາເລກບິນ..."
                            value="<?= htmlspecialchars($search_id) ?>">
                    </div>
                    <div class="form-group">
                        <label>ວັນທີ</label>
                        <input type="date" name="filter_date" class="form-control"
                            value="<?= htmlspecialchars($filter_date) ?>">
                    </div>
                    <div class="filter-actions">
                        <button type="submit" class="btn btn-search">
                            <i class="fas fa-search"></i> ຄົ້ນຫາ
                        </button>
                        <a href="packer.php" class="btn btn-clear">
                            <i class="fas fa-undo"></i> ລ້າງຄ່າ
                        </a>
                    </div>
                </div>
            </form>
        </div>

        <!-- Orders List -->
        <div class="order-list">
            <?php if (count($orders) > 0): ?>
                    <?php foreach ($orders as $order): ?>
                            <div class="order-card" id="order-card-<?= $order['OR_id'] ?>">
                                <div class="order-header">
                                    <div>
                                        <div class="order-id">#
                                            <?= $order['OR_id'] ?>
                                            <?php if (!empty($order['bill_number'])): ?>
                                                <span style="font-size: 14px; font-weight: 500; color: #fff; background: rgba(255,255,255,0.1); padding: 2px 8px; border-radius: 10px; margin-left: 8px;">
                                                    ບິນໜ້າຮ້ານ: <?= htmlspecialchars($order['bill_number']) ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="order-date" style="margin-top: 5px;">
                                            <i class="far fa-clock"></i>
                                            <?= date('d/m/Y H:i', strtotime($order['created_at'])) ?>
                                        </div>
                                    </div>
                                    <button class="btn-expand" data-order-id="<?= $order['OR_id'] ?>" title="ເບິ່ງລາຍລະອຽດ">
                                        <i class="fas fa-expand-alt"></i>
                                    </button>
                                </div>
                                <div class="order-body">
                                    <div class="customer-info">
                                        <i class="fas fa-user"></i>
                                        <div>
                                            <div>
                                                <?= htmlspecialchars($order['CU_name'] ?? 'ລູກຄ້າທົ່ວໄປ') ?>
                                            </div>
                                            <?php if (!empty($order['CU_phone'])): ?>
                                                    <div style="font-size: 12px; color: var(--text-secondary); margin-top:2px;">
                                                        <i class="fas fa-phone-alt"
                                                            style="font-size: 10px; background: none; padding: 0; color: inherit;"></i>
                                                        <?= htmlspecialchars($order['CU_phone']) ?>
                                                    </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="order-status-badge <?= $order['order_status'] === 'completed' ? 'completed' : '' ?>">
                                        ສະຖານະບິນ:
                                        <?= htmlspecialchars($order['order_status']) ?>
                                    </div>
                                </div>

                                <!-- Actions -->
                                <div class="order-actions">
                                    <!-- Pack Status -->
                                    <button class="status-btn <?= getStatusBtnClass($order['pack_status'], 'ແພັກແລ້ວ') ?>"
                                        data-id="<?= $order['OR_id'] ?>" data-type="pack_status"
                                        data-current="<?= htmlspecialchars($order['pack_status']) ?>">
                                        <div class="spinner"></div>
                                        <?= getStatusLabel('pack_status', $order['pack_status']) ?>
                                    </button>

                                    <!-- Shipping Status -->
                                    <button class="status-btn <?= getStatusBtnClass($order['shipping_status'], 'ເຄື່ອງອອກແລ້ວ') ?>"
                                        data-id="<?= $order['OR_id'] ?>" data-type="shipping_status"
                                        data-current="<?= htmlspecialchars($order['shipping_status']) ?>">
                                        <div class="spinner"></div>
                                        <?= getStatusLabel('shipping_status', $order['shipping_status']) ?>
                                    </button>

                                    <!-- Shop Bill Status -->
                                    <button class="status-btn <?= getStatusBtnClass($order['shop_bill_status'], 'ແຈ້ງບິນແລ້ວ') ?>"
                                        data-id="<?= $order['OR_id'] ?>" data-type="shop_bill_status"
                                        data-current="<?= htmlspecialchars($order['shop_bill_status']) ?>">
                                        <div class="spinner"></div>
                                        <?= getStatusLabel('shop_bill_status', $order['shop_bill_status']) ?>
                                    </button>

                                    <!-- Transport Bill Status -->
                                    <button class="status-btn <?= getStatusBtnClass($order['transport_bill_status'], 'ແຈ້ງບິນແລ້ວ') ?>"
                                        data-id="<?= $order['OR_id'] ?>" data-type="transport_bill_status"
                                        data-current="<?= htmlspecialchars($order['transport_bill_status']) ?>">
                                        <div class="spinner"></div>
                                        <?= getStatusLabel('transport_bill_status', $order['transport_bill_status']) ?>
                                    </button>
                                </div>
                            </div>
                    <?php endforeach; ?>
            <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-clipboard-list"></i>
                        <h3>ບໍ່ພົບຂໍ້ມູນບິນ</h3>
                        <p>ລອງປ່ຽນເງື່ອນໄຂການຄົ້ນຫາອີກຄັ້ງ</p>
                    </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Order Details Modal -->
    <div class="modal-overlay" id="orderDetailsModal">
        <div class="modal-container">
            <div class="modal-header">
                <div class="modal-title">
                    <i class="fas fa-file-invoice"></i>
                    ລາຍລະອຽດບິນ <span id="modalOrderId" style="color: var(--accent); margin-left: 8px;"></span>
                    <span id="modalBillNumber" style="font-size: 14px; font-weight: 500; color: #fff; background: rgba(255,255,255,0.1); padding: 2px 8px; border-radius: 10px; margin-left: 8px; display: none;"></span>
                </div>
                <button class="modal-close" id="closeOrderDetailsBtn">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <div style="text-align: center; padding: 40px;" id="modalLoading">
                    <i class="fas fa-spinner fa-spin" style="font-size: 30px; color: var(--accent);"></i>
                    <p style="margin-top: 15px; color: var(--text-secondary);">ກຳລັງໂຫຼດຂໍ້ມູນ...</p>
                </div>
                
                <div id="modalContent" style="display: none;">
                    <div class="detail-section">
                        <div class="detail-row">
                            <span class="detail-label">ຊື່ລູກຄ້າ:</span>
                            <span class="detail-value" id="modalCustomerName"></span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">ເບີໂທ:</span>
                            <span class="detail-value" id="modalCustomerPhone"></span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">ວັນທີສັ່ງຊື້:</span>
                            <span class="detail-value" id="modalOrderDate"></span>
                        </div>
                        <div class="detail-row" style="margin-top: 12px; padding-top: 12px; border-top: 1px dashed rgba(255,255,255,0.1);">
                            <span class="detail-label">ບໍລິສັດຂົນສົ່ງ:</span>
                            <span class="detail-value text-info" id="modalShippingCompany">-</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">ສາຂາຂົນສົ່ງ:</span>
                            <span class="detail-value text-info" id="modalShippingBranch">-</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">ໝາຍເຫດ:</span>
                            <span class="detail-value" id="modalNotes">-</span>
                        </div>
                    </div>

                    <div class="detail-section">
                        <h4 style="margin-bottom: 12px; font-size: 14px; color: var(--accent);">ລາຍການສິນຄ້າ</h4>
                        <div class="item-list" id="modalItemsList">
                            <!-- Items will be injected here -->
                        </div>
                    </div>

                    <div class="detail-section" style="border-bottom: none; padding-bottom: 0;">
                        <div class="detail-row">
                            <span class="detail-label">ລວມມູນຄ່າທັງໝົດ:</span>
                            <span class="detail-value" style="font-size: 18px; color: var(--success);" id="modalTotalAmount"></span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">ສະຖານະການຈ່າຍ:</span>
                            <span class="detail-value" id="modalPaymentStatus"></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JS for AJAX Status Update & Modal -->
    <script>
        document.addEventListener('DOMContentLoaded', function () {

            const btnLabels = {
                'pack_status': {
                    'ຍັງບໍ່ໄດ້ແພັກ': '<span><i class="fas fa-box-open"></i> ກຳລັງແພັກ</span>',
                    'ແພັກແລ້ວ': '<span><i class="fas fa-box"></i> ແພັກແລ້ວ</span>'
                },
                'shipping_status': {
                    'ເຄື່ອງຍັງບໍ່ທັນອອກ': '<span><i class="fas fa-truck-loading"></i> ລໍຖ້າອອກ</span>',
                    'ເຄື່ອງອອກແລ້ວ': '<span><i class="fas fa-truck"></i> ເຄື່ອງອອກແລ້ວ</span>'
                },
                'shop_bill_status': {
                    'ຍັງບໍ່ທັນແຈ້ງບິນ': '<span><i class="fas fa-file-invoice"></i> ແຈ້ງບິນຮ້ານ</span>',
                    'ແຈ້ງບິນແລ້ວ': '<span><i class="fas fa-check-circle"></i> ແຈ້ງບິນຮ້ານສຳເລັດ</span>'
                },
                'transport_bill_status': {
                    'ຍັງບໍ່ທັນແຈ້ງບິນ': '<span><i class="fas fa-file-invoice"></i> ແຈ້ງຂົນສົ່ງ</span>',
                    'ແຈ້ງບິນແລ້ວ': '<span><i class="fas fa-check-circle"></i> ແຈ້ງຂົນສົ່ງສຳເລັດ</span>'
                }
            };

            const toggleMapping = {
                'pack_status': { 'ຍັງບໍ່ໄດ້ແພັກ': 'ແພັກແລ້ວ', 'ແພັກແລ້ວ': 'ຍັງບໍ່ໄດ້ແພັກ' },
                'shipping_status': { 'ເຄື່ອງຍັງບໍ່ທັນອອກ': 'ເຄື່ອງອອກແລ້ວ', 'ເຄື່ອງອອກແລ້ວ': 'ເຄື່ອງຍັງບໍ່ທັນອອກ' },
                'shop_bill_status': { 'ຍັງບໍ່ທັນແຈ້ງບິນ': 'ແຈ້ງບິນແລ້ວ', 'ແຈ້ງບິນແລ້ວ': 'ຍັງບໍ່ທັນແຈ້ງບິນ' },
                'transport_bill_status': { 'ຍັງບໍ່ທັນແຈ້ງບິນ': 'ແຈ້ງບິນແລ້ວ', 'ແຈ້ງບິນແລ້ວ': 'ຍັງບໍ່ທັນແຈ້ງບິນ' }
            };

            const checkedValues = ['ແພັກແລ້ວ', 'ເຄື່ອງອອກແລ້ວ', 'ແຈ້ງບິນແລ້ວ'];

            document.querySelectorAll('.status-btn').forEach(btn => {
                // Ensure span wrapper on init for text replacement
                if (!btn.innerHTML.includes('<span')) {
                    const textContent = btn.innerHTML.replace('<div class="spinner"></div>', '');
                    btn.innerHTML = `<div class="spinner"></div><span>${textContent.trim()}</span>`;
                }

                btn.addEventListener('click', async function () {
                    if (this.classList.contains('loading')) return;

                    const orderId = this.dataset.id;
                    const type = this.dataset.type;
                    const current = this.dataset.current;
                    const newStatus = toggleMapping[type][current];

                    // Add loading state
                    this.classList.add('loading');

                    try {
                        const formData = new FormData();
                        formData.append('action', 'update_status');
                        formData.append('order_id', orderId);
                        formData.append('status_type', type);
                        formData.append('new_status', newStatus);

                        const response = await fetch('packer.php', {
                            method: 'POST',
                            body: formData
                        });

                        const data = await response.json();

                        if (data.success) {
                            // Update State and Storage
                            this.dataset.current = newStatus;

                            // Re-render
                            this.innerHTML = `<div class="spinner"></div>${btnLabels[type][newStatus]}`;

                            if (checkedValues.includes(newStatus)) {
                                this.classList.add('active');
                            } else {
                                this.classList.remove('active');
                            }
                        } else {
                            alert('ບໍ່ສາມາດອັບເດດສະຖານະໄດ້: ' + (data.message || 'ເກີດຂໍ້ຜິດພາດ'));
                        }
                    } catch (err) {
                        alert('ເກີດຂໍ້ຜິດພາດຂອງເຊີບເວີ ລອງໃໝ່ອີກຄັ້ງ');
                    } finally {
                        this.classList.remove('loading');
                    }
                });
            });

            // Modal Logic
            const modal = document.getElementById('orderDetailsModal');
            const closeBtn = document.getElementById('closeOrderDetailsBtn');
            const btnExpands = document.querySelectorAll('.btn-expand');
            
            const modalLoading = document.getElementById('modalLoading');
            const modalContent = document.getElementById('modalContent');
            
            function formatNumber(num) {
                return new Intl.NumberFormat('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 2 }).format(num);
            }

            function formatDate(dateString) {
                if (!dateString) return '-';
                const date = new Date(dateString);
                return date.toLocaleDateString('en-GB') + ' ' + date.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
            }

            closeBtn.addEventListener('click', () => {
                modal.classList.remove('active');
            });

            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.classList.remove('active');
                }
            });

            btnExpands.forEach(btn => {
                btn.addEventListener('click', async function() {
                    const orderId = this.dataset.orderId;
                    
                    // Show modal and loading state
                    modal.classList.add('active');
                    modalLoading.style.display = 'block';
                    modalContent.style.display = 'none';
                    document.getElementById('modalOrderId').textContent = '#' + orderId;
                    document.getElementById('modalBillNumber').style.display = 'none';
                    
                    try {
                        const response = await fetch(`packer.php?action=get_order_details&order_id=${encodeURIComponent(orderId)}`);
                        const data = await response.json();
                        
                        if (data.success) {
                            const order = data.order;
                            const items = data.items;
                            
                            if (order.bill_number) {
                                const mbn = document.getElementById('modalBillNumber');
                                mbn.textContent = 'ບິນ: ' + order.bill_number;
                                mbn.style.display = 'inline-block';
                            }

                            // Populate Customer Details
                            document.getElementById('modalCustomerName').textContent = order.CU_name || 'ລູກຄ້າທົ່ວໄປ';
                            document.getElementById('modalCustomerPhone').textContent = order.CU_phone || '-';
                            document.getElementById('modalOrderDate').textContent = formatDate(order.created_at);
                            document.getElementById('modalShippingCompany').textContent = order.shipping_company || '-';
                            document.getElementById('modalShippingBranch').textContent = order.shipping_branch || '-';
                            document.getElementById('modalNotes').textContent = order.notes || order.note || '-';
                            
                            // Formatting payment status
                            let pStatusText = '-';
                            if (order.payment_status === 'paid') pStatusText = '<span style="color:var(--success)">ຈ່າຍແລ້ວ</span>';
                            else if (order.payment_status === 'pending') pStatusText = '<span style="color:var(--warning)">ຍັງບໍ່ຈ່າຍ</span>';
                            else if (order.payment_status === 'partial') pStatusText = '<span style="color:var(--info)">ມັດຈຳ</span>';
                            document.getElementById('modalPaymentStatus').innerHTML = pStatusText;
                            
                            // Format Total Amount
                            document.getElementById('modalTotalAmount').textContent = formatNumber(order.total_amount) + ' ₭ (LAK)';
                            
                            // Populate Items
                            const itemsContainer = document.getElementById('modalItemsList');
                            if (items.length > 0) {
                                let itemsHtml = '';
                                items.forEach(item => {
                                    itemsHtml += `
                                        <div class="item-row">
                                            <div>
                                                <div class="item-name">${item.product_name}</div>
                                                <div class="item-qty">${formatNumber(item.quantity)} x ${formatNumber(item.unit_price)}</div>
                                            </div>
                                            <div class="item-subtotal">${formatNumber(item.total)}</div>
                                        </div>
                                    `;
                                });
                                itemsContainer.innerHTML = itemsHtml;
                            } else {
                                itemsContainer.innerHTML = '<div style="color:var(--text-secondary); text-align:center; padding:10px;">ບໍ່ມີລາຍການສິນຄ້າ</div>';
                            }
                            
                            // Switch view
                            modalLoading.style.display = 'none';
                            modalContent.style.display = 'block';
                        } else {
                            alert('ດຶງຂໍ້ມູນບິນບໍ່ສຳເລັດ: ' + data.message);
                            modal.classList.remove('active');
                        }
                    } catch (err) {
                        alert('ເກີດຂໍ້ຜິດພາດໃນການເຊື່ອມຕໍ່');
                        modal.classList.remove('active');
                    }
                });
            });

        });
    </script>
</body>
</html>