<?php
// Session & Config
if (session_status() === PHP_SESSION_NONE)
    session_start();
require_once '../../include/con_data.php';

// Check Auth
if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit;
}

$shop_id = $_SESSION['shop_id'] ?? null;
$user_id = $_SESSION['user_id'] ?? null;

// ==========================================
// AJAX HANDLERS
// ==========================================
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    $action = $_GET['ajax'];

    if (!$shop_id) {
        echo json_encode(['status' => 'error', 'message' => 'Shop ID not found']);
        exit;
    }

    try {
        // --- 1. Load Table ---
        if ($action === 'table') {
            $search = isset($_GET['search']) ? trim($_GET['search']) : '';
            $date_from = $_GET['date_from'] ?? '';
            $date_to = $_GET['date_to'] ?? '';
            $page = max(1, intval($_GET['page'] ?? 1));
            $limit = 100;
            $offset = ($page - 1) * $limit;

            $where = "o.shop_id = ? AND o.order_status != 'cancelled'";
            $params = [$shop_id];
            $types = "i";

            // Customer filter (from customer.php link)
            $customer_filter = isset($_GET['customer_id']) ? trim($_GET['customer_id']) : '';
            if ($customer_filter) {
                $where .= " AND o.customer_id = ?";
                array_push($params, $customer_filter);
                $types .= "s";
            }

            $users_filter = isset($_GET['users']) ? trim($_GET['users']) : '';
            if ($users_filter) {
                $user_ids = array_filter(array_map('trim', explode(',', $users_filter)));
                if (!empty($user_ids)) {
                    $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
                    $where .= " AND o.created_by IN ($placeholders)";
                    foreach ($user_ids as $uid) {
                        array_push($params, $uid);
                        $types .= "s";
                    }
                }
            }

            if ($search) {
                $where .= " AND (o.OR_id LIKE ? OR c.name LIKE ? OR c.phone LIKE ? OR o.bill_number LIKE ?)";
                $s = "%$search%";
                array_push($params, $s, $s, $s, $s);
                $types .= "ssss";
            } elseif ($date_from && $date_to) {
                $where .= " AND DATE(o.created_at) BETWEEN ? AND ?";
                array_push($params, $date_from, $date_to);
                $types .= "ss";
            }

            $sql = "SELECT o.*, c.name as customer_name, c.phone as customer_phone,
                           sc.company_name as shipping_company, sb.branch_name as shipping_branch,
                           cur.currencys_symbol as currency_symbol
                    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
                    LEFT JOIN currencys cur ON o.currencys_id = cur.currencys_id
                    WHERE $where
                    ORDER BY o.created_at ASC
                    LIMIT ? OFFSET ?";
            array_push($params, $limit, $offset);
            $types .= "ii";

            $stmt = $conn->prepare($sql);
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows > 0) {
                $i = $offset + 1;
                while ($row = $result->fetch_assoc()) {
                    $status_class = match ($row['payment_status']) {
                        'paid' => 'status-paid',
                        'partial' => 'status-partial',
                        'pending' => 'status-pending',
                        'refunded' => 'status-refunded',
                        default => ''
                    };
                    $status_text = match ($row['payment_status']) {
                        'paid' => 'ຈ່າຍແລ້ວ',
                        'partial' => 'ມັດຈຳ',
                        'pending' => 'ຍັງບໍ່ຈ່າຍ',
                        'refunded' => 'ຄືນເງິນ',
                        default => '-'
                    };

                    $type_badge = match ($row['order_type']) {
                        'pos' => '<span class="badge type-pos">ໜ້າຮ້ານ</span>',
                        'online' => '<span class="badge type-online">ອອນລາຍ</span>',
                        'wholesale' => '<span class="badge type-wholesale">ຂາຍສົ່ງ</span>',
                        default => '-'
                    };

                    $symbol = $row['currency_symbol'] ?? '₭';
                    $total = number_format($row['total_amount'], ($row['currencys_id'] === 'CUR_3' ? 2 : 0));

                    echo '<tr data-order-id="' . $row['OR_id'] . '" data-order-type="' . $row['order_type'] . '">';
                    echo '<td class="bulk-checkbox"><input type="checkbox" class="order-checkbox" data-order-id="' . $row['OR_id'] . '"></td>';
                    echo '<td>' . $i++ . '</td>';
                    echo '<td>' . htmlspecialchars($row['bill_number'] ?? '-') . '</td>';
                    echo '<td class="order-id-cell">' . $row['OR_id'] . '</td>';
                    echo '<td>' . date('d/m/Y H:i', strtotime($row['created_at'])) . '</td>';
                    echo '<td>' . htmlspecialchars($row['customer_name'] ?? '-') . '</td>';
                    echo '<td>' . htmlspecialchars($row['customer_phone'] ?? '-') . '</td>';
                    echo '<td>' . htmlspecialchars($row['shipping_company'] ?? '-') . '</td>';
                    echo '<td>' . htmlspecialchars($row['shipping_branch'] ?? '-') . '</td>';
                    echo '<td><span class="badge ' . $status_class . '">' . $status_text . '</span></td>';
                    // Print Icon Badge (Green if printed, Red if not)
                    echo '<td style="text-align:center;">' . ($row['print_status'] === 'printed' ? '<span class="badge status-paid" title="ພິມແລ້ວ" style="padding: 10px; border-radius: 50%; width: 35px; height: 35px; justify-content: center;"><i class="fas fa-print"></i></span>' : '<span class="badge status-unprinted" title="ຍັງບໍ່ພິມ" style="padding: 10px; border-radius: 50%; width: 35px; height: 35px; justify-content: center;"><i class="fas fa-print"></i></span>') . '</td>';
                    echo '<td class="amount-cell">' . $symbol . $total . '</td>';
                    echo '<td>
                        <div class="action-btns">
                            <button class="btn-icon view" onclick="viewOrder(\'' . $row['OR_id'] . '\')" title="ເບິ່ງ"><i class="fas fa-eye"></i></button>
                            <button class="btn-icon edit" onclick="editOrder(\'' . $row['OR_id'] . '\')" title="ແກ້ໄຂ"><i class="fas fa-pen"></i></button>
                            <button class="btn-icon print" onclick="printOrder(\'' . $row['OR_id'] . '\')" title="ພິມ"><i class="fas fa-print"></i></button>
                            <button class="btn-icon delete" onclick="confirmDeleteOrder(\'' . $row['OR_id'] . '\')" title="ລົບ"><i class="fas fa-trash"></i></button>
                        </div>
                    </td>';
                    echo '</tr>';
                }
            } else {
                echo '<tr><td colspan="14" class="empty-state">ບໍ່ພົບຂໍ້ມູນ</td></tr>';
            }
            exit;
        }

        // --- 2. Pagination ---
        if ($action === 'pagination') {
            $search = $_GET['search'] ?? '';
            $date_from = $_GET['date_from'] ?? '';
            $date_to = $_GET['date_to'] ?? '';
            $page = max(1, intval($_GET['page'] ?? 1));
            $limit = 100;

            $where = "o.shop_id = ? AND o.order_status != 'cancelled'";
            $params = [$shop_id];
            $types = "i";

            // Customer filter (from customer.php link)
            $customer_filter = isset($_GET['customer_id']) ? trim($_GET['customer_id']) : '';
            if ($customer_filter) {
                $where .= " AND o.customer_id = ?";
                array_push($params, $customer_filter);
                $types .= "s";
            }

            $users_filter = isset($_GET['users']) ? trim($_GET['users']) : '';
            if ($users_filter) {
                $user_ids = array_filter(array_map('trim', explode(',', $users_filter)));
                if (!empty($user_ids)) {
                    $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
                    $where .= " AND o.created_by IN ($placeholders)";
                    foreach ($user_ids as $uid) {
                        array_push($params, $uid);
                        $types .= "s";
                    }
                }
            }

            if ($search) {
                $where .= " AND (o.OR_id LIKE ? OR c.name LIKE ? OR c.phone LIKE ? OR o.bill_number LIKE ?)";
                $s = "%$search%";
                array_push($params, $s, $s, $s, $s);
                $types .= "ssss";
            } elseif ($date_from && $date_to) {
                $where .= " AND DATE(o.created_at) BETWEEN ? AND ?";
                array_push($params, $date_from, $date_to);
                $types .= "ss";
            }

            $sql = "SELECT COUNT(*) as total FROM orders o 
                    LEFT JOIN customers c ON o.customer_id = c.CU_id 
                    WHERE $where";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $total_rows = $stmt->get_result()->fetch_assoc()['total'];
            $total_pages = ceil($total_rows / $limit);

            echo '<div class="pagination-info">ທັງໝົດ ' . number_format($total_rows) . ' ລາຍການ</div>';
            echo '<div class="pagination-btns">';
            if ($total_pages > 1) {
                if ($page > 1)
                    echo '<button onclick="loadTablePage(' . ($page - 1) . ')"><i class="fas fa-angle-left"></i></button>';

                $start = max(1, $page - 2);
                $end = min($total_pages, $page + 2);
                for ($i = $start; $i <= $end; $i++) {
                    $active = ($i == $page) ? 'active' : '';
                    echo '<button class="' . $active . '" onclick="loadTablePage(' . $i . ')">' . $i . '</button>';
                }

                if ($page < $total_pages)
                    echo '<button onclick="loadTablePage(' . ($page + 1) . ')"><i class="fas fa-angle-right"></i></button>';
            }
            echo '</div>';
            exit;
        }

        // --- 3. Order Details ---
        if ($action === 'details') {
            $order_id = $_GET['order_id'] ?? '';

            $sql = "SELECT o.*, c.name as customer_name, c.phone as customer_phone,
                           sc.company_name as shipping_company, sb.branch_name as shipping_branch,
                           cur.currencys_symbol, cur.currencys_name,
                           u.name as created_by_name
                    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
                    LEFT JOIN currencys cur ON o.currencys_id = cur.currencys_id
                    LEFT JOIN users u ON o.created_by = u.user_id
                    WHERE o.OR_id = ? AND o.shop_id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("si", $order_id, $shop_id);
            $stmt->execute();
            $order = $stmt->get_result()->fetch_assoc();

            if (!$order) {
                echo json_encode(['status' => 'error', 'message' => 'Not found']);
                exit;
            }

            // Use subqueries to prevent cartesian product duplicates
            // ORDER BY prioritizes: 1) product_id match first, 2) longer barcode (real EAN vs short internal code)
            $sql = "SELECT oi.*, 
                           (SELECT p1.barcode FROM products p1 
                            WHERE (oi.product_id != '' AND (oi.product_id = p1.id OR oi.product_id = p1.product_code OR oi.product_id = p1.barcode))
                               OR (oi.product_id = '' AND TRIM(oi.product_name) = TRIM(p1.products_name))
                            ORDER BY (oi.product_id != '' AND (oi.product_id = p1.id OR oi.product_id = p1.product_code OR oi.product_id = p1.barcode)) DESC, LENGTH(p1.barcode) DESC
                            LIMIT 1) as barcode,
                           (SELECT p2.image FROM products p2 
                            WHERE (oi.product_id != '' AND (oi.product_id = p2.id OR oi.product_id = p2.product_code OR oi.product_id = p2.barcode))
                               OR (oi.product_id = '' AND TRIM(oi.product_name) = TRIM(p2.products_name))
                            ORDER BY (oi.product_id != '' AND (oi.product_id = p2.id OR oi.product_id = p2.product_code OR oi.product_id = p2.barcode)) DESC, LENGTH(p2.barcode) DESC
                            LIMIT 1) as product_image
                    FROM order_items oi 
                    WHERE oi.order_id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $order['id']);
            $stmt->execute();
            $items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

            $response = [
                'status' => 'success',
                'order' => array_merge($order, [
                    'order_type_text' => match ($order['order_type']) { 'pos' => 'ຂາຍໜ້າຮ້ານ', 'online' => 'ຂາຍອອນລາຍ', default => 'ຂາຍສົ່ງ'},
                    'payment_status_text' => match ($order['payment_status']) { 'paid' => 'ຈ່າຍແລ້ວ', 'pending' => 'ຍັງບໍ່ຈ່າຍ', 'partial' => 'ມັດຈຳ', 'refunded' => 'ຄືນເງິນ', default => '-'},
                    'currency_symbol' => $order['currencys_symbol'] ?? '₭',
                    'currency_name' => $order['currencys_name'] ?? 'LAK'
                ]),
                'items' => $items
            ];
            echo json_encode($response);
            exit;
        }

        // --- 4. Search Customers (AJAX Live Search) ---
        if ($action === 'search_customers') {
            $q = trim($_GET['q'] ?? '');
            $like = "%$q%";
            $stmt = $conn->prepare("SELECT id, CU_id, name, phone FROM customers WHERE shop_id = ? AND (name LIKE ? OR phone LIKE ?) ORDER BY name LIMIT 20");
            $stmt->bind_param("iss", $shop_id, $like, $like);
            $stmt->execute();
            $results = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            echo json_encode(['status' => 'success', 'data' => $results]);
            exit;
        }

        // --- 5. Search Products (AJAX Live Search) ---
        if ($action === 'search_products') {
            $q = trim($_GET['q'] ?? '');
            $results = [];
            if (strlen($q) >= 1) {
                $like = "%$q%";
                $stmt = $conn->prepare("SELECT id, product_code, barcode, products_name, price_1, image FROM products WHERE shop_id = ? AND deleted_at IS NULL AND (products_name LIKE ? OR product_code LIKE ? OR barcode LIKE ?) ORDER BY products_name LIMIT 20");
                $stmt->bind_param("isss", $shop_id, $like, $like, $like);
                $stmt->execute();
                $results = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            }
            echo json_encode(['status' => 'success', 'data' => $results]);
            exit;
        }

        // --- 6. Search Shipping Companies ---
        if ($action === 'search_shipping_companies') {
            $q = trim($_GET['q'] ?? '');
            $like = "%$q%";
            $stmt = $conn->prepare("SELECT id, SC_id, company_name FROM shipping_companies WHERE shop_id = ? AND company_name LIKE ? ORDER BY company_name LIMIT 20");
            $stmt->bind_param("is", $shop_id, $like);
            $stmt->execute();
            $results = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            echo json_encode(['status' => 'success', 'data' => $results]);
            exit;
        }

        // --- 7. Search Shipping Branches ---
        if ($action === 'search_shipping_branches') {
            $q = trim($_GET['q'] ?? '');
            $like = "%$q%";
            $stmt = $conn->prepare("SELECT id, SB_id, branch_name FROM shipping_branches WHERE shop_id = ? AND branch_name LIKE ? ORDER BY branch_name LIMIT 20");
            $stmt->bind_param("is", $shop_id, $like);
            $stmt->execute();
            $results = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            echo json_encode(['status' => 'success', 'data' => $results]);
            exit;
        }

        if ($action === 'update_full' && $_SERVER['REQUEST_METHOD'] === 'POST') {
            require_once '../../include/secondary_ids.php';
            // Handle both application/json and multipart/form-data
            if (isset($_POST['data'])) {
                $input = json_decode($_POST['data'], true);
            } else {
                $input = json_decode(file_get_contents('php://input'), true);
            }
            $oid = $input['order_id'] ?? '';

            // Look up internal order id
            $stmt = $conn->prepare("SELECT id FROM orders WHERE OR_id = ? AND shop_id = ?");
            $stmt->bind_param("si", $oid, $shop_id);
            $stmt->execute();
            $orderRow = $stmt->get_result()->fetch_assoc();
            if (!$orderRow) {
                echo json_encode(['status' => 'error', 'message' => 'Order not found']);
                exit;
            }
            $internal_id = $orderRow['id'];

            // Resolve secondary IDs
            $customer_id = null;
            if (!empty($input['customer_cu_id'])) {
                $customer_id = $input['customer_cu_id'];
            }

            $shipping_company_id = null;
            if (!empty($input['shipping_company_sc_id'])) {
                $shipping_company_id = $input['shipping_company_sc_id'];
            }

            $shipping_branch_id = null;
            if (!empty($input['shipping_branch_sb_id'])) {
                $shipping_branch_id = $input['shipping_branch_sb_id'];
            }

            $currencys_id = !empty($input['currencys_id']) ? $input['currencys_id'] : null;
            $currency_rate = floatval($input['currency_rate'] ?? 1);
            $vat_enabled = intval($input['vat_enabled'] ?? 0);

            $subtotal = floatval($input['subtotal'] ?? 0);
            $discount_amount = floatval($input['discount_amount'] ?? 0);
            $tax_amount = floatval($input['tax_amount'] ?? 0);
            $total_amount = floatval($input['total_amount'] ?? 0);

            $subtotal_lak = floatval($input['subtotal_lak'] ?? 0);
            $discount_lak = floatval($input['discount_lak'] ?? 0);
            $vat_amount_lak = floatval($input['vat_amount_lak'] ?? 0);
            $total_amount_lak = floatval($input['total_amount_lak'] ?? 0);

            $payment_status = $input['payment_status'] ?? 'pending';
            $payment_method = !empty($input['payment_method']) ? $input['payment_method'] : null;
            $deposit_amount = floatval($input['deposit_amount'] ?? 0);
            $notes = $input['notes'] ?? null;
            $bill_number = $input['bill_number'] ?? null;
            $bill_transport_number = $input['bill_transport_number'] ?? null;
            $shipping_date = !empty($input['shipping_date']) ? $input['shipping_date'] : null;

            $print_status = ($input['print_status'] === 'printed' || $input['print_status'] === 'ພິມແລ້ວ') ? 'printed' : 'pending';
            $prepare_status = ($input['prepare_status'] === 'ຈັດເຄື່ອງແລ້ວ') ? 'ຈັດເຄື່ອງແລ້ວ' : 'ຍັງບໍ່ທັນຈັດເຄື່ອງ';
            $front_stock_status = ($input['front_stock_status'] === 'ຄີແລ້ວ') ? 'ຄີແລ້ວ' : 'ຍັງບໍ່ທັນຄີ';
            $pack_status = ($input['pack_status'] === 'ແພັກແລ້ວ') ? 'ແພັກແລ້ວ' : 'ຍັງບໍ່ໄດ້ແພັກ';
            $shipping_status = ($input['shipping_status'] === 'ເຄື່ອງອອກແລ້ວ') ? 'ເຄື່ອງອອກແລ້ວ' : 'ເຄື່ອງຍັງບໍ່ທັນອອກ';
            $shop_bill_status = ($input['shop_bill_status'] === 'ແຈ້ງບິນແລ້ວ' || $input['shop_bill_status'] === 'ແຈ້ງແລ້ວ') ? 'ແຈ້ງບິນແລ້ວ' : 'ຍັງບໍ່ທັນແຈ້ງບິນ';
            $transport_bill_status = ($input['transport_bill_status'] === 'ແຈ້ງບິນແລ້ວ' || $input['transport_bill_status'] === 'ແຈ້ງແລ້ວ') ? 'ແຈ້ງບິນແລ້ວ' : 'ຍັງບໍ່ທັນແຈ້ງບິນ';

            // Handle slip uploads
            $slip_filenames = [];
            if (isset($_FILES['slip_images'])) {
                $uploadDir = '../../img/slip/';
                if (!is_dir($uploadDir))
                    mkdir($uploadDir, 0777, true);
                $files = $_FILES['slip_images'];
                for ($i = 0; $i < count($files['name']); $i++) {
                    if ($files['error'][$i] === 0) {
                        $ext = pathinfo($files['name'][$i], PATHINFO_EXTENSION);
                        if (in_array(strtolower($ext), ['jpg', 'jpeg', 'png', 'webp'])) {
                            $filename = uniqid('slip_') . '.' . $ext;
                            if (move_uploaded_file($files['tmp_name'][$i], $uploadDir . $filename)) {
                                $slip_filenames[] = $filename;
                            }
                        }
                    }
                }
            }

            $conn->begin_transaction();
            try {
                set_error_handler(function ($errno, $errstr, $errfile, $errline) {
                    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
                });
                $existing_slips = isset($input['existing_slips']) ? $input['existing_slips'] : [];
                $final_slips = array_merge($existing_slips, $slip_filenames);
                $slip_str = !empty($final_slips) ? implode(',', $final_slips) : null;

                // Build update query - always include order_image_slip
                $sql = "UPDATE orders SET 
                    customer_id = ?, shipping_company_id = ?, shipping_branch_id = ?,
                    currencys_id = ?, currency_rate = ?, vat_enabled = ?,
                    subtotal = ?, discount_amount = ?, tax_amount = ?, total_amount = ?,
                    subtotal_lak = ?, discount_lak = ?, vat_amount_lak = ?, total_amount_lak = ?,
                    payment_status = ?, payment_method = ?, deposit_amount = ?,
                    notes = ?, bill_number = ?, bill_transport_number = ?, shipping_date = ?,
                    order_image_slip = ?, print_status = ?, prepare_status = ?, front_stock_status = ?,
                    pack_status = ?, shipping_status = ?, shop_bill_status = ?, transport_bill_status = ?
                    WHERE OR_id = ? AND shop_id = ?";
                $stmt = $conn->prepare($sql);
                // 29 parameters total: 10 strings, 1 int, 1 float, 4 float, 4 float, 2 string, 1 string (sometimes float? wait, deposit is float), ...
                // Let's use the exact type string format
                $stmt->bind_param(
                    "ssssdiddddddddssdsssssssssssssi",
                    $customer_id,
                    $shipping_company_id,
                    $shipping_branch_id,
                    $currencys_id,
                    $currency_rate,
                    $vat_enabled,
                    $subtotal,
                    $discount_amount,
                    $tax_amount,
                    $total_amount,
                    $subtotal_lak,
                    $discount_lak,
                    $vat_amount_lak,
                    $total_amount_lak,
                    $payment_status,
                    $payment_method,
                    $deposit_amount,
                    $notes,
                    $bill_number,
                    $bill_transport_number,
                    $shipping_date,
                    $slip_str,
                    $print_status,
                    $prepare_status,
                    $front_stock_status,
                    $pack_status,
                    $shipping_status,
                    $shop_bill_status,
                    $transport_bill_status,
                    $oid,
                    $shop_id
                );
                if (!$stmt->execute()) {
                    throw new Exception('Update failed: ' . $stmt->error);
                }

                // Delete old items and re-insert
                $stmt = $conn->prepare("DELETE FROM order_items WHERE order_id = ?");
                $stmt->bind_param("i", $internal_id);
                $stmt->execute();

                $items = $input['items'] ?? [];
                if (!empty($items)) {
                    $stmt = $conn->prepare("INSERT INTO order_items (order_id, product_id, product_name, quantity, unit_price, total) VALUES (?, ?, ?, ?, ?, ?)");
                    foreach ($items as $item) {
                        $product_id = $item['product_id'] ?? '';
                        $product_name = $item['product_name'] ?? '';
                        $qty = floatval($item['quantity'] ?? 1);
                        $unit_price = floatval($item['unit_price'] ?? 0);
                        $item_total = floatval($item['total'] ?? 0);
                        $stmt->bind_param("issddd", $internal_id, $product_id, $product_name, $qty, $unit_price, $item_total);
                        if (!$stmt->execute()) {
                            throw new Exception('Item insert failed: ' . $stmt->error);
                        }
                    }
                }

                $conn->commit();
                echo json_encode(['status' => 'success', 'message' => 'Order updated successfully']);
            } catch (Throwable $e) {
                if (isset($conn))
                    $conn->rollback();
                restore_error_handler();
                echo json_encode(['status' => 'error', 'message' => 'Exception: ' . $e->getMessage() . ' at ' . $e->getFile() . ':' . $e->getLine()]);
            }
            exit;
        }

        // --- 9. Legacy Update Order (kept for compatibility) ---
        if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $oid = $input['order_id'];
            $status = $input['payment_status'];
            $deposit = $input['deposit_amount'];
            $ship_code = $input['shipping_code'];
            $notes = $input['notes'];

            $stmt = $conn->prepare("UPDATE orders SET payment_status=?, deposit_amount=?, shipping_code=?, notes=? WHERE OR_id=? AND shop_id=?");
            $stmt->bind_param("sdsssi", $status, $deposit, $ship_code, $notes, $oid, $shop_id);

            if ($stmt->execute())
                echo json_encode(['status' => 'success']);
            else
                echo json_encode(['status' => 'error', 'message' => $conn->error]);
            exit;
        }

        // --- 5. Delete Order ---
        if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $oid = $input['order_id'];
            $pass = $input['password'];

            $stmt = $conn->prepare("SELECT password FROM users WHERE id=?");
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();

            if (!$user || !password_verify($pass, $user['password'])) {
                echo json_encode(['status' => 'error', 'message' => 'ລະຫັດຜ່ານບໍ່ຖືກຕ້ອງ']);
                exit;
            }

            $stmt = $conn->prepare("SELECT id FROM orders WHERE OR_id=? AND shop_id=?");
            $stmt->bind_param("si", $oid, $shop_id);
            $stmt->execute();
            $order = $stmt->get_result()->fetch_assoc();

            if ($order) {
                // Soft delete by changing status
                $stmt = $conn->prepare("UPDATE orders SET order_status='cancelled' WHERE OR_id=? AND shop_id=?");
                $stmt->bind_param("si", $oid, $shop_id);

                if ($stmt->execute()) {
                    // Update tips or other related items if necessary (skipped as schema unverified for tips)
                    echo json_encode(['status' => 'success']);
                } else {
                    echo json_encode(['status' => 'error', 'message' => $conn->error]);
                }
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Not found']);
            }
            exit;
        }

    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        exit;
    }
}

$page_title = 'ປະຫວັດການຂາຍ';
require_once '../includes/header.php';

// Load users for the multi-select filter
$users_list = [];
try {
    $userStmt = $pdo->prepare("SELECT user_id, name FROM users WHERE shop_id = :shop_id ORDER BY name");
    $userStmt->execute([':shop_id' => $shop_id]);
    $users_list = $userStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // silently handle
}

// Load currencies for edit modal
$currencies = [];
try {
    $curStmt = $pdo->prepare("SELECT c.*, 
        (SELECT r.rate_amount FROM rates r WHERE r.currencys_id = c.currencys_id AND r.shop_id = c.shop_id ORDER BY r.rate_datetime DESC LIMIT 1) as rate_amount,
        (SELECT r.rate_id FROM rates r WHERE r.currencys_id = c.currencys_id AND r.shop_id = c.shop_id ORDER BY r.rate_datetime DESC LIMIT 1) as rate_id
        FROM currencys c WHERE c.shop_id = :shop_id ORDER BY c.base_currency DESC, c.currencys_name");
    $curStmt->execute([':shop_id' => $shop_id]);
    $currencies = $curStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // currencies query failed
}
if (empty($currencies)) {
    $currencies = [['currencys_id' => 'LAK', 'currencys_name' => 'Lao Kip', 'currencys_symbol' => '₭', 'rate_amount' => 1]];
}
?>

<style>
    /* Copied Styles */
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        flex-wrap: wrap;
        gap: 16px;
    }

    .page-header h1 {
        font-size: 24px;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 12px;
        margin: 0;
    }

    .filter-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 16px;
        padding: 20px;
        margin-bottom: 20px;
    }

    .filter-row {
        display: flex;
        gap: 16px;
        flex-wrap: wrap;
        align-items: center;
    }

    .search-box {
        display: flex;
        align-items: center;
        gap: 8px;
        background: var(--input-bg);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        padding: 12px 16px;
        flex: 1;
        min-width: 250px;
    }

    .search-box input {
        border: none;
        background: transparent;
        outline: none;
        color: var(--text-primary);
        width: 100%;
        font-size: 16px;
    }

    /* Multi-select filter styles */
    .user-filter-wrapper {
        position: relative;
        min-width: 200px;
    }

    .user-filter-btn {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 16px;
        background: var(--input-bg);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        color: var(--text-primary);
        font-size: 16px;
        cursor: pointer;
        width: 100%;
        text-align: left;
    }

    .user-filter-btn:hover {
        border-color: var(--accent);
    }

    .user-filter-dropdown {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        margin-top: 4px;
        background: var(--bg-secondary, #fff);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        z-index: 100;
        display: none;
        max-height: 300px;
        overflow-y: auto;
        padding: 8px 0;
    }

    .user-filter-dropdown.show {
        display: block;
    }

    .user-filter-item {
        padding: 8px 16px;
        display: flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;
    }

    .user-filter-item:hover {
        background: rgba(var(--accent-rgb), 0.05);
    }

    .user-filter-item input[type="checkbox"] {
        cursor: pointer;
        width: 16px;
        height: 16px;
    }

    .user-filter-count {
        background: var(--accent);
        color: white;
        font-size: 12px;
        padding: 2px 6px;
        border-radius: 10px;
        margin-left: 8px;
        display: none;
    }

    .date-input {
        padding: 12px 16px;
        border: 1px solid var(--border-color);
        border-radius: 10px;
        background: var(--input-bg);
        color: var(--text-primary);
        font-size: 16px;
    }

    .btn-pro {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 14px 24px;
        border-radius: 10px;
        border: none;
        font-weight: 600;
        cursor: pointer;
        transition: all .3s;
        font-size: 16px;
    }

    .btn-pro.primary {
        background: linear-gradient(135deg, var(--accent), var(--accent-soft));
        color: #fff;
        box-shadow: 0 4px 15px rgba(74, 144, 217, .3);
    }

    .btn-pro.primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(74, 144, 217, .4);
    }

    .btn-pro.secondary {
        background: var(--border-color);
        color: var(--text-primary);
    }

    .btn-pro.success {
        background: linear-gradient(135deg, #28a745, #20c997);
        color: #fff;
    }

    .btn-reset {
        background: #6c757d;
        color: #fff;
        padding: 12px 20px;
        border-radius: 10px;
        border: none;
        font-weight: 500;
        cursor: pointer;
        text-decoration: none;
        font-size: 14px;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .data-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 16px;
        overflow: hidden;
    }

    .data-card-header {
        padding: 20px 24px;
        border-bottom: 1px solid var(--border-color);
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 16px;
    }

    .data-card-header h3 {
        margin: 0;
        font-size: 18px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .pro-table {
        width: 100%;
        border-collapse: collapse;
    }

    .pro-table th {
        background: rgba(var(--accent-rgb), 0.1);
        padding: 16px 14px;
        text-align: left;
        font-weight: 600;
        font-size: 15px;
        text-transform: uppercase;
        color: var(--text-secondary);
        white-space: nowrap;
        border-bottom: 2px solid var(--accent);
    }

    .pro-table td {
        padding: 16px 14px;
        border-bottom: 1px solid var(--border-color);
        vertical-align: middle;
        font-size: 16px;
    }

    .pro-table tbody tr:hover {
        background: rgba(var(--accent-rgb), 0.05);
    }

    .badge {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 8px 14px;
        border-radius: 20px;
        font-size: 14px;
        font-weight: 600;
    }

    .badge::before {
        content: '';
        width: 6px;
        height: 6px;
        border-radius: 50%;
    }

    .badge.type-pos {
        background: rgba(255, 152, 0, .15);
        color: #ff9800;
    }

    .badge.type-pos::before {
        background: #ff9800;
    }

    .badge.type-online {
        background: rgba(33, 150, 243, .15);
        color: #2196f3;
    }

    .badge.type-online::before {
        background: #2196f3;
    }

    .badge.type-wholesale {
        background: rgba(156, 39, 176, .15);
        color: #9c27b0;
    }

    .badge.type-wholesale::before {
        background: #9c27b0;
    }

    .badge.status-paid {
        background: rgba(40, 167, 69, .15);
        color: #28a745;
    }

    .badge.status-paid::before {
        background: #28a745;
    }

    .badge.status-partial {
        background: rgba(23, 162, 184, .15);
        color: #17a2b8;
    }

    .badge.status-partial::before {
        background: #17a2b8;
    }

    .badge.status-pending {
        background: rgba(255, 193, 7, .15);
        color: #ffc107;
    }

    .badge.status-pending::before {
        background: #ffc107;
    }

    .badge.status-refunded {
        background: rgba(220, 53, 69, .15);
        color: #dc3545;
    }

    .badge.status-refunded::before {
        background: #dc3545;
    }

    .badge.status-unprinted {
        background: rgba(220, 53, 69, .15);
        color: #dc3545;
    }

    .badge.status-unprinted::before {
        background: #dc3545;
    }

    .amount-cell {
        font-weight: 700;
        font-size: 17px;
        color: #28a745;
    }

    .action-btns {
        display: flex;
        gap: 6px;
    }

    .btn-icon {
        width: 38px;
        height: 38px;
        border-radius: 8px;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all .2s;
        font-size: 15px;
    }

    .btn-icon.view {
        background: rgba(74, 144, 217, .15);
        color: var(--accent);
    }

    .btn-icon.view:hover {
        background: var(--accent);
        color: #fff;
    }

    .btn-icon.edit {
        background: rgba(255, 193, 7, .15);
        color: #ffc107;
    }

    .btn-icon.edit:hover {
        background: #ffc107;
        color: #000;
    }

    .btn-icon.delete {
        background: rgba(220, 53, 69, .15);
        color: #dc3545;
    }

    .btn-icon.delete:hover {
        background: #dc3545;
        color: #fff;
    }

    .btn-icon.print {
        background: rgba(40, 167, 69, .15);
        color: #28a745;
    }

    .btn-icon.print:hover {
        background: #28a745;
        color: #fff;
    }

    /* Pagination */
    .pagination-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 20px;
        border-top: 1px solid var(--border-color);
        flex-wrap: wrap;
        gap: 10px;
    }

    .pagination-info {
        font-size: 14px;
        color: var(--text-secondary);
    }

    .pagination-btns {
        display: flex;
        gap: 4px;
    }

    .pagination-btns button {
        min-width: 36px;
        height: 36px;
        border: 1px solid var(--border-color);
        background: var(--card-bg);
        color: var(--text-primary);
        border-radius: 8px;
        cursor: pointer;
        font-size: 13px;
        transition: all .2s;
        font-family: inherit;
    }

    .pagination-btns button:hover {
        border-color: var(--accent);
        color: var(--accent);
    }

    .pagination-btns button.active {
        background: var(--accent);
        color: #fff;
        border-color: var(--accent);
    }

    .pagination-btns button:disabled {
        opacity: .4;
        cursor: not-allowed;
    }

    /* Modal */
    .pro-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, .6);
        backdrop-filter: blur(4px);
        z-index: 9999;
        align-items: center;
        justify-content: center;
        padding: 20px;
    }

    .pro-modal.show {
        display: flex;
    }

    .pro-modal-content {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 20px;
        width: 100%;
        max-height: 90vh;
        overflow-y: auto;
        animation: modalSlide .3s ease;
    }


    .pro-modal-content.large {
        max-width: 900px;
    }

    .pro-modal-content.small {
        max-width: 420px;
    }

    @keyframes modalSlide {
        from {
            opacity: 0;
            transform: translateY(-20px) scale(.95);
        }

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

    .pro-modal-header {
        padding: 24px;
        border-bottom: 1px solid var(--border-color);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .pro-modal-header h3 {
        margin: 0;
        font-size: 20px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .pro-modal-close {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        border: none;
        background: rgba(255, 255, 255, .1);
        color: var(--text-secondary);
        cursor: pointer;
        font-size: 20px;
    }

    .pro-modal-body {
        padding: 24px;
    }

    .info-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 16px;
        margin-bottom: 24px;
    }

    .info-box {
        background: var(--input-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        padding: 16px;
        border-left: 3px solid var(--accent);
    }

    .info-box h4 {
        font-size: 15px;
        color: var(--accent);
        margin: 0 0 12px 0;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .info-box p {
        margin: 10px 0;
        font-size: 18px;
        display: flex;
        justify-content: space-between;
    }

    .items-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 16px;
    }

    .items-table th {
        background: var(--accent);
        color: #fff;
        padding: 14px;
        text-align: left;
        font-size: 16px;
    }

    .items-table td {
        padding: 14px;
        border-bottom: 1px solid var(--border-color);
        font-size: 16px;
    }

    .form-pro-input {
        width: 100%;
        padding: 14px 16px;
        border: 2px solid var(--border-color);
        border-radius: 10px;
        background: var(--input-bg);
        color: var(--text-primary);
        font-size: 15px;
    }

    .bulk-checkbox {
        display: none;
    }

    .bulk-checkbox.show {
        display: table-cell;
    }

    .bulk-actions {
        display: none;
        gap: 10px;
    }

    /* ========== Edit Modal Styles ========== */
    .pro-modal-content.xlarge {
        max-width: 1100px;
    }

    .edit-section {
        margin-bottom: 20px;
        padding-bottom: 20px;
        border-bottom: 1px solid var(--border-color);
    }

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

    .edit-section h4 {
        font-size: 16px;
        color: var(--accent);
        margin: 0 0 14px 0;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .edit-form-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 14px;
        margin-bottom: 14px;
    }

    .edit-form-group {
        margin-bottom: 12px;
    }

    .edit-form-group label {
        display: block;
        margin-bottom: 6px;
        font-weight: 500;
        color: var(--text-secondary);
        font-size: 14px;
    }

    /* Searchable Select Component (matching pos.php) */
    .input-with-btn {
        display: flex;
        gap: 8px;
        align-items: flex-start;
    }

    .input-with-btn .searchable-select {
        flex: 1;
    }

    .searchable-select {
        position: relative;
    }

    .searchable-select-display {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 14px;
        border: 1px solid var(--border-color);
        border-radius: 10px;
        background: var(--bg-secondary, var(--input-bg));
        color: var(--text-primary);
        cursor: pointer;
        min-height: 48px;
        transition: all 0.2s;
        font-size: 14px;
    }

    .searchable-select-display:hover {
        border-color: var(--accent);
    }

    .searchable-select.open .searchable-select-display {
        border-color: var(--accent);
        box-shadow: 0 0 0 3px rgba(var(--accent-rgb, 99, 102, 241), 0.15);
    }

    .searchable-select-text {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        flex: 1;
    }

    .searchable-select-text.placeholder {
        color: var(--text-secondary);
        opacity: 0.7;
    }

    .searchable-select-arrow {
        font-size: 11px;
        color: var(--text-secondary);
        transition: transform 0.2s;
        margin-left: 8px;
    }

    .searchable-select.open .searchable-select-arrow {
        transform: rotate(180deg);
    }

    .searchable-select-dropdown {
        display: none;
        position: absolute;
        top: calc(100% + 4px);
        left: 0;
        right: 0;
        background: var(--bg-primary, var(--card-bg));
        border: 1px solid var(--border-color);
        border-radius: 10px;
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
        z-index: 1000;
        overflow: hidden;
    }

    .searchable-select.open .searchable-select-dropdown {
        display: block;
        animation: searchSelectSlideDown 0.2s ease;
    }

    @keyframes searchSelectSlideDown {
        from {
            opacity: 0;
            transform: translateY(-8px);
        }

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

    .searchable-select-search {
        display: flex;
        align-items: center;
        padding: 10px 12px;
        border-bottom: 1px solid var(--border-color);
        gap: 8px;
        background: var(--bg-secondary, var(--input-bg));
    }

    .searchable-select-search i {
        color: var(--text-secondary);
        font-size: 13px;
    }

    .searchable-select-search input {
        border: none;
        outline: none;
        background: transparent;
        color: var(--text-primary);
        font-size: 14px;
        width: 100%;
        padding: 4px 0;
    }

    .searchable-select-options {
        max-height: 200px;
        overflow-y: auto;
        padding: 4px;
    }

    .searchable-select-option {
        padding: 10px 12px;
        cursor: pointer;
        border-radius: 6px;
        transition: background 0.15s;
        font-size: 14px;
        color: var(--text-primary);
    }

    .searchable-select-option:hover {
        background: var(--bg-secondary, rgba(0, 0, 0, 0.05));
    }

    .searchable-select-option.selected {
        background: var(--accent);
        color: white;
    }

    .searchable-select-option.hidden {
        display: none;
    }

    .searchable-select-options::-webkit-scrollbar {
        width: 6px;
    }

    .searchable-select-options::-webkit-scrollbar-track {
        background: transparent;
    }

    .searchable-select-options::-webkit-scrollbar-thumb {
        background: var(--border-color);
        border-radius: 3px;
    }

    .edit-input-row {
        display: flex;
        gap: 8px;
        align-items: flex-start;
    }

    .edit-quick-add-btn {
        width: 42px;
        height: 42px;
        border-radius: 10px;
        border: 2px solid var(--border-color);
        background: var(--input-bg);
        color: var(--accent);
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;
        flex-shrink: 0;
    }

    .edit-quick-add-btn:hover {
        background: var(--accent);
        color: #fff;
        border-color: var(--accent);
    }

    .edit-quick-form {
        margin-top: 8px;
        padding: 10px;
        background: var(--input-bg);
        border: 2px solid var(--accent);
        border-radius: 10px;
        animation: slideDown 0.2s ease;
    }

    .edit-quick-form input {
        margin-bottom: 8px;
    }

    .eq-actions {
        display: flex;
        gap: 6px;
    }

    .eq-save {
        flex: 1;
        padding: 6px 10px;
        border-radius: 6px;
        border: none;
        background: var(--accent);
        color: #fff;
        font-size: 12px;
        font-weight: 600;
        cursor: pointer;
    }

    .eq-cancel {
        padding: 6px 10px;
        border-radius: 6px;
        border: 2px solid var(--border-color);
        background: transparent;
        color: var(--text-secondary);
        cursor: pointer;
    }

    /* Product Search in Edit */
    .edit-product-search {
        position: relative;
        margin-bottom: 12px;
    }

    .edit-product-search input {
        width: 100%;
        padding: 10px 14px 10px 38px;
        border: 2px solid var(--border-color);
        border-radius: 10px;
        background: var(--input-bg);
        color: var(--text-primary);
        font-size: 14px;
    }

    .edit-product-search input:focus {
        border-color: var(--accent);
        outline: none;
    }

    .edit-product-search i {
        position: absolute;
        left: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: var(--text-secondary);
    }

    .edit-product-results {
        display: none;
        position: absolute;
        top: calc(100% + 4px);
        left: 0;
        right: 0;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
        z-index: 1000;
        max-height: 250px;
        overflow-y: auto;
    }

    .edit-product-results.show {
        display: block;
    }

    .epr-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px 14px;
        cursor: pointer;
        border-bottom: 1px solid var(--border-color);
        font-size: 14px;
    }

    .epr-item:hover {
        background: rgba(var(--accent-rgb), 0.08);
    }

    .epr-item img {
        width: 36px;
        height: 36px;
        border-radius: 6px;
        object-fit: cover;
        border: 1px solid var(--border-color);
    }

    .epr-item .epr-info {
        flex: 1;
    }

    .epr-item .epr-name {
        font-weight: 500;
    }

    .epr-item .epr-code {
        font-size: 12px;
        color: var(--text-secondary);
    }

    .epr-item .epr-price {
        font-weight: 700;
        color: var(--accent);
        white-space: nowrap;
    }

    /* Edit Items Table */
    .edit-items-table {
        width: 100%;
        border-collapse: collapse;
    }

    .edit-items-table th {
        background: var(--accent);
        color: #fff;
        padding: 10px 12px;
        text-align: left;
        font-size: 13px;
        font-weight: 600;
    }

    .edit-items-table td {
        padding: 8px 10px;
        border-bottom: 1px solid var(--border-color);
        font-size: 14px;
        vertical-align: middle;
    }

    .edit-items-table input[type="number"] {
        width: 80px;
        padding: 6px 8px;
        border: 1px solid var(--border-color);
        border-radius: 6px;
        background: var(--input-bg);
        color: var(--text-primary);
        font-size: 14px;
        text-align: right;
    }

    .edit-items-table input[type="number"]:focus {
        border-color: var(--accent);
        outline: none;
    }

    .edit-items-table .remove-item-btn {
        width: 28px;
        height: 28px;
        border-radius: 6px;
        border: none;
        background: rgba(220, 53, 69, 0.1);
        color: #dc3545;
        cursor: pointer;
        font-size: 12px;
    }

    .edit-items-table .remove-item-btn:hover {
        background: #dc3545;
        color: #fff;
    }

    /* Financial Summary Edit */
    .edit-summary {
        background: var(--input-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        padding: 16px;
        margin-top: 12px;
    }

    .edit-summary-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        font-size: 15px;
    }

    .edit-summary-row.total {
        font-size: 20px;
        font-weight: 700;
        color: #28a745;
        padding-top: 10px;
        border-top: 2px solid var(--border-color);
        margin-top: 10px;
    }

    .edit-summary-row .es-val {
        font-weight: 600;
    }

    .edit-discount-wrap {
        display: flex;
        align-items: center;
        gap: 6px;
    }

    .edit-discount-wrap input {
        width: 100px;
        padding: 6px 8px;
        border: 1px solid var(--border-color);
        border-radius: 6px;
        background: var(--input-bg);
        color: var(--text-primary);
        text-align: right;
        font-size: 14px;
    }

    .edit-discount-toggle {
        cursor: pointer;
        padding: 4px 10px;
        background: var(--border-color);
        border-radius: 6px;
        font-size: 14px;
        font-weight: 700;
        min-width: 30px;
        text-align: center;
        user-select: none;
    }

    .edit-discount-toggle:hover {
        background: var(--accent);
        color: #fff;
    }

    .edit-vat-wrap {
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .edit-vat-toggle {
        cursor: pointer;
        padding: 4px 10px;
        background: var(--border-color);
        border-radius: 6px;
        font-size: 13px;
        font-weight: 600;
        user-select: none;
    }

    .edit-vat-toggle.active {
        background: linear-gradient(135deg, #28a745, #20c997);
        color: #fff;
    }

    .edit-vat-wrap input {
        width: 80px;
        padding: 6px 8px;
        border: 1px solid var(--border-color);
        border-radius: 6px;
        background: var(--input-bg);
        color: var(--text-primary);
        text-align: right;
        font-size: 14px;
    }

    /* ======================================================
       ORDER DETAIL MODAL — Modern Redesign (.od-* classes)
       ====================================================== */

    /* Modal size override */
    .pro-modal-content.od-large {
        max-width: 960px;
    }

    /* --- Header Section --- */
    .od-header {
        display: flex;
        flex-wrap: wrap;
        align-items: flex-start;
        justify-content: space-between;
        gap: 12px;
        margin-bottom: 28px;
        padding-bottom: 20px;
        border-bottom: 1px solid var(--border-color);
    }

    .od-header-left {
        flex: 1;
        min-width: 200px;
    }

    .od-order-id {
        font-size: 30px;
        font-weight: 800;
        letter-spacing: -0.5px;
        color: var(--text-primary);
        line-height: 1.2;
    }

    .od-header-meta {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 8px;
        margin-top: 8px;
        font-size: 14px;
        color: var(--text-secondary);
    }

    .od-header-meta i {
        font-size: 14px;
    }

    .od-header-badges {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        align-items: flex-start;
    }

    /* --- Badges --- */
    .od-badge {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 6px 14px;
        border-radius: 20px;
        font-size: 14px;
        font-weight: 600;
        white-space: nowrap;
    }

    .od-badge i {
        font-size: 12px;
    }

    .od-badge-paid {
        background: rgba(40, 167, 69, .12);
        color: #28a745;
    }

    .od-badge-pending {
        background: rgba(255, 193, 7, .12);
        color: #e6a800;
    }

    .od-badge-partial {
        background: rgba(23, 162, 184, .12);
        color: #17a2b8;
    }

    .od-badge-refunded {
        background: rgba(220, 53, 69, .12);
        color: #dc3545;
    }

    .od-badge-currency {
        background: rgba(103, 58, 183, .1);
        color: #673ab7;
        font-size: 13px;
        padding: 4px 12px;
    }

    .od-badge-type {
        background: rgba(255, 152, 0, .1);
        color: #ff9800;
        font-size: 13px;
        padding: 4px 12px;
    }

    /* --- Cards --- */
    .od-card {
        background: var(--card-bg);
        border-radius: 12px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06), 0 1px 2px rgba(0, 0, 0, 0.04);
        padding: 20px 24px;
        margin-bottom: 20px;
        border: 1px solid var(--border-color);
    }

    .od-card-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: 700;
        color: var(--text-primary);
        margin: 0 0 16px 0;
        text-transform: uppercase;
        letter-spacing: 0.3px;
    }

    .od-card-title i {
        color: var(--accent, #4a90d9);
        font-size: 15px;
    }

    /* --- 2-column grid --- */
    .od-grid-2col {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
        margin-bottom: 20px;
    }

    /* --- Info rows inside cards --- */
    .od-info-row {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        padding: 8px 0;
        font-size: 15px;
        border-bottom: 1px solid var(--border-color);
    }

    .od-info-row:last-child {
        border-bottom: none;
    }

    .od-info-label {
        color: var(--text-secondary);
        font-weight: 500;
        flex-shrink: 0;
        margin-right: 12px;
    }

    .od-info-value {
        color: var(--text-primary);
        font-weight: 600;
        text-align: right;
        word-break: break-word;
    }

    /* --- Step Progress --- */
    .od-step-progress {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 0;
        padding: 8px 0 0 0;
        position: relative;
    }

    .od-step {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 1;
        position: relative;
        text-align: center;
        z-index: 1;
    }

    .od-step-circle {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 15px;
        font-weight: 700;
        margin-bottom: 8px;
        transition: all .3s;
        position: relative;
        z-index: 2;
    }

    .od-step.done .od-step-circle {
        background: #28a745;
        color: #fff;
        box-shadow: 0 2px 8px rgba(40, 167, 69, 0.3);
    }

    .od-step.active .od-step-circle {
        background: #dc3545;
        color: #fff;
        box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3);
        animation: od-pulse 2s infinite;
    }

    @keyframes od-pulse {

        0%,
        100% {
            box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3);
        }

        50% {
            box-shadow: 0 2px 16px rgba(220, 53, 69, 0.5);
        }
    }

    .od-step.pending .od-step-circle {
        background: var(--border-color);
        color: var(--text-secondary);
    }

    .od-step-label {
        font-size: 13px;
        font-weight: 600;
        color: var(--text-secondary);
        line-height: 1.3;
        max-width: 100px;
    }

    .od-step.done .od-step-label {
        color: #28a745;
    }

    .od-step.active .od-step-label {
        color: #dc3545;
    }

    .od-step-date {
        font-size: 11px;
        color: var(--text-secondary);
        margin-top: 2px;
    }

    /* Connecting line between steps */
    .od-step::after {
        content: '';
        position: absolute;
        top: 20px;
        left: calc(50% + 20px);
        width: calc(100% - 40px);
        height: 3px;
        background: var(--border-color);
        z-index: 0;
    }

    .od-step:last-child::after {
        display: none;
    }

    .od-step.done::after {
        background: #28a745;
    }

    .od-step.active::after {
        background: linear-gradient(90deg, #dc3545 50%, var(--border-color) 50%);
    }

    /* --- Product Table --- */
    .od-product-table {
        width: 100%;
        border-collapse: collapse;
    }

    .od-product-table th {
        background: var(--input-bg);
        padding: 12px 14px;
        text-align: left;
        font-size: 14px;
        font-weight: 700;
        color: var(--text-secondary);
        text-transform: uppercase;
        letter-spacing: 0.3px;
        border-bottom: 2px solid var(--border-color);
    }

    .od-product-table td {
        padding: 12px 14px;
        border-bottom: 1px solid var(--border-color);
        font-size: 15px;
        vertical-align: middle;
    }

    .od-product-table tbody tr:hover {
        background: var(--input-bg);
    }

    .od-product-table .text-right {
        text-align: right;
    }

    .od-product-table .text-center {
        text-align: center;
    }

    .od-product-table .fw-bold {
        font-weight: 700;
    }

    .od-product-img {
        width: 40px;
        height: 40px;
        border-radius: 8px;
        object-fit: cover;
        border: 1px solid var(--border-color);
        flex-shrink: 0;
    }

    .od-product-placeholder {
        width: 40px;
        height: 40px;
        border-radius: 8px;
        background: var(--input-bg);
        border: 1px solid var(--border-color);
        display: flex;
        align-items: center;
        justify-content: center;
        color: #ccc;
        flex-shrink: 0;
    }

    .od-product-cell {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .od-product-name {
        font-weight: 500;
        font-size: 15px;
        line-height: 1.4;
    }

    /* --- Summary Section --- */
    .od-summary {
        background: var(--card-bg);
        border-radius: 12px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
        border: 1px solid var(--border-color);
        padding: 20px 24px;
        margin-top: 20px;
    }

    .od-summary-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;
        font-size: 16px;
    }

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

    .od-summary-value {
        font-weight: 600;
        color: var(--text-primary);
    }

    .od-summary-value.discount {
        color: #dc3545;
    }

    .od-summary-total {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 12px;
        padding: 16px 20px;
        background: rgba(40, 167, 69, 0.08);
        border-radius: 10px;
        border: 1px solid rgba(40, 167, 69, 0.2);
    }

    .od-summary-total-label {
        font-size: 20px;
        font-weight: 700;
        color: #28a745;
    }

    .od-summary-total-value {
        font-size: 28px;
        font-weight: 800;
        color: #28a745;
    }

    /* --- Slip Section --- */
    .od-slip-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        justify-content: center;
    }

    .od-slip-img {
        max-width: 180px;
        max-height: 180px;
        border-radius: 10px;
        cursor: pointer;
        border: 1px solid var(--border-color);
        transition: transform .2s, box-shadow .2s;
        object-fit: cover;
    }

    .od-slip-img:hover {
        transform: scale(1.03);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
    }

    .od-slip-empty {
        text-align: center;
        padding: 24px;
        color: var(--text-secondary);
        font-size: 15px;
    }

    .od-slip-empty i {
        font-size: 36px;
        opacity: 0.25;
        display: block;
        margin-bottom: 8px;
    }

    /* --- Currency Conversion Box --- */
    .od-currency-box {
        display: flex;
        align-items: stretch;
        gap: 0;
        flex-wrap: wrap;
        margin-top: 12px;
    }

    .od-cur-panel {
        flex: 1;
        min-width: 160px;
        padding: 16px;
        text-align: center;
        border-radius: 12px;
    }

    .od-cur-panel.foreign {
        background: linear-gradient(135deg, rgba(255, 152, 0, 0.08), rgba(255, 193, 7, 0.05));
        border: 1px solid rgba(255, 152, 0, 0.2);
    }

    .od-cur-panel.lak {
        background: linear-gradient(135deg, rgba(40, 167, 69, 0.08), rgba(32, 201, 151, 0.05));
        border: 1px solid rgba(40, 167, 69, 0.2);
    }

    .od-cur-panel .od-cur-title {
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 0.8px;
        font-weight: 700;
        margin-bottom: 8px;
    }

    .od-cur-panel.foreign .od-cur-title {
        color: #ff9800;
    }

    .od-cur-panel.lak .od-cur-title {
        color: #28a745;
    }

    .od-cur-panel .od-cur-amount {
        font-size: 22px;
        font-weight: 800;
    }

    .od-cur-panel.foreign .od-cur-amount {
        color: #ff9800;
    }

    .od-cur-panel.lak .od-cur-amount {
        color: #28a745;
    }

    .od-cur-arrow {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 0 14px;
        min-width: 80px;
    }

    .od-cur-rate-badge {
        background: linear-gradient(135deg, #673ab7, #9c27b0);
        color: #fff;
        padding: 8px 18px;
        border-radius: 20px;
        font-weight: 800;
        font-size: 16px;
        box-shadow: 0 2px 8px rgba(103, 58, 183, 0.25);
    }

    .od-cur-arrow i {
        margin-top: 6px;
        color: #673ab7;
        font-size: 20px;
    }

    /* --- Notes --- */
    .od-notes {
        margin-top: 16px;
        padding: 14px 18px;
        background: rgba(33, 150, 243, 0.06);
        border: 1px solid rgba(33, 150, 243, 0.15);
        border-radius: 10px;
        color: #1976d2;
        font-size: 15px;
    }

    .od-notes i {
        margin-right: 6px;
    }

    /* --- Edit modal specific --- */
    .od-edit-status-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 12px;
    }

    .od-edit-status-item {
        text-align: center;
        padding: 12px;
        background: var(--input-bg);
        border-radius: 10px;
        border: 1px solid var(--border-color);
    }

    .od-edit-status-item label {
        display: block;
        font-size: 14px;
        font-weight: 700;
        color: var(--text-primary);
        margin-bottom: 8px;
    }

    .od-edit-status-item select {
        width: 100%;
        padding: 6px 8px;
        font-size: 13px;
        border-radius: 8px;
        border: 1px solid var(--border-color);
        background: var(--card-bg);
        color: var(--text-primary);
    }

    .od-edit-status-item.done {
        background: rgba(40, 167, 69, 0.1);
        border-color: rgba(40, 167, 69, 0.35);
    }

    .od-edit-status-item.done label {
        color: #28a745;
    }

    .od-edit-status-item.done select {
        border-color: rgba(40, 167, 69, 0.4);
        color: #28a745;
        font-weight: 600;
    }

    .od-edit-status-item.not-done {
        background: rgba(220, 53, 69, 0.1);
        border-color: rgba(220, 53, 69, 0.35);
    }

    .od-edit-status-item.not-done label {
        color: #dc3545;
    }

    .od-edit-status-item.not-done select {
        border-color: rgba(220, 53, 69, 0.4);
        color: #dc3545;
        font-weight: 600;
    }

    /* --- Section Separator --- */
    .od-section-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: 700;
        color: var(--text-primary);
        margin: 24px 0 14px 0;
        text-transform: uppercase;
        letter-spacing: 0.3px;
    }

    .od-section-title i {
        color: var(--accent, #4a90d9);
        font-size: 15px;
    }

    /* --- Responsive --- */
    @media (max-width: 768px) {
        .od-grid-2col {
            grid-template-columns: 1fr;
        }

        .od-step-progress {
            flex-direction: column;
            align-items: flex-start;
            gap: 0;
        }

        .od-step {
            flex-direction: row;
            align-items: center;
            text-align: left;
            gap: 12px;
            padding: 8px 0;
        }

        .od-step::after {
            top: auto;
            left: 18px;
            width: 3px;
            height: calc(100%);
            top: 36px;
        }

        .od-step:last-child::after {
            display: none;
        }

        .od-step-circle {
            margin-bottom: 0;
        }

        .od-step-label {
            max-width: none;
        }

        .od-header {
            flex-direction: column;
        }

        .od-order-id {
            font-size: 22px;
        }

        .od-summary-total-value {
            font-size: 20px;
        }

        .od-currency-box {
            flex-direction: column;
            gap: 12px;
        }

        .od-cur-arrow {
            flex-direction: row;
            padding: 8px 0;
        }

        .od-cur-arrow i {
            margin-top: 0;
            margin-left: 8px;
            transform: rotate(90deg);
        }

        .od-edit-status-grid {
            grid-template-columns: 1fr 1fr;
        }
    }

    @media (max-width: 480px) {
        .od-edit-status-grid {
            grid-template-columns: 1fr;
        }

        .od-card {
            padding: 16px;
        }
    }
</style>

<div class="page-header">
    <h1><i class="fas fa-history"></i> ປະຫວັດການຂາຍ</h1>
</div>

<div class="filter-card">
    <div class="filter-row">
        <div class="search-box">
            <i class="fas fa-search"></i>
            <input type="text" id="search-input" placeholder="ຄົ້ນຫາໃບບິນ, ລູກຄ້າ, ເບີໂທ...">
        </div>

        <!-- User Multi-Select Filter -->
        <div class="user-filter-wrapper" id="user-filter-wrapper">
            <button class="user-filter-btn" type="button" onclick="toggleUserFilter()">
                <span><i class="fas fa-users" style="margin-right:6px"></i> ພະນັກງານ <span id="user-filter-count"
                        class="user-filter-count">0</span></span>
                <i class="fas fa-chevron-down" style="font-size:12px; opacity:0.7"></i>
            </button>
            <div class="user-filter-dropdown" id="user-filter-dropdown">
                <label class="user-filter-item">
                    <input type="checkbox" id="user-filter-all" onchange="toggleAllUsers(this)" checked>
                    <strong>ທັງໝົດ (All)</strong>
                </label>
                <hr style="border-top:1px solid var(--border-color); margin:4px 0;">
                <?php foreach ($users_list as $u): ?>
                        <label class="user-filter-item">
                            <input type="checkbox" class="user-filter-checkbox" value="<?= htmlspecialchars($u['user_id']) ?>"
                                onchange="updateUserFilterSelection()">
                            <?= htmlspecialchars($u['name']) ?>
                        </label>
                <?php endforeach; ?>
            </div>
        </div>

        <input type="date" id="date-from" class="date-input" value="<?= date('Y-m-d') ?>">
        <span style="color:var(--text-secondary)">ຫາ</span>
        <input type="date" id="date-to" class="date-input" value="<?= date('Y-m-d') ?>">
        <button type="button" class="btn-pro primary" onclick="loadTablePage(1)">
            <i class="fas fa-filter"></i> ກັ່ນຕອງ
        </button>
        <button type="button" class="btn-reset" onclick="resetFilter()">
            <i class="fas fa-undo"></i> ລ້າງ
        </button>
    </div>
</div>

<div class="data-card">
    <div class="data-card-header">
        <h3><i class="fas fa-table"></i> ຕາຕະລາງການຂາຍ</h3>
        <div style="display:flex;gap:10px;align-items:center">
            <button type="button" id="toggle-bulk-select" class="btn-pro secondary">
                <i class="fas fa-check-square"></i> ເລືອກຫຼາຍລາຍການ
            </button>
            <div class="bulk-actions" id="bulk-actions">
                <button id="print-selected" class="btn-pro success" disabled>
                    <i class="fas fa-print"></i> ພິມທີ່ເລືອກ
                </button>
                <button id="cancel-selection" class="btn-pro secondary">
                    <i class="fas fa-times"></i> ຍົກເລີກ
                </button>
            </div>
        </div>
    </div>

    <div style="overflow-x:auto">
        <table class="pro-table">
            <thead>
                <tr>
                    <th class="bulk-checkbox" id="bulk-header"><input type="checkbox" id="select-all"></th>
                    <th>ລຳດັບ</th>
                    <th>ເລກບິນ POS</th>
                    <th>ເລກທີໃບບິນ</th>
                    <th>ວັນທີ</th>
                    <th>ລູກຄ້າ</th>
                    <th>ເບີໂທ</th>
                    <th>ບໍລິສັດຂົນສົ່ງ</th>
                    <th>ສາຂາຂົນສົ່ງ</th>
                    <th>ສະຖານະ</th>
                    <th>Print</th>
                    <th>ຍອດລວມ</th>
                    <th>ຈັດການ</th>
                </tr>
            </thead>
            <tbody id="sales-table-body">
                <tr>
                    <td colspan="14" class="loading-state" style="text-align:center;padding:40px;"><i
                            class="fas fa-spinner fa-spin"></i> ກຳລັງໂຫຼດຂໍ້ມູນ...</td>
                </tr>
            </tbody>
        </table>
    </div>
    <div id="pagination" class="pagination-wrap"></div>
</div>

<!-- Details Modal -->
<div class="pro-modal" id="order-modal">
    <div class="pro-modal-content od-large">
        <div class="pro-modal-header">
            <h3><i class="fas fa-file-invoice"></i> <span id="modal-title">ລາຍລະອຽດໃບບິນ</span></h3>
            <button class="pro-modal-close" onclick="closeModal('order-modal')">&times;</button>
        </div>
        <div class="pro-modal-body" id="order-details"></div>
    </div>
</div>

<!-- Edit Modal (Comprehensive - Modern Redesign) -->
<div class="pro-modal" id="edit-modal">
    <div class="pro-modal-content od-large">
        <div class="pro-modal-header">
            <h3><i class="fas fa-edit"></i> <span id="edit-modal-title">ແກ້ໄຂໃບບິນ</span></h3>
            <button class="pro-modal-close" onclick="closeModal('edit-modal')">&times;</button>
        </div>
        <div class="pro-modal-body">
            <input type="hidden" id="edit-order-id">
            <input type="hidden" id="edit-order-internal-id">

            <!-- 1) HEADER (readonly) -->
            <div class="od-header">
                <div class="od-header-left">
                    <div class="od-order-id" id="edit-or-id-display2"></div>
                    <div class="od-header-meta">
                        <i class="far fa-calendar-alt"></i> <span id="edit-created-at">-</span>
                        <span style="color:#ddd">|</span>
                        <i class="fas fa-user"></i> <span id="edit-created-by">-</span>
                        <span style="color:#ddd">|</span>
                        <span id="edit-order-type-display2">-</span>
                    </div>
                </div>
            </div>

            <!-- 2) ORDER INFO + CUSTOMER/SHIPPING (2 columns) -->
            <div class="od-grid-2col">
                <!-- Left: Order Info (editable) -->
                <div class="od-card">
                    <div class="od-card-title"><i class="fas fa-file-alt"></i> ຂໍ້ມູນອໍເດີ</div>
                    <div class="edit-form-group">
                        <label>ສະຖານະຈ່າຍ</label>
                        <select id="edit-payment-status" class="form-pro-input" onchange="editPaymentStatusChange()">
                            <option value="pending">ຍັງບໍ່ຈ່າຍ</option>
                            <option value="partial">ມັດຈຳ</option>
                            <option value="paid">ຈ່າຍແລ້ວ</option>
                        </select>
                    </div>
                    <div class="edit-form-group">
                        <label>ວິທີຊຳລະ</label>
                        <select id="edit-payment-method" class="form-pro-input">
                            <option value="">- ເລືອກ -</option>
                            <option value="cash">ເງິນສົດ</option>
                            <option value="transfer">ໂອນ</option>
                        </select>
                    </div>
                    <div class="edit-form-group" id="edit-deposit-group" style="display:none">
                        <label>ຈຳນວນມັດຈຳ</label>
                        <input type="number" id="edit-deposit-amount" class="form-pro-input" placeholder="0">
                    </div>
                    <div class="edit-form-group">
                        <label>ເລກບິນ POS ໜ້າຮ້ານ</label>
                        <input type="text" id="edit-bill-number" class="form-pro-input" placeholder="ເລກບິນ">
                    </div>
                    <input type="hidden" id="edit-shipping-date">
                    <div class="edit-form-group">
                        <label>ຄ່າຝາກ</label>
                        <select id="edit-notes" class="form-pro-input">
                            <option value="">-- ເລືອກຄ່າຝາກ --</option>
                            <option value="ຕົ້ນທາງ">ຕົ້ນທາງ</option>
                            <option value="ປາຍທາງ">ປາຍທາງ</option>
                        </select>
                    </div>
                </div>

                <!-- Right: Customer & Shipping (editable) -->
                <div class="od-card">
                    <div class="od-card-title"><i class="fas fa-user"></i> ຂໍ້ມູນລູກຄ້າ</div>
                    <div class="edit-form-group">
                        <label>ເລືອກລູກຄ້າ</label>
                        <div class="input-with-btn">
                            <div class="searchable-select" id="editCustomerWrapper">
                                <div class="searchable-select-display"
                                    onclick="editToggleSearchable('editCustomerWrapper')">
                                    <span class="searchable-select-text placeholder"
                                        data-placeholder="ເລືອກລູກຄ້າ">ເລືອກລູກຄ້າ</span>
                                    <i class="fas fa-chevron-down searchable-select-arrow"></i>
                                </div>
                                <div class="searchable-select-dropdown">
                                    <div class="searchable-select-search">
                                        <i class="fas fa-search"></i>
                                        <input type="text" placeholder="ຄົ້ນຫາລູກຄ້າ..."
                                            oninput="editFilterSearchable('editCustomerWrapper', this.value)">
                                    </div>
                                    <div class="searchable-select-options" id="editCustomerOptions">
                                        <div class="searchable-select-option" data-value=""
                                            onclick="editSelectOption('editCustomerWrapper', '', 'ເລືອກລູກຄ້າ')">
                                            ເລືອກລູກຄ້າ</div>
                                    </div>
                                </div>
                                <input type="hidden" id="editCustomerId">
                                <input type="hidden" id="editCustomerCuId">
                            </div>
                            <button type="button" class="edit-quick-add-btn" onclick="toggleEditQuickAdd('customer')"
                                title="ເພີ່ມລູກຄ້າໃໝ່"><i class="fas fa-plus"></i></button>
                        </div>
                    </div>
                    <div id="editQuickCustomerForm" class="edit-quick-form" style="display:none">
                        <input type="text" id="eqNewCustName" class="form-pro-input" placeholder="ຊື່ລູກຄ້າ">
                        <input type="text" id="eqNewCustPhone" class="form-pro-input" placeholder="ເບີໂທ">
                        <div class="eq-actions">
                            <button type="button" class="eq-save" onclick="editSaveQuickCustomer()"><i
                                    class="fas fa-check"></i> ບັນທຶກ</button>
                            <button type="button" class="eq-cancel" onclick="toggleEditQuickAdd('customer')"><i
                                    class="fas fa-times"></i></button>
                        </div>
                    </div>

                    <div class="od-card-title" style="margin-top:16px"><i class="fas fa-truck"></i> ການຂົນສົ່ງ</div>
                    <div class="edit-form-group">
                        <label>ບໍລິສັດ</label>
                        <div class="input-with-btn">
                            <div class="searchable-select" id="editCompanyWrapper">
                                <div class="searchable-select-display"
                                    onclick="editToggleSearchable('editCompanyWrapper')">
                                    <span class="searchable-select-text placeholder"
                                        data-placeholder="ເລືອກບໍລິສັດ">ເລືອກບໍລິສັດ</span>
                                    <i class="fas fa-chevron-down searchable-select-arrow"></i>
                                </div>
                                <div class="searchable-select-dropdown">
                                    <div class="searchable-select-search">
                                        <i class="fas fa-search"></i>
                                        <input type="text" placeholder="ຄົ້ນຫາບໍລິສັດ..."
                                            oninput="editFilterSearchable('editCompanyWrapper', this.value)">
                                    </div>
                                    <div class="searchable-select-options" id="editCompanyOptions">
                                        <div class="searchable-select-option" data-value=""
                                            onclick="editSelectOption('editCompanyWrapper', '', 'ເລືອກບໍລິສັດ')">
                                            ເລືອກບໍລິສັດ</div>
                                    </div>
                                </div>
                                <input type="hidden" id="editCompanyId">
                                <input type="hidden" id="editCompanyScId">
                            </div>
                            <button type="button" class="edit-quick-add-btn" onclick="toggleEditQuickAdd('company')"
                                title="ເພີ່ມບໍລິສັດໃໝ່"><i class="fas fa-plus"></i></button>
                        </div>
                    </div>
                    <div id="editQuickCompanyForm" class="edit-quick-form" style="display:none">
                        <input type="text" id="eqNewCompanyName" class="form-pro-input" placeholder="ຊື່ບໍລິສັດໃໝ່">
                        <div class="eq-actions">
                            <button type="button" class="eq-save" onclick="editSaveQuickCompany()"><i
                                    class="fas fa-check"></i> ບັນທຶກ</button>
                            <button type="button" class="eq-cancel" onclick="toggleEditQuickAdd('company')"><i
                                    class="fas fa-times"></i></button>
                        </div>
                    </div>

                    <div class="edit-form-group" style="margin-top:12px">
                        <label>ສາຂາ</label>
                        <div class="input-with-btn">
                            <div class="searchable-select" id="editBranchWrapper">
                                <div class="searchable-select-display"
                                    onclick="editToggleSearchable('editBranchWrapper')">
                                    <span class="searchable-select-text placeholder"
                                        data-placeholder="ເລືອກສາຂາ">ເລືອກສາຂາ</span>
                                    <i class="fas fa-chevron-down searchable-select-arrow"></i>
                                </div>
                                <div class="searchable-select-dropdown">
                                    <div class="searchable-select-search">
                                        <i class="fas fa-search"></i>
                                        <input type="text" placeholder="ຄົ້ນຫາສາຂາ..."
                                            oninput="editFilterSearchable('editBranchWrapper', this.value)">
                                    </div>
                                    <div class="searchable-select-options" id="editBranchOptions">
                                        <div class="searchable-select-option" data-value=""
                                            onclick="editSelectOption('editBranchWrapper', '', 'ເລືອກສາຂາ')">ເລືອກສາຂາ
                                        </div>
                                    </div>
                                </div>



                                <input type="hidden" id="editBranchId">
                                <input type="hidden" id="editBranchSbId">
                            </div>
                            <button type="button" class="edit-quick-add-btn" onclick="toggleEditQuickAdd('branch')"
                                title="ເພີ່ມສາຂາໃໝ່"><i class="fas fa-plus"></i></button>
                        </div>
                    </div>
                    <div id="editQuickBranchForm" class="edit-quick-form" style="display:none">
                        <input type="text" id="eqNewBranchName" class="form-pro-input" placeholder="ຊື່ສາຂາໃໝ່">
                        <div class="eq-actions">
                            <button type="button" class="eq-save" onclick="editSaveQuickBranch()"><i
                                    class="fas fa-check"></i> ບັນທຶກ</button>
                            <button type="button" class="eq-cancel" onclick="toggleEditQuickAdd('branch')"><i
                                    class="fas fa-times"></i></button>
                        </div>
                    </div>

                    <div class="edit-form-group" style="margin-top:12px">
                        <label>ເລກໃບບິນຂົນສົ່ງ</label>
                        <input type="text" id="edit-bill-transport" class="form-pro-input" placeholder="ເລກໃບບິນ">
                    </div>
                </div>
            </div>

            <!-- 3) CURRENCY & SLIP -->
            <div class="od-grid-2col">
                <div class="od-card">
                    <div class="od-card-title"><i class="fas fa-coins"></i> ສະກຸນເງິນ & ພາສີ</div>
                    <div class="edit-form-group">
                        <label>ສະກຸນເງິນ</label>
                        <select id="editCurrencySelect" class="form-pro-input">
                            <?php foreach ($currencies as $cur): ?>
                                    <option value="<?= $cur['currencys_id'] ?>"
                                        data-symbol="<?= $cur['currencys_symbol'] ?? '₭' ?>"
                                        data-rate="<?= $cur['rate_amount'] ?? 1 ?>" data-rate-id="<?= $cur['rate_id'] ?? '' ?>"
                                        data-name="<?= htmlspecialchars($cur['currencys_name']) ?>" <?= ($cur['base_currency'] ?? '') === 'YES' ? 'selected' : '' ?>>
                                        <?= $cur['currencys_symbol'] ?? '₭' ?>         <?= htmlspecialchars($cur['currencys_name']) ?>
                                    </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="od-info-row" style="margin-top:8px">
                        <span class="od-info-label">ອັດຕາແລກປ່ຽນ</span>
                        <span class="od-info-value" id="edit-rate-display">-</span>
                    </div>
                </div>
                <div class="od-card">
                    <div class="od-card-title"><i class="fas fa-image"></i> ຫຼັກຖານການໂອນ</div>
                    <input type="file" id="edit-slip-image" accept="image/*" multiple style="display:none"
                        onchange="editAddNewSlips()">
                    <button type="button" class="btn-pro secondary"
                        onclick="document.getElementById('edit-slip-image').click()"
                        style="margin-bottom:12px;font-size:14px">
                        <i class="fas fa-plus"></i> ເພີ່ມຮູບ
                    </button>
                    <span style="font-size:13px;color:var(--text-secondary);margin-left:8px;">(ຫຼື Ctrl+V
                        ວາງຮູບໃນຂອບນີ້)</span>
                    <span id="edit-slip-count"
                        style="margin-left:8px;font-size:13px;color:var(--text-secondary)"></span>

                    <!-- Paste & Drop Zone -->
                    <div id="edit-slip-dropzone" tabindex="0"
                        style="outline:none;position:relative;min-height:100px;border:2px dashed var(--border-color);border-radius:12px;padding:16px;transition:all 0.2s;"
                        onmouseover="this.focus()" onfocus="this.style.borderColor='var(--accent)'"
                        onblur="this.style.borderColor='var(--border-color)'">

                        <!-- Invisible paste catcher to guarantee focus interception on some browsers -->
                        <div id="edit-slip-preview" class="od-slip-empty">
                            <i class="fas fa-image"></i>
                            ບໍ່ມີຫຼັກຖານການໂອນ<br>
                            <span style="font-size:12px;opacity:0.7;">(ຄລິກທີ່ນີ້ແລ້ວກົດ Paste)</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 4) STATUS TRACKING -->
            <div class="od-card">
                <div class="od-card-title"><i class="fas fa-tasks"></i> ສະຖານະການດຳເນີນງານ</div>
                <div class="od-edit-status-grid">

                    <div class="od-edit-status-item">
                        <label>ການຈັດເຄື່ອງ</label>
                        <select id="edit-prepare-status" onchange="editUpdateStatusStyle()">
                            <option value="ຍັງບໍ່ຈັດເຄື່ອງ">ຍັງບໍ່ຈັດເຄື່ອງ</option>
                            <option value="ຈັດເຄື່ອງແລ້ວ">ຈັດເຄື່ອງແລ້ວ</option>
                        </select>
                    </div>
                    <div class="od-edit-status-item">
                        <label>ຄີເຄື່ອງໜ້າຮ້ານ</label>
                        <select id="edit-front-stock" onchange="editUpdateStatusStyle()">
                            <option value="ຍັງບໍ່ຄີ">ຍັງບໍ່ຄີ</option>
                            <option value="ຄີແລ້ວ">ຄີແລ້ວ</option>
                        </select>
                    </div>
                    <div class="od-edit-status-item">
                        <label>ການແພັກເຄື່ອງ</label>
                        <select id="edit-pack-status" onchange="editUpdateStatusStyle()">
                            <option value="ຍັງບໍ່ໄດ້ແພັກ">ຍັງບໍ່ໄດ້ແພັກ</option>
                            <option value="ແພັກແລ້ວ">ແພັກແລ້ວ</option>
                        </select>
                    </div>
                    <div class="od-edit-status-item">
                        <label>ເຄື່ອງອອກ</label>
                        <select id="edit-shipping-status"
                            onchange="handleShippingStatusChange(); editUpdateStatusStyle()">
                            <option value="ເຄື່ອງຍັງບໍ່ອອກ">ເຄື່ອງຍັງບໍ່ອອກ</option>
                            <option value="ເຄື່ອງອອກແລ້ວ">ເຄື່ອງອອກແລ້ວ</option>
                        </select>
                        <div id="edit-shipping-date-display"
                            style="font-size:11px;color:var(--text-secondary);margin-top:4px;display:none;">
                            ວັນທີ: <span id="edit-shipping-date-text"></span>
                        </div>
                    </div>
                    <div class="od-edit-status-item">
                        <label>ການແຈ້ງບິນຮ້ານ</label>
                        <select id="edit-shop-bill" onchange="editUpdateStatusStyle()">
                            <option value="ຍັງບໍ່ແຈ້ງ">ຍັງບໍ່ແຈ້ງ</option>
                            <option value="ແຈ້ງບິນແລ້ວ">ແຈ້ງແລ້ວ</option>
                        </select>
                    </div>
                    <div class="od-edit-status-item">
                        <label>ການແຈ້ງບິນຂົນສົ່ງ</label>
                        <select id="edit-transport-bill" onchange="editUpdateStatusStyle()">
                            <option value="ຍັງບໍ່ແຈ້ງ">ຍັງບໍ່ແຈ້ງ</option>
                            <option value="ແຈ້ງບິນແລ້ວ">ແຈ້ງແລ້ວ</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- 5) PRODUCTS TABLE -->
            <div class="od-section-title"><i class="fas fa-box-open"></i> ລາຍການສິນຄ້າ</div>
            <div class="edit-product-search">
                <i class="fas fa-search"></i>
                <input type="text" id="editProductSearch" placeholder="ຄົ້ນຫາສິນຄ້າ (ຊື່, ບາໂຄດ, ລະຫັດ)..."
                    autocomplete="off">
                <div class="edit-product-results" id="editProductResults"></div>
            </div>
            <div style="overflow-x:auto">
                <table class="od-product-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>ບາໂຄດ</th>
                            <th>ຮູບພາບ ແລະ ຊື່ສິນຄ້າ</th>
                            <th class="text-right">ລາຄາ</th>
                            <th class="text-center">ຈຳນວນ</th>
                            <th class="text-right">ລວມ</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody id="editItemsBody"></tbody>
                </table>
            </div>

            <!-- 6) FINANCIAL SUMMARY -->
            <div class="od-summary">
                <div class="od-summary-row"><span class="od-summary-label">ລວມ</span> <span class="od-summary-value"
                        id="editSubtotal">0</span></div>
                <div class="od-summary-row">
                    <span class="od-summary-label">ສ່ວນຫຼຸດ</span>
                    <div class="edit-discount-wrap">
                        <input type="number" id="editDiscountAmount" value="0" min="0" oninput="editRecalculate()">
                        <span class="edit-discount-toggle" id="editDiscountToggle"
                            onclick="editToggleDiscountType()">₭</span>
                    </div>
                </div>
                <div class="od-summary-row" style="align-items:center">
                    <span class="od-summary-label">VAT</span>
                    <div class="edit-vat-wrap" style="justify-content:flex-end">
                        <span class="edit-vat-toggle" id="editVatToggle" onclick="editToggleVAT()"><i
                                class="fas fa-percent"></i> VAT</span>
                        <input type="number" id="editVatPercent" class="form-pro-input" value="10" min="0" step="0.1"
                            style="width:80px" oninput="editRecalculate()">
                        <span style="color:var(--text-secondary)">%</span>
                    </div>
                </div>
                <div class="od-summary-row" id="editVatRow" style="display:none">
                    <span class="od-summary-label">VAT (<span id="editVatLabel">10</span>%)</span>
                    <span class="od-summary-value" id="editVatAmount">0</span>
                </div>
                <div class="od-summary-total">
                    <span class="od-summary-total-label">ລວມທັງໝົດ</span>
                    <span class="od-summary-total-value" id="editGrandTotal">0</span>
                </div>
            </div>

            <!-- Notes -->
            <div class="od-notes" id="edit-notes-section">
                <i class="fas fa-comment"></i> <strong>ໝາຍເຫດ:</strong> <span id="edit-notes-display">-</span>
            </div>
        </div>

        <div class="pro-modal-footer"
            style="padding:20px 24px;border-top:1px solid var(--border-color);display:flex;justify-content:flex-end;gap:12px">
            <button type="button" class="btn-pro secondary" onclick="closeModal('edit-modal')">ຍົກເລີກ</button>
            <button type="button" class="btn-pro primary" onclick="editSaveOrder()"><i class="fas fa-save"></i>
                ບັນທຶກ</button>
        </div>
    </div>
</div>


<!-- Delete Modal -->
<div class="pro-modal" id="delete-modal">
    <div class="pro-modal-content small">
        <div class="pro-modal-header">
            <h3 style="color:#dc3545"><i class="fas fa-exclamation-triangle"></i> ຢືນຢັນການລົບ</h3>
            <button class="pro-modal-close" onclick="closeModal('delete-modal')">&times;</button>
        </div>
        <div class="pro-modal-body">
            <div style="text-align:center;padding:20px 0">
                <i class="fas fa-trash-alt" style="font-size:48px;color:#dc3545;margin-bottom:16px"></i>
                <h4 style="margin:0 0 12px 0;font-size:20px">ລຶບໃບບິນນີ້?</h4>
                <p style="color:var(--text-secondary);margin-bottom:20px">ກະລຸນາປ້ອນລະຫັດຜ່ານເພື່ອຢືນຢັນ</p>
                <input type="password" id="delete-password" class="form-pro-input" placeholder="ລະຫັດຜ່ານ">
                <input type="hidden" id="delete-order-id">
            </div>
            <div style="display:flex;justify-content:flex-end;gap:12px">
                <button type="button" class="btn-pro secondary" onclick="closeModal('delete-modal')">ຍົກເລີກ</button>
                <button type="button" id="confirm-delete-btn" class="btn-pro"
                    style="background:#dc3545;color:#fff">ລົບ</button>
            </div>
        </div>
    </div>
</div>

<script>
    // ========== USER FILTER LOGIC ==========
    function toggleUserFilter() {
        document.getElementById('user-filter-dropdown').classList.toggle('show');
    }

    // Close dropdown when clicking outside
    document.addEventListener('click', function (event) {
        const wrapper = document.getElementById('user-filter-wrapper');
        const dropdown = document.getElementById('user-filter-dropdown');
        if (wrapper && dropdown && !wrapper.contains(event.target)) {
            dropdown.classList.remove('show');
        }
    });

    function toggleAllUsers(checkbox) {
        const cbs = document.querySelectorAll('.user-filter-checkbox');
        if (checkbox.checked) {
            cbs.forEach(cb => cb.checked = false);
        }
        updateUserFilterSelection();
    }

    function updateUserFilterSelection() {
        const cbs = document.querySelectorAll('.user-filter-checkbox');
        const allCb = document.getElementById('user-filter-all');
        const countBadge = document.getElementById('user-filter-count');

        let checkedCount = 0;
        cbs.forEach(cb => {
            if (cb.checked) checkedCount++;
        });

        if (checkedCount > 0) {
            allCb.checked = false;
            countBadge.textContent = checkedCount;
            countBadge.style.display = 'inline-block';
        } else {
            allCb.checked = true;
            countBadge.style.display = 'none';
        }

        // Auto reload table when filter changes
        loadTablePage(1);
    }

    function getSelectedUserIds() {
        const allCb = document.getElementById('user-filter-all');
        if (allCb.checked) return []; // Empty array means all

        const selected = [];
        document.querySelectorAll('.user-filter-checkbox:checked').forEach(cb => {
            selected.push(cb.value);
        });
        return selected;
    }

    // Init user filter from localStorage
    function initUserFilter() {
        const saved = localStorage.getItem('pos_history_selected_users');
        if (saved) {
            const savedIds = saved.split(',').filter(id => id.trim() !== '');
            if (savedIds.length > 0) {
                document.getElementById('user-filter-all').checked = false;
                document.querySelectorAll('.user-filter-checkbox').forEach(cb => {
                    if (savedIds.includes(cb.value)) {
                        cb.checked = true;
                    } else {
                        cb.checked = false;
                    }
                });
            }
        }
        updateUserFilterSelection();
    }

    let bulkSelectActive = false;

    document.addEventListener('DOMContentLoaded', () => {
        initUserFilter();
        // If customer_id filter is present, clear date/user filters to show all orders
        const urlCustomerId = new URLSearchParams(window.location.search).get('customer_id');
        if (urlCustomerId) {
            document.getElementById('date-from').value = '';
            document.getElementById('date-to').value = '';
            // Force "show all users"
            document.getElementById('user-filter-all').checked = true;
            document.querySelectorAll('.user-filter-checkbox').forEach(cb => cb.checked = false);
            updateUserFilterSelection();
            localStorage.removeItem('pos_history_selected_users');
        }

        loadTablePage(1); // Load initial data

        // Bulk Selection Logic
        document.getElementById('toggle-bulk-select').addEventListener('click', function () {
            bulkSelectActive = !bulkSelectActive;
            if (bulkSelectActive) {
                this.innerHTML = '<i class="fas fa-times"></i> ປິດ';
                document.getElementById('bulk-actions').style.display = 'flex';
                document.querySelectorAll('.bulk-checkbox').forEach(el => el.classList.add('show'));
            } else {
                resetBulkSelection();
            }
        });

        document.getElementById('cancel-selection').addEventListener('click', resetBulkSelection);

        document.getElementById('select-all').addEventListener('change', function () {
            document.querySelectorAll('.order-checkbox').forEach(cb => cb.checked = this.checked);
            updatePrintButton();
        });

        document.addEventListener('change', e => {
            if (e.target.classList.contains('order-checkbox')) updatePrintButton();
        });

        document.getElementById('print-selected').addEventListener('click', () => {
            const ids = Array.from(document.querySelectorAll('.order-checkbox:checked')).map(cb => cb.dataset.orderId);
            if (ids.length) window.open('print_invoice.php?order_ids=' + ids.join(','), '_blank');
        });



        // Delete Logic
        document.getElementById('confirm-delete-btn').addEventListener('click', function () {
            const oid = document.getElementById('delete-order-id').value;
            const pass = document.getElementById('delete-password').value;
            if (!pass) return Swal.fire('Error', 'Please enter password', 'error');

            fetch('history_pos.php?ajax=delete', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ order_id: oid, password: pass })
            })
                .then(r => r.json())
                .then(res => {
                    if (res.status === 'success') {
                        closeModal('delete-modal');
                        Swal.fire({ icon: 'success', title: 'Deleted', timer: 1500, showConfirmButton: false });
                        loadTablePage(1);
                    } else {
                        Swal.fire({ icon: 'error', title: 'Error', text: res.message });
                    }
                });
        });
    });

    function loadTablePage(page) {
        const search = document.getElementById('search-input').value;
        const dFrom = document.getElementById('date-from').value;
        const dTo = document.getElementById('date-to').value;

        // Get selected users
        const selectedUsers = getSelectedUserIds();
        // save to localStorage
        localStorage.setItem('pos_history_selected_users', selectedUsers.join(','));

        const params = new URLSearchParams({
            ajax: 'table',
            page,
            search,
            date_from: dFrom,
            date_to: dTo,
            users: selectedUsers.join(',')
        });

        // Pass customer_id filter if present in URL
        const urlCustomerId = new URLSearchParams(window.location.search).get('customer_id');
        if (urlCustomerId) {
            params.set('customer_id', urlCustomerId);
        }

        document.getElementById('sales-table-body').innerHTML = '<tr><td colspan="13" style="text-align:center;padding:40px;"><i class="fas fa-spinner fa-spin"></i> Loading...</td></tr>';

        fetch('history_pos.php?' + params)
            .then(r => r.text())
            .then(html => {
                document.getElementById('sales-table-body').innerHTML = html;
                if (bulkSelectActive) document.querySelectorAll('.bulk-checkbox').forEach(el => el.classList.add('show'));
            });

        const pParams = new URLSearchParams({
            ajax: 'pagination',
            page,
            search,
            date_from: dFrom,
            date_to: dTo,
            users: selectedUsers.join(',')
        });
        if (urlCustomerId) {
            pParams.set('customer_id', urlCustomerId);
        }
        fetch('history_pos.php?' + pParams)
            .then(r => r.text())
            .then(html => document.getElementById('pagination').innerHTML = html);
    }

    function resetFilter() {
        document.getElementById('search-input').value = '';
        document.getElementById('date-from').value = '<?= date('Y-m-d') ?>';
        document.getElementById('date-to').value = '<?= date('Y-m-d') ?>';

        // Reset users filter
        document.getElementById('user-filter-all').checked = true;
        document.querySelectorAll('.user-filter-checkbox').forEach(cb => cb.checked = false);
        updateUserFilterSelection();
        localStorage.removeItem('pos_history_selected_users');

        loadTablePage(1);
    }

    function viewOrder(oid) {
        document.getElementById('modal-title').innerText = 'ລາຍລະອຽດໃບບິນ: ' + oid;
        document.getElementById('order-modal').classList.add('show');
        document.getElementById('order-details').innerHTML = '<div style="text-align:center;padding:40px"><i class="fas fa-spinner fa-spin fa-2x"></i><br><br>Loading...</div>';

        fetch('history_pos.php?ajax=details&order_id=' + oid)
            .then(r => r.json())
            .then(res => {
                if (res.status === 'success') {
                    const o = res.order;
                    const sym = o.currency_symbol;
                    const fmt = (v) => v ? Number(v).toLocaleString() : '0';

                    // Update title (simple)
                    document.getElementById('modal-title').textContent = 'ລາຍລະອຽດໃບບິນ';

                    // --- Payment status badge ---
                    const payBadgeClass = { paid: 'od-badge-paid', pending: 'od-badge-pending', partial: 'od-badge-partial', refunded: 'od-badge-refunded' }[o.payment_status] || 'od-badge-pending';
                    const payBadgeIcon = { paid: 'fa-check-circle', pending: 'fa-clock', partial: 'fa-minus-circle', refunded: 'fa-undo' }[o.payment_status] || 'fa-clock';

                    // --- Order type badge ---
                    const typeText = { pos: 'ໜ້າຮ້ານ', online: 'ອອນລາຍ', wholesale: 'ຂາຍສົ່ງ' }[o.order_type] || o.order_type;

                    // --- Payment method ---
                    const payMethodText = o.payment_method === 'cash' ? 'ເງິນສົດ' : o.payment_method === 'transfer' ? 'ໂອນ' : o.payment_method || '-';

                    // --- Items HTML ---
                    let itemsHtml = '';
                    if (res.items && res.items.length > 0) {
                        itemsHtml = res.items.map((it, i) => {
                            const imgHtml = it.product_image
                                ? `<img class="od-product-img" src="../api/get_image.php?f=${encodeURIComponent(it.product_image)}&w=200" alt="">`
                                : `<div class="od-product-placeholder"><i class="fas fa-box"></i></div>`;
                            return `<tr>
                                <td>${i + 1}</td>
                                <td>${it.barcode || '-'}</td>
                                <td><div class="od-product-cell">${imgHtml}<div class="od-product-name">${it.product_name}</div></div></td>
                                <td class="text-right">${sym}${fmt(it.unit_price)}</td>
                                <td class="text-center">${it.quantity}</td>
                                <td class="text-right fw-bold">${sym}${fmt(it.total)}</td>
                            </tr>`;
                        }).join('');
                    } else {
                        itemsHtml = '<tr><td colspan="6" style="text-align:center;padding:20px;color:var(--text-secondary)">ບໍ່ມີລາຍການສິນຄ້າ</td></tr>';
                    }

                    // --- Slip HTML ---
                    let slipContent = '';
                    if (o.order_image_slip) {
                        const slipFiles = o.order_image_slip.split(',');
                        slipContent = `<div class="od-slip-grid">${slipFiles.map(f => `<img class="od-slip-img" src="../../img/slip/${f.trim()}" onclick="window.open(this.src,'_blank')" title="ຄລິກເພື່ອຂະຫຍາຍ">`).join('')}</div>`;
                    } else {
                        slipContent = `<div class="od-slip-empty"><i class="fas fa-image"></i>ບໍ່ມີສລິບແນບ</div>`;
                    }

                    // --- Step Progress helper ---
                    const steps = [
                        { label: 'ພິມບິນ', val: o.print_status, goodVal: 'printed' },
                        { label: 'ຈັດເຄື່ອງ', val: o.prepare_status, goodVal: 'ຈັດເຄື່ອງແລ້ວ' },
                        { label: 'ຄີເຄື່ອງ', val: o.front_stock_status, goodVal: 'ຄີແລ້ວ' },
                        { label: 'ແພັກເຄື່ອງ', val: o.pack_status, goodVal: 'ແພັກແລ້ວ' },
                        { label: 'ເຄື່ອງອອກ', val: o.shipping_status, goodVal: 'ເຄື່ອງອອກແລ້ວ', date: o.shipping_date },
                        { label: 'ແຈ້ງບິນຮ້ານ', val: o.shop_bill_status, goodVal: 'ແຈ້ງບິນແລ້ວ' },
                        { label: 'ແຈ້ງບິນຂົນສົ່ງ', val: o.transport_bill_status, goodVal: 'ແຈ້ງບິນແລ້ວ' }
                    ];
                    // Determine first not-done step as "active"
                    let foundActive = false;
                    const stepsHtml = steps.map((s, i) => {
                        let cls = 'pending';
                        let icon = '';
                        if (s.val === s.goodVal) {
                            cls = 'done';
                            icon = '<i class="fas fa-check"></i>';
                        } else if (!foundActive) {
                            cls = 'active';
                            icon = '<i class="fas fa-circle" style="font-size:10px"></i>';
                            foundActive = true;
                        } else {
                            icon = (i + 1);
                        }
                        const dateHtml = s.date ? `<div class="od-step-date">${s.date}</div>` : '';
                        return `<div class="od-step ${cls}"><div class="od-step-circle">${icon}</div><div class="od-step-label">${s.label}</div>${dateHtml}</div>`;
                    }).join('');

                    // --- Currency conversion section ---
                    let currencyHtml = '';
                    if (Number(o.currency_rate) !== 1) {
                        currencyHtml = `
                        <div class="od-card">
                            <div class="od-card-title"><i class="fas fa-exchange-alt"></i> ການແປງສະກຸນເງິນ</div>
                            <div class="od-currency-box">
                                <div class="od-cur-panel foreign">
                                    <div class="od-cur-title">ສະກຸນເງິນທີ່ລູກຄ້າຈ່າຍ</div>
                                    <div style="font-size:13px;color:var(--text-secondary);margin-bottom:4px">${o.currency_name || '-'}</div>
                                    <div class="od-cur-amount">${sym}${fmt(o.total_amount)}</div>
                                    <div style="margin-top:10px;font-size:14px;color:var(--text-secondary)">
                                        <div style="display:flex;justify-content:space-between;padding:3px 0"><span>ລວມ:</span><span>${sym}${fmt(o.subtotal)}</span></div>
                                        <div style="display:flex;justify-content:space-between;padding:3px 0"><span>ສ່ວນຫຼຸດ:</span><span style="color:#dc3545">-${sym}${fmt(o.discount_amount)}</span></div>
                                        <div style="display:flex;justify-content:space-between;padding:3px 0"><span>VAT:</span><span>${o.vat_enabled == 1 ? sym + fmt(o.tax_amount) : '-'}</span></div>
                                    </div>
                                </div>
                                <div class="od-cur-arrow">
                                    <div style="font-size:11px;color:var(--text-secondary);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px">ອັດຕາ</div>
                                    <div class="od-cur-rate-badge">× ${fmt(o.currency_rate)}</div>
                                    <i class="fas fa-long-arrow-alt-right"></i>
                                </div>
                                <div class="od-cur-panel lak">
                                    <div class="od-cur-title">ເປັນເງິນກີບ (LAK)</div>
                                    <div style="font-size:13px;color:var(--text-secondary);margin-bottom:4px">Lao Kip</div>
                                    <div class="od-cur-amount">₭${fmt(o.total_amount_lak)}</div>
                                    <div style="margin-top:10px;font-size:14px;color:var(--text-secondary)">
                                        <div style="display:flex;justify-content:space-between;padding:3px 0"><span>ລວມ (LAK):</span><span>₭${fmt(o.subtotal_lak)}</span></div>
                                        <div style="display:flex;justify-content:space-between;padding:3px 0"><span>ສ່ວນຫຼຸດ (LAK):</span><span style="color:#dc3545">-₭${fmt(o.discount_lak)}</span></div>
                                        <div style="display:flex;justify-content:space-between;padding:3px 0"><span>VAT (LAK):</span><span>₭${fmt(o.vat_amount_lak)}</span></div>
                                    </div>
                                </div>
                            </div>
                        </div>`;
                    }

                    // === Assemble full modal content ===
                    document.getElementById('order-details').innerHTML = `
                        <!-- 1) HEADER -->
                        <div class="od-header">
                            <div class="od-header-left">
                                <div class="od-order-id">${o.OR_id}</div>
                                <div class="od-header-meta">
                                    <i class="far fa-calendar-alt"></i> ${o.created_at}
                                    <span style="color:#ddd">|</span>
                                    <i class="fas fa-user"></i> ${o.created_by_name || o.created_by || '-'}
                                </div>
                            </div>
                            <div class="od-header-badges">
                                <span class="od-badge ${payBadgeClass}"><i class="fas ${payBadgeIcon}"></i> ${o.payment_status_text}</span>
                                <span class="od-badge od-badge-type"><i class="fas fa-store"></i> ${typeText}</span>
                                <span class="od-badge od-badge-currency"><i class="fas fa-coins"></i> ${o.currency_name || 'LAK'}</span>
                            </div>
                        </div>

                        <!-- 2) ORDER & CUSTOMER INFO -->
                        <div class="od-grid-2col">
                            <div class="od-card">
                                <div class="od-card-title"><i class="fas fa-file-alt"></i> ຂໍ້ມູນອໍເດີ</div>
                                <div class="od-info-row"><span class="od-info-label">ຜູ້ທຳລາຍການ</span><span class="od-info-value">${o.created_by_name || o.created_by || '-'}</span></div>
                                <div class="od-info-row"><span class="od-info-label">ປະເພດ</span><span class="od-info-value">${o.order_type_text}</span></div>
                                <div class="od-info-row"><span class="od-info-label">ວິທີຊຳລະ</span><span class="od-info-value">${payMethodText}</span></div>
                                <div class="od-info-row"><span class="od-info-label">ສະຖານະການຈ່າຍ</span><span class="od-info-value">${o.payment_status_text}</span></div>
                                <div class="od-info-row"><span class="od-info-label">ເລກບິນ POS</span><span class="od-info-value">${o.bill_number || '-'}</span></div>
                                <div class="od-info-row"><span class="od-info-label">ຄ່າຝາກ</span><span class="od-info-value">${o.notes || '-'}</span></div>
                            </div>
                            <div class="od-card">
                                <div class="od-card-title"><i class="fas fa-user"></i> ຂໍ້ມູນລູກຄ້າ</div>
                                <div class="od-info-row"><span class="od-info-label">ລະຫັດລູກຄ້າ</span><span class="od-info-value">${o.customer_id || '-'}</span></div>
                                <div class="od-info-row"><span class="od-info-label">ຊື່ລູກຄ້າ</span><span class="od-info-value">${o.customer_name || '-'}</span></div>
                                <div class="od-info-row"><span class="od-info-label">ເບີໂທ</span><span class="od-info-value">${o.customer_phone || '-'}</span></div>
                                <div class="od-card-title" style="margin-top:16px"><i class="fas fa-truck"></i> ການຂົນສົ່ງ</div>
                                <div class="od-info-row"><span class="od-info-label">ບໍລິສັດ</span><span class="od-info-value">${o.shipping_company || '-'}</span></div>
                                <div class="od-info-row"><span class="od-info-label">ສາຂາ</span><span class="od-info-value">${o.shipping_branch || '-'}</span></div>
                                <div class="od-info-row"><span class="od-info-label">ເລກໃບບິນຂົນສົ່ງ</span><span class="od-info-value">${o.bill_transport_number || '-'}</span></div>
                            </div>
                        </div>

                        <!-- 3) PAYMENT SLIP -->
                        <div class="od-card">
                            <div class="od-card-title"><i class="fas fa-image"></i> ຫຼັກຖານການໂອນ ${o.order_image_slip ? '(' + o.order_image_slip.split(',').length + ' ຮູບ)' : ''}</div>
                            ${slipContent}
                        </div>

                        <!-- 4) CURRENCY CONVERSION (if foreign) -->
                        ${currencyHtml}

                        <!-- 5) WORKFLOW STEP PROGRESS -->
                        <div class="od-card">
                            <div class="od-card-title"><i class="fas fa-tasks"></i> ສະຖານະການດຳເນີນງານ</div>
                            <div class="od-step-progress">
                                ${stepsHtml}
                            </div>
                        </div>

                        <!-- 6) PRODUCT TABLE -->
                        <div class="od-section-title"><i class="fas fa-box-open"></i> ລາຍການສິນຄ້າ</div>
                        <div style="overflow-x:auto">
                            <table class="od-product-table">
                                <thead><tr>
                                    <th>#</th><th>ບາໂຄດ</th><th>ຮູບພາບ ແລະ ຊື່ສິນຄ້າ</th>
                                    <th class="text-right">ລາຄາ</th><th class="text-center">ຈຳນວນ</th><th class="text-right">ລວມ</th>
                                </tr></thead>
                                <tbody>${itemsHtml}</tbody>
                            </table>
                        </div>

                        <!-- 7) SUMMARY -->
                        <div class="od-summary">
                            <div class="od-summary-row"><span class="od-summary-label">ລວມ</span><span class="od-summary-value">${sym}${fmt(o.subtotal)}</span></div>
                            <div class="od-summary-row"><span class="od-summary-label">ສ່ວນຫຼຸດ</span><span class="od-summary-value discount">-${sym}${fmt(o.discount_amount)}</span></div>
                            <div class="od-summary-row"><span class="od-summary-label">VAT</span><span class="od-summary-value">${o.vat_enabled == 1 ? sym + fmt(o.tax_amount) : '-'}</span></div>
                            <div class="od-summary-total">
                                <span class="od-summary-total-label">ລວມທັງໝົດ</span>
                                <span class="od-summary-total-value">${sym}${fmt(o.total_amount)}</span>
                            </div>
                            ${o.order_type === 'pos' ? `
                            <div class="od-summary-row" style="margin-top:8px"><span class="od-summary-label">ເງິນມັດຈຳ</span><span class="od-summary-value">${Number(o.deposit_amount) > 0 ? sym + fmt(o.deposit_amount) : '-'}</span></div>
                            <div class="od-summary-row"><span class="od-summary-label">ເງິນສົດຮັບ</span><span class="od-summary-value">${Number(o.cash_received) > 0 ? sym + fmt(o.cash_received) : '-'}</span></div>
                            <div class="od-summary-row"><span class="od-summary-label">ເງິນທອນ</span><span class="od-summary-value">${Number(o.cash_change) > 0 ? sym + fmt(o.cash_change) : '-'}</span></div>
                            ` : ''}
                        </div>

                        <!-- 8) NOTES -->
                        <div class="od-notes"><i class="fas fa-comment"></i> <strong>ໝາຍເຫດ:</strong> ${o.note || '-'}</div>
                    `;
                }
            });
    }

    // ========== EDIT MODAL LOGIC ==========
    let editItems = [];
    let editExistingSlips = [];
    let editNewSlipFiles = [];

    function editAddNewSlips() {
        const input = document.getElementById('edit-slip-image');
        if (input.files && input.files.length > 0) {
            Array.from(input.files).forEach(f => editNewSlipFiles.push(f));
            input.value = '';
        }
        editRenderSlips();
    }

    // Handle Paste Image specifically on the dropzone
    const slipDropzone = document.getElementById('edit-slip-dropzone');
    if (slipDropzone) {
        slipDropzone.addEventListener('paste', function (e) {
            const items = (e.clipboardData || e.originalEvent.clipboardData).items;
            let hasImage = false;

            for (let i = 0; i < items.length; i++) {
                const item = items[i];
                if (item.kind === 'file' && item.type.startsWith('image/')) {
                    const file = item.getAsFile();
                    if (file) {
                        editNewSlipFiles.push(file);
                        hasImage = true;
                    }
                }
            }

            if (hasImage) {
                editRenderSlips();
                e.preventDefault();
            }
        });

        // Also add basic drag and drop support while we're at it
        slipDropzone.addEventListener('dragover', e => {
            e.preventDefault();
            slipDropzone.style.backgroundColor = 'rgba(var(--accent-rgb), 0.05)';
        });
        slipDropzone.addEventListener('dragleave', e => {
            e.preventDefault();
            slipDropzone.style.backgroundColor = 'transparent';
        });
        slipDropzone.addEventListener('drop', e => {
            e.preventDefault();
            slipDropzone.style.backgroundColor = 'transparent';
            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
                Array.from(e.dataTransfer.files).forEach(f => {
                    if (f.type.startsWith('image/')) {
                        editNewSlipFiles.push(f);
                    }
                });
                editRenderSlips();
            }
        });
    }

    function editRenderSlips() {
        const slipEl = document.getElementById('edit-slip-preview');
        const countEl = document.getElementById('edit-slip-count');
        const total = editExistingSlips.length + editNewSlipFiles.length;

        if (countEl) countEl.textContent = total > 0 ? `(${total} ຮູບ)` : '';

        if (total === 0) {
            slipEl.innerHTML = '<i class="fas fa-image" style="font-size:32px;opacity:0.3;margin-bottom:8px;display:block"></i>ບໍ່ມີຫຼັກຖານການໂອນ';
            slipEl.className = 'od-slip-empty';
            return;
        }

        slipEl.className = '';
        let html = '<div style="display:flex;flex-wrap:wrap;gap:10px">';

        editExistingSlips.forEach((f, i) => {
            html += `<div style="position:relative;display:inline-block">
                <img src="../../img/slip/${f}" style="max-width:120px;max-height:120px;border-radius:8px;cursor:pointer;border:1px solid var(--border-color)" onclick="window.open(this.src,'_blank')">
                <button type="button" style="position:absolute;top:-8px;right:-8px;background:#dc3545;color:white;border:none;border-radius:50%;width:24px;height:24px;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 4px rgba(0,0,0,0.2)" onclick="editRemoveExistingSlip(${i})"><i class="fas fa-times" style="font-size:12px"></i></button>
            </div>`;
        });

        editNewSlipFiles.forEach((file, i) => {
            html += `<div style="position:relative;display:inline-block" id="edit-new-slip-${i}">
                <div class="slip-spinner" style="width:120px;height:120px;border-radius:8px;border:1px solid var(--border-color);display:flex;align-items:center;justify-content:center;background:var(--input-bg)"><i class="fas fa-spinner fa-spin"></i></div>
                <img class="slip-img" src="" style="display:none;max-width:120px;max-height:120px;border-radius:8px;border:1px solid var(--border-color)">
                <button type="button" style="position:absolute;top:-8px;right:-8px;background:#dc3545;color:white;border:none;border-radius:50%;width:24px;height:24px;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 4px rgba(0,0,0,0.2);z-index:10;" onclick="event.stopPropagation(); event.preventDefault(); editRemoveNewSlip(${i});"><i class="fas fa-times" style="font-size:12px"></i></button>
            </div>`;
        });

        html += '</div>';
        slipEl.innerHTML = html;

        editNewSlipFiles.forEach((file, i) => {
            const reader = new FileReader();
            reader.onload = e => {
                const container = document.getElementById('edit-new-slip-' + i);
                if (container) {
                    const spinner = container.querySelector('.slip-spinner');
                    const img = container.querySelector('.slip-img');
                    if (spinner) spinner.style.display = 'none';
                    if (img) {
                        img.src = e.target.result;
                        img.style.display = 'block';
                    }
                }
            };
            reader.readAsDataURL(file);
        });
    }

    function editRemoveExistingSlip(index) {
        editExistingSlips.splice(index, 1);
        editRenderSlips();
    }

    function editRemoveNewSlip(index) {
        editNewSlipFiles.splice(index, 1);
        editRenderSlips();
    }
    let editVatEnabled = false;
    let editDiscountType = 'fixed'; // 'fixed' or 'percent'
    let editBaseDiscountLAK = 0;
    let editCurrentCurrency = { id: 'LAK', symbol: '₭', rate: 1 };
    let editSearchTimers = {};
    const shopId = <?= json_encode($shop_id) ?>;

    function editOrder(oid) {
        document.getElementById('edit-order-id').value = oid;
        Swal.fire({ title: 'ກຳລັງໂຫຼດ...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });

        fetch('history_pos.php?ajax=details&order_id=' + oid)
            .then(r => r.json())
            .then(res => {
                Swal.close();
                if (res.status !== 'success') return Swal.fire('Error', res.message || 'Load failed', 'error');
                const o = res.order;
                const stBadge = (val, goodVal, goodLabel, badLabel) => {
                    if (!val) return `<span class="badge status-pending">${badLabel}</span>`;
                    return val === goodVal
                        ? `<span class="badge status-paid">${goodLabel}</span>`
                        : `<span class="badge status-pending">${badLabel}</span>`;
                };

                // Order info (readonly display)
                document.getElementById('edit-or-id-display2').textContent = o.OR_id;
                document.getElementById('edit-created-at').textContent = o.created_at || '-';
                document.getElementById('edit-order-type-display2').textContent = o.order_type_text || o.order_type || '-';
                document.getElementById('edit-created-by').textContent = o.created_by_name || o.created_by || '-';
                document.getElementById('edit-bill-number').value = o.bill_number || '';
                document.getElementById('edit-shipping-date').value = o.shipping_date || '';
                document.getElementById('edit-bill-transport').value = o.bill_transport_number || '';

                // Title with currency
                const currLabel = o.currency_name || 'LAK';
                document.getElementById('edit-modal-title').innerHTML = 'ແກ້ໄຂໃບບິນ: ' + o.OR_id + ' <span style="font-size:13px;background:linear-gradient(135deg,#673ab7,#9c27b0);color:#fff;padding:4px 12px;border-radius:20px;margin-left:8px;font-weight:600;">' + currLabel + '</span>';

                // Customer
                editResetSearchable('editCustomerWrapper');
                if (o.customer_id) {
                    editSelectOption('editCustomerWrapper', o.customer_id, o.customer_name + (o.customer_phone ? ' - ' + o.customer_phone : ''), o.customer_id);
                }

                // Shipping Company
                editResetSearchable('editCompanyWrapper');
                if (o.shipping_company_id) {
                    editSelectOption('editCompanyWrapper', o.shipping_company_id, o.shipping_company || o.shipping_company_id, o.shipping_company_id);
                }

                // Shipping Branch
                editResetSearchable('editBranchWrapper');
                if (o.shipping_branch_id) {
                    editSelectOption('editBranchWrapper', o.shipping_branch_id, o.shipping_branch || o.shipping_branch_id, o.shipping_branch_id);
                }

                // Currency
                const currSel = document.getElementById('editCurrencySelect');
                if (o.currencys_id) {
                    currSel.value = o.currencys_id;
                }
                const curOpt = currSel.options[currSel.selectedIndex];
                editCurrentCurrency = {
                    id: currSel.value,
                    symbol: curOpt.dataset.symbol || '₭',
                    rate: parseFloat(curOpt.dataset.rate) || 1
                };

                // Exchange rate display
                document.getElementById('edit-rate-display').textContent = Number(o.currency_rate) !== 1 ? '× ' + Number(o.currency_rate).toLocaleString() : '-';

                // VAT
                editVatEnabled = (o.vat_enabled == 1);
                document.getElementById('editVatToggle').classList.toggle('active', editVatEnabled);
                document.getElementById('editVatRow').style.display = editVatEnabled ? 'flex' : 'none';

                // Slip image preview display
                const slipEl = document.getElementById('edit-slip-preview');
                const slipInput = document.getElementById('edit-slip-image');
                slipInput.value = '';
                editNewSlipFiles = [];
                if (o.order_image_slip) {
                    editExistingSlips = o.order_image_slip.split(',').map(f => f.trim()).filter(f => f !== "");
                } else {
                    editExistingSlips = [];
                }
                editRenderSlips();
                // Helper for setting select value with fallback
                const setSelectVal = (id, val, fallback) => {
                    const el = document.getElementById(id);
                    if (el) {
                        if (!val) {
                            el.value = fallback;
                            return;
                        }
                        const v = val.trim();
                        // Check if option exists
                        const exists = Array.from(el.options).some(opt => opt.value === v);
                        if (exists) {
                            el.value = v;
                        } else {
                            // If it doesn't match predefined options but exists in DB, maybe we should still add it or fallback
                            el.value = fallback;
                        }
                    }
                };

                // Status selects (editable)
                setSelectVal('edit-print-status', o.print_status, 'ຍັງບໍ່ພິມ');
                setSelectVal('edit-prepare-status', o.prepare_status, 'ຍັງບໍ່ຈັດເຄື່ອງ');
                setSelectVal('edit-front-stock', o.front_stock_status, 'ຍັງບໍ່ຄີ');
                setSelectVal('edit-pack-status', o.pack_status, 'ຍັງບໍ່ໄດ້ແພັກ');
                setSelectVal('edit-shipping-status', o.shipping_status, 'ເຄື່ອງຍັງບໍ່ອອກ');
                setSelectVal('edit-shop-bill', o.shop_bill_status, 'ຍັງບໍ່ແຈ້ງ');
                setSelectVal('edit-transport-bill', o.transport_bill_status, 'ຍັງບໍ່ແຈ້ງ');

                // Update shipping date display if status is shipped
                if (o.shipping_status === 'ເຄື່ອງອອກແລ້ວ' && o.shipping_date) {
                    document.getElementById('edit-shipping-date-display').style.display = 'block';
                    document.getElementById('edit-shipping-date-text').textContent = o.shipping_date;
                } else {
                    document.getElementById('edit-shipping-date-display').style.display = 'none';
                }

                // Load items (include barcode + image)
                editItems = [];
                if (res.items && res.items.length > 0) {
                    res.items.forEach(it => {
                        editItems.push({
                            product_id: it.product_id || '',
                            product_name: it.product_name || '',
                            barcode: it.barcode || '',
                            product_image: it.product_image || '',
                            basePriceLAK: parseFloat(it.unit_price_lak || it.unit_price || 0),
                            qty: parseInt(it.quantity) || 1
                        });
                    });
                }

                // Discount
                editDiscountType = 'fixed';
                document.getElementById('editDiscountToggle').textContent = editCurrentCurrency.symbol;
                const discLak = parseFloat(o.discount_lak || o.discount_amount || 0);
                editBaseDiscountLAK = discLak;
                document.getElementById('editDiscountAmount').value = editConvertPrice(discLak);

                // Payment
                document.getElementById('edit-payment-status').value = o.payment_status || 'pending';
                editPaymentStatusChange();
                document.getElementById('edit-payment-method').value = o.payment_method || '';
                document.getElementById('edit-deposit-amount').value = o.deposit_amount || '';
                // Set notes select
                document.getElementById('edit-notes').value = o.notes || '';
                document.getElementById('edit-notes-display').textContent = o.notes || '-';

                editRenderItems();
                editRecalculate();

                editUpdateStatusStyle();

                document.getElementById('edit-modal').classList.add('show');
            })
            .catch(err => {
                Swal.close();
                Swal.fire('Error', 'Failed to load order: ' + err.message, 'error');
            });
    }

    // ===== Currency =====
    document.getElementById('editCurrencySelect').addEventListener('change', function () {
        const opt = this.options[this.selectedIndex];
        editCurrentCurrency = {
            id: this.value,
            symbol: opt.dataset.symbol || '₭',
            rate: parseFloat(opt.dataset.rate) || 1
        };

        // Update exchange rate display
        document.getElementById('edit-rate-display').textContent = editCurrentCurrency.rate !== 1 ? '× ' + editCurrentCurrency.rate.toLocaleString() : '-';


        // Update discount display
        if (editDiscountType === 'fixed') {
            document.getElementById('editDiscountAmount').value = editConvertPrice(editBaseDiscountLAK);
            document.getElementById('editDiscountToggle').textContent = editCurrentCurrency.symbol;
        }

        editRenderItems();
        editRecalculate();
    });

    function editConvertPrice(lakAmount) {
        if (editCurrentCurrency.rate === 1) return lakAmount;
        return lakAmount / editCurrentCurrency.rate;
    }

    function handleShippingStatusChange() {
        const status = document.getElementById('edit-shipping-status').value;
        if (status === 'ເຄື່ອງອອກແລ້ວ') {
            const now = new Date();
            // Format to YYYY-MM-DDThh:mm for datetime-local
            const offset = now.getTimezoneOffset() * 60000;
            const localISOTime = (new Date(now - offset)).toISOString().slice(0, 16);

            Swal.fire({
                title: 'ປ້ອນວັນທີ ແລະ ເວລາເຄື່ອງອອກ',
                html: '<input type="datetime-local" id="swal-shipping-date" class="swal2-input" value="' + localISOTime + '" style="max-width:260px; font-size:14px;">',
                showCancelButton: true,
                confirmButtonText: 'ບັນທຶກ',
                cancelButtonText: 'ຍົກເລີກ'
            }).then((result) => {
                if (result.isConfirmed) {
                    const dateVal = document.getElementById('swal-shipping-date').value;
                    if (dateVal) {
                        document.getElementById('edit-shipping-date').value = dateVal;
                        document.getElementById('edit-shipping-date-display').style.display = 'block';
                        document.getElementById('edit-shipping-date-text').textContent = dateVal;
                    }
                } else {
                    // Revert selection if user cancels
                    document.getElementById('edit-shipping-status').value = 'ເຄື່ອງຍັງບໍ່ອອກ';
                    document.getElementById('edit-shipping-date-display').style.display = 'none';
                }
            });
        } else {
            document.getElementById('edit-shipping-date-display').style.display = 'none';
            document.getElementById('edit-shipping-date').value = '';
        }
    }

    function editConvertToLAK(displayAmount) {
        if (editCurrentCurrency.rate === 1) return displayAmount;
        return displayAmount * editCurrentCurrency.rate;
    }

    function editFormatNumber(num) {
        if (editCurrentCurrency.symbol === '$') {
            return new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(num);
        }
        return new Intl.NumberFormat('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(Math.round(num));
    }

    // ===== VAT =====
    function editToggleVAT() {
        editVatEnabled = !editVatEnabled;
        document.getElementById('editVatToggle').classList.toggle('active', editVatEnabled);
        document.getElementById('editVatRow').style.display = editVatEnabled ? 'flex' : 'none';
        editRecalculate();
    }

    // ===== Discount =====
    function editToggleDiscountType() {
        const toggle = document.getElementById('editDiscountToggle');
        if (editDiscountType === 'fixed') {
            editDiscountType = 'percent';
            toggle.textContent = '%';
            toggle.style.background = 'linear-gradient(135deg, #28a745, #20c997)';
            toggle.style.color = 'white';
            // Convert current LAK discount to % of subtotal
            const subtotalLAK = editItems.reduce((s, i) => s + (i.basePriceLAK * i.qty), 0);
            if (subtotalLAK > 0) {
                document.getElementById('editDiscountAmount').value = Math.round((editBaseDiscountLAK / subtotalLAK) * 100 * 100) / 100;
            }
        } else {
            editDiscountType = 'fixed';
            toggle.textContent = editCurrentCurrency.symbol;
            toggle.style.background = '';
            toggle.style.color = '';
            document.getElementById('editDiscountAmount').value = editFormatNumber(editConvertPrice(editBaseDiscountLAK));
        }
        editRecalculate();
    }

    // ===== Recalculate =====
    function editRecalculate() {
        const subtotalLAK = editItems.reduce((s, i) => s + (i.basePriceLAK * i.qty), 0);

        // Update discount base
        const discVal = parseFloat(document.getElementById('editDiscountAmount').value) || 0;
        if (editDiscountType === 'percent') {
            const pct = Math.min(discVal, 100);
            editBaseDiscountLAK = subtotalLAK * (pct / 100);
        } else {
            editBaseDiscountLAK = editConvertToLAK(discVal);
        }

        const taxableLAK = Math.max(0, subtotalLAK - editBaseDiscountLAK);
        const vatPct = parseFloat(document.getElementById('editVatPercent').value) || 10;
        const vatLAK = editVatEnabled ? taxableLAK * (vatPct / 100) : 0;
        const totalLAK = taxableLAK + vatLAK;

        const sym = editCurrentCurrency.symbol;
        document.getElementById('editSubtotal').textContent = sym + editFormatNumber(editConvertPrice(subtotalLAK));
        document.getElementById('editVatLabel').textContent = vatPct;
        document.getElementById('editVatAmount').textContent = sym + editFormatNumber(editConvertPrice(vatLAK));
        document.getElementById('editGrandTotal').textContent = sym + editFormatNumber(editConvertPrice(totalLAK));

        // Sync notes display
        document.getElementById('edit-notes-display').textContent = document.getElementById('edit-notes').value || '-';
    }

    // ===== Items =====
    function editRenderItems() {
        const body = document.getElementById('editItemsBody');
        if (editItems.length === 0) {
            body.innerHTML = '<tr><td colspan="7" style="text-align:center;padding:20px;color:var(--text-secondary)"><i class="fas fa-box-open"></i> ບໍ່ມີສິນຄ້າ</td></tr>';
            return;
        }
        const sym = editCurrentCurrency.symbol;
        body.innerHTML = editItems.map((item, i) => {
            const price = editConvertPrice(item.basePriceLAK);
            const total = price * item.qty;
            let imgHtml = '';
            if (item.product_image) {
                imgHtml = `<img src="../api/get_image.php?f=${encodeURIComponent(item.product_image)}&w=200" style="width:40px;height:40px;border-radius:4px;object-fit:cover;border:1px solid var(--border-color);flex-shrink:0" alt="">`;
            } else {
                imgHtml = `<div style="width:40px;height:40px;border-radius:4px;background:rgba(0,0,0,0.03);border:1px solid var(--border-color);display:flex;align-items:center;justify-content:center;color:var(--text-secondary);flex-shrink:0"><i class="fas fa-box"></i></div>`;
            }
            return `<tr>
                <td>${i + 1}</td>
                <td>${item.barcode || '-'}</td>
                <td><div style="display:flex;align-items:center;gap:10px">${imgHtml}<div style="font-weight:500;font-size:14px;line-height:1.4">${item.product_name}</div></div></td>
                <td style="text-align:right">${sym}${editFormatNumber(price)}</td>
                <td style="text-align:center"><input type="number" value="${item.qty}" min="1" style="width:70px;padding:6px 8px;border:1px solid var(--border-color);border-radius:6px;background:var(--input-bg);color:var(--text-primary);text-align:right" onchange="editUpdateQty(${i}, this.value)"></td>
                <td style="text-align:right;font-weight:600">${sym}${editFormatNumber(total)}</td>
                <td><button type="button" style="width:28px;height:28px;border-radius:6px;border:none;background:rgba(220,53,69,0.1);color:#dc3545;cursor:pointer;font-size:12px" onclick="editRemoveItem(${i})"><i class="fas fa-times"></i></button></td>
            </tr>`;
        }).join('');
    }

    function editAddProduct(product) {
        const existing = editItems.find(i => i.product_id == product.id);
        if (existing) {
            existing.qty++;
        } else {
            editItems.push({
                product_id: product.id,
                product_name: product.products_name,
                barcode: product.barcode || '',
                product_image: product.image || '',
                basePriceLAK: parseFloat(product.price_1) || 0,
                qty: 1
            });
        }
        editRenderItems();
        editRecalculate();
        document.getElementById('editProductSearch').value = '';
        document.getElementById('editProductResults').classList.remove('show');
    }

    function editRemoveItem(index) {
        editItems.splice(index, 1);
        editRenderItems();
        editRecalculate();
    }

    function editUpdateQty(index, val) {
        const qty = parseInt(val);
        if (qty > 0) {
            editItems[index].qty = qty;
        }
        editRenderItems();
        editRecalculate();
    }

    // ===== Barcode Scanner Integration =====
    function editDecodeAsciiBarcode(input) {
        if (/^\d+$/.test(input) && input.length % 3 === 0 && input.length > 24) {
            var decoded = '';
            for (var i = 0; i < input.length; i += 3) {
                var code = parseInt(input.substr(i, 3));
                if (code >= 48 && code <= 57) {
                    decoded += String.fromCharCode(code);
                } else {
                    return input;
                }
            }
            if (decoded.length >= 8 && decoded.length <= 14) {
                return decoded;
            }
        }
        return input;
    }

    function editScanAndAddToCart(barcode) {
        barcode = barcode.trim();
        if (!barcode || barcode.length < 4) return;

        const searchBox = document.getElementById('editProductSearch');
        if (searchBox) searchBox.value = '';
        document.getElementById('editProductResults').classList.remove('show');

        // We use the same search endpoint but we pick the exact match
        fetch('history_pos.php?ajax=search_products&q=' + encodeURIComponent(barcode))
            .then(r => r.json())
            .then(res => {
                if (res.data && res.data.length > 0) {
                    let product = null;
                    for (let i = 0; i < res.data.length; i++) {
                        if (res.data[i].product_code === barcode ||
                            (res.data[i].barcode && res.data[i].barcode === barcode)) {
                            product = res.data[i];
                            break;
                        }
                    }
                    if (!product) product = res.data[0];

                    editAddProduct(product);

                    if (typeof Swal !== 'undefined') {
                        Swal.fire({
                            toast: true,
                            position: 'top-end',
                            icon: 'success',
                            title: 'ເພີ່ມ: ' + product.products_name,
                            showConfirmButton: false,
                            timer: 1500,
                            timerProgressBar: true
                        });
                    }
                } else {
                    if (typeof Swal !== 'undefined') {
                        Swal.fire({
                            toast: true,
                            position: 'top-end',
                            icon: 'warning',
                            title: 'ບໍ່ພົບສິນຄ້າ: ' + barcode,
                            showConfirmButton: false,
                            timer: 2000
                        });
                    }
                }
            })
            .catch(err => {
                console.error('Barcode lookup error:', err);
            });
    }

    // ===== Product Search =====
    document.getElementById('editProductSearch').addEventListener('input', function () {
        clearTimeout(editSearchTimers.product);
        editSearchTimers.product = setTimeout(() => {
            const q = this.value.trim();

            // Auto-decode ASCII-encoded barcodes
            const decoded = editDecodeAsciiBarcode(q);
            if (decoded !== q) {
                this.value = decoded;
                editScanAndAddToCart(decoded);
                return;
            }

            // If it looks like a normal barcode (all digits, 8-14 chars), auto-add
            if (/^\d{8,14}$/.test(q)) {
                editScanAndAddToCart(q);
                return;
            }

            if (q.length < 1) { document.getElementById('editProductResults').classList.remove('show'); return; }

            fetch('history_pos.php?ajax=search_products&q=' + encodeURIComponent(q))
                .then(r => r.json())
                .then(res => {
                    const container = document.getElementById('editProductResults');
                    if (res.data && res.data.length > 0) {
                        const sym = editCurrentCurrency.symbol;
                        container.innerHTML = res.data.map(p => {
                            const price = editConvertPrice(parseFloat(p.price_1) || 0);
                            const imgHtml = p.image ? `<img src="../api/get_image.php?f=${encodeURIComponent(p.image)}&w=80" alt="">` : '<div style="width:36px;height:36px;border-radius:6px;background:var(--border-color);display:flex;align-items:center;justify-content:center"><i class="fas fa-box" style="color:var(--text-secondary)"></i></div>';
                            return `<div class="epr-item" onclick='editAddProduct(${JSON.stringify(p).replace(/'/g, "&#39;")})'>
                                ${imgHtml}
                                <div class="epr-info"><div class="epr-name">${p.products_name}</div><div class="epr-code">${p.barcode || p.product_code || ''}</div></div>
                                <div class="epr-price">${editFormatNumber(price)} ${sym}</div>
                            </div>`;
                        }).join('');
                        container.classList.add('show');
                    } else {
                        container.innerHTML = '<div style="padding:14px;text-align:center;color:var(--text-secondary)">ບໍ່ພົບສິນຄ້າ</div>';
                        container.classList.add('show');
                    }
                });
        }, 500);
    });

    // Handle Enter key on search box for barcode scanning
    document.getElementById('editProductSearch').addEventListener('keydown', function (e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            clearTimeout(editSearchTimers.product);
            let val = this.value.trim();
            const decoded = editDecodeAsciiBarcode(val);
            if (decoded !== val) {
                this.value = decoded;
                val = decoded;
            }
            if (/^\d{4,}$/.test(val)) {
                editScanAndAddToCart(val);
            }
        }
    });

    // ===== Searchable Selects (Customer, Company, Branch) - pos.php style =====
    function editToggleSearchable(wrapperId) {
        const wrapper = document.getElementById(wrapperId);
        const isOpen = wrapper.classList.contains('open');

        // Close all other open searchable selects
        document.querySelectorAll('.searchable-select.open').forEach(el => {
            el.classList.remove('open');
        });

        if (!isOpen) {
            wrapper.classList.add('open');
            const searchInput = wrapper.querySelector('.searchable-select-search input');
            searchInput.value = '';
            // Load options via AJAX
            editLoadOptions(wrapperId, '');
            setTimeout(() => searchInput.focus(), 50);
        }
    }

    function editFilterSearchable(wrapperId, query) {
        // Re-load from AJAX with query
        editLoadOptions(wrapperId, query);
    }

    function editLoadOptions(wrapperId, query) {
        let ajaxAction = '';
        let optionsId = '';
        if (wrapperId === 'editCustomerWrapper') { ajaxAction = 'search_customers'; optionsId = 'editCustomerOptions'; }
        else if (wrapperId === 'editCompanyWrapper') { ajaxAction = 'search_shipping_companies'; optionsId = 'editCompanyOptions'; }
        else if (wrapperId === 'editBranchWrapper') { ajaxAction = 'search_shipping_branches'; optionsId = 'editBranchOptions'; }

        fetch('history_pos.php?ajax=' + ajaxAction + '&q=' + encodeURIComponent(query))
            .then(r => r.json())
            .then(res => {
                const container = document.getElementById(optionsId);
                // Keep default/placeholder option
                let placeholder = '';
                if (wrapperId === 'editCustomerWrapper') placeholder = 'ເລືອກລູກຄ້າ';
                else if (wrapperId === 'editCompanyWrapper') placeholder = 'ເລືອກບໍລິສັດ';
                else if (wrapperId === 'editBranchWrapper') placeholder = 'ເລືອກສາຂາ';

                let html = `<div class="searchable-select-option" data-value="" onclick="editSelectOption('${wrapperId}', '', '${placeholder}')">${placeholder}</div>`;

                if (res.data && res.data.length > 0) {
                    res.data.forEach(item => {
                        let displayText = '';
                        let secondaryId = '';
                        let id = item.id;
                        if (wrapperId === 'editCustomerWrapper') {
                            displayText = item.name + (item.phone ? ' - ' + item.phone : '');
                            secondaryId = item.CU_id;
                        } else if (wrapperId === 'editCompanyWrapper') {
                            displayText = item.company_name;
                            secondaryId = item.SC_id;
                        } else if (wrapperId === 'editBranchWrapper') {
                            displayText = item.branch_name;
                            secondaryId = item.SB_id;
                        }
                        html += `<div class="searchable-select-option" data-value="${id}" data-secondary="${secondaryId}" onclick="editSelectOption('${wrapperId}', '${id}', '${displayText.replace(/'/g, "\\'")}', '${secondaryId}')">${displayText}</div>`;
                    });
                }
                container.innerHTML = html;

                // Mark current selection
                const wrapper = document.getElementById(wrapperId);
                const curVal = wrapper.querySelector('input[type="hidden"]').value;
                if (curVal) {
                    container.querySelectorAll('.searchable-select-option').forEach(opt => {
                        opt.classList.toggle('selected', opt.dataset.value === curVal);
                    });
                }
            });
    }

    function editSelectOption(wrapperId, value, displayText, secondaryId) {
        const wrapper = document.getElementById(wrapperId);
        const displaySpan = wrapper.querySelector('.searchable-select-text');
        let inputId = '', cuIdInput = '';

        if (wrapperId === 'editCustomerWrapper') { inputId = 'editCustomerId'; cuIdInput = 'editCustomerCuId'; }
        else if (wrapperId === 'editCompanyWrapper') { inputId = 'editCompanyId'; cuIdInput = 'editCompanyScId'; }
        else if (wrapperId === 'editBranchWrapper') { inputId = 'editBranchId'; cuIdInput = 'editBranchSbId'; }

        document.getElementById(inputId).value = value;
        document.getElementById(cuIdInput).value = secondaryId || '';

        if (value === '' || !value) {
            displaySpan.textContent = displaySpan.dataset.placeholder;
            displaySpan.classList.add('placeholder');
        } else {
            displaySpan.textContent = displayText;
            displaySpan.classList.remove('placeholder');
        }

        // Mark selected
        wrapper.querySelectorAll('.searchable-select-option').forEach(opt => {
            opt.classList.toggle('selected', opt.dataset.value === value);
        });

        // Close dropdown
        wrapper.classList.remove('open');
    }

    function editResetSearchable(wrapperId) {
        const wrapper = document.getElementById(wrapperId);
        if (!wrapper) return;
        const displaySpan = wrapper.querySelector('.searchable-select-text');
        const hiddenInputs = wrapper.querySelectorAll('input[type="hidden"]');
        hiddenInputs.forEach(input => input.value = '');
        displaySpan.textContent = displaySpan.dataset.placeholder;
        displaySpan.classList.add('placeholder');
    }

    // Close dropdowns on outside click
    document.addEventListener('click', function (e) {
        if (!e.target.closest('.searchable-select')) {
            document.querySelectorAll('.searchable-select.open').forEach(el => el.classList.remove('open'));
        }
        if (!e.target.closest('.edit-product-search')) {
            document.getElementById('editProductResults').classList.remove('show');
        }
    });

    // ===== Quick Add =====
    function toggleEditQuickAdd(type) {
        const formId = type === 'customer' ? 'editQuickCustomerForm' : type === 'company' ? 'editQuickCompanyForm' : 'editQuickBranchForm';
        const form = document.getElementById(formId);
        form.style.display = form.style.display === 'none' ? 'block' : 'none';
    }

    function editSaveQuickCustomer() {
        const name = document.getElementById('eqNewCustName').value.trim();
        const phone = document.getElementById('eqNewCustPhone').value.trim();
        if (!name || !phone) return Swal.fire({ icon: 'warning', title: 'ກະລຸນາປ້ອນຂໍ້ມູນ' });

        fetch('../api/pos_quick_add.php', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ type: 'customer', name, phone, shop_id: shopId })
        }).then(r => r.json()).then(data => {
            if (data.success) {
                editSelectOption('editCustomerWrapper', data.id, name + ' - ' + phone, data.id);
                document.getElementById('eqNewCustName').value = '';
                document.getElementById('eqNewCustPhone').value = '';
                toggleEditQuickAdd('customer');
                Swal.fire({ icon: 'success', title: 'ສຳເລັດ', timer: 1000, showConfirmButton: false });
            } else {
                Swal.fire({ icon: 'error', title: 'Error', text: data.message });
            }
        });
    }

    function editSaveQuickCompany() {
        const name = document.getElementById('eqNewCompanyName').value.trim();
        if (!name) return;

        fetch('../api/pos_quick_add.php', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ type: 'company', name, shop_id: shopId })
        }).then(r => r.json()).then(data => {
            if (data.success) {
                editSelectOption('editCompanyWrapper', data.id, name, data.id);
                document.getElementById('eqNewCompanyName').value = '';
                toggleEditQuickAdd('company');
                Swal.fire({ icon: 'success', title: 'ສຳເລັດ', timer: 1000, showConfirmButton: false });
            } else {
                Swal.fire({ icon: 'error', title: 'Error', text: data.message });
            }
        });
    }

    function editSaveQuickBranch() {
        const name = document.getElementById('eqNewBranchName').value.trim();
        if (!name) return;

        fetch('../api/pos_quick_add.php', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ type: 'branch', name, shop_id: shopId })
        }).then(r => r.json()).then(data => {
            if (data.success) {
                editSelectOption('editBranchWrapper', data.id, name, data.id);
                document.getElementById('eqNewBranchName').value = '';
                toggleEditQuickAdd('branch');
                Swal.fire({ icon: 'success', title: 'ສຳເລັດ', timer: 1000, showConfirmButton: false });
            } else {
                Swal.fire({ icon: 'error', title: 'Error', text: data.message });
            }
        });
    }

    // ===== Status Style Toggle =====
    function editUpdateStatusStyle() {
        const statusMap = {
            'edit-print-status': 'printed',
            'edit-prepare-status': 'ຈັດເຄື່ອງແລ້ວ',
            'edit-front-stock': 'ຄີແລ້ວ',
            'edit-pack-status': 'ແພັກແລ້ວ',
            'edit-shipping-status': 'ເຄື່ອງອອກແລ້ວ',
            'edit-shop-bill': 'ແຈ້ງບິນແລ້ວ',
            'edit-transport-bill': 'ແຈ້ງບິນແລ້ວ'
        };
        for (const [id, doneVal] of Object.entries(statusMap)) {
            const el = document.getElementById(id);
            if (el) {
                const item = el.closest('.od-edit-status-item');
                if (item) {
                    const isDone = (el.value === doneVal);
                    item.classList.toggle('done', isDone);
                    item.classList.toggle('not-done', !isDone);
                }
            }
        }
    }

    // ===== Payment Status Change =====
    function editPaymentStatusChange() {
        const status = document.getElementById('edit-payment-status').value;
        document.getElementById('edit-deposit-group').style.display = status === 'partial' ? 'block' : 'none';
    }

    // ===== Save Order =====
    function editSaveOrder() {
        const oid = document.getElementById('edit-order-id').value;
        if (!oid) return;

        if (editItems.length === 0) {
            return Swal.fire({ icon: 'warning', title: 'ກະລຸນາເພີ່ມສິນຄ້າ' });
        }

        // Recalc final values
        const subtotalLAK = editItems.reduce((s, i) => s + (i.basePriceLAK * i.qty), 0);
        const taxableLAK = Math.max(0, subtotalLAK - editBaseDiscountLAK);
        const vatPct = parseFloat(document.getElementById('editVatPercent').value) || 10;
        const vatLAK = editVatEnabled ? taxableLAK * (vatPct / 100) : 0;
        const totalLAK = taxableLAK + vatLAK;

        const payload = {
            order_id: oid,
            customer_cu_id: document.getElementById('editCustomerCuId').value || null,
            shipping_company_sc_id: document.getElementById('editCompanyScId').value || null,
            shipping_branch_sb_id: document.getElementById('editBranchSbId').value || null,
            currencys_id: editCurrentCurrency.id,
            currency_rate: editCurrentCurrency.rate,
            vat_enabled: editVatEnabled ? 1 : 0,
            subtotal: editConvertPrice(subtotalLAK),
            discount_amount: editConvertPrice(editBaseDiscountLAK),
            tax_amount: editConvertPrice(vatLAK),
            total_amount: editConvertPrice(totalLAK),
            subtotal_lak: subtotalLAK,
            discount_lak: editBaseDiscountLAK,
            vat_amount_lak: vatLAK,
            total_amount_lak: totalLAK,
            payment_status: document.getElementById('edit-payment-status').value,
            payment_method: document.getElementById('edit-payment-method').value || null,
            deposit_amount: parseFloat(document.getElementById('edit-deposit-amount').value) || 0,
            notes: document.getElementById('edit-notes').value || null,
            bill_number: document.getElementById('edit-bill-number').value || null,
            bill_transport_number: document.getElementById('edit-bill-transport').value || null,
            shipping_date: document.getElementById('edit-shipping-date').value || null,
            print_status: document.getElementById('edit-print-status').value || null,
            prepare_status: document.getElementById('edit-prepare-status').value || null,
            front_stock_status: document.getElementById('edit-front-stock').value || null,
            pack_status: document.getElementById('edit-pack-status').value || null,
            shipping_status: document.getElementById('edit-shipping-status').value || null,
            shop_bill_status: document.getElementById('edit-shop-bill').value || null,
            transport_bill_status: document.getElementById('edit-transport-bill').value || null,
            existing_slips: editExistingSlips,
            items: editItems.map(i => ({
                product_id: i.product_id,
                product_name: i.product_name,
                quantity: i.qty,
                unit_price: i.basePriceLAK,
                total: i.basePriceLAK * i.qty
            }))
        };

        const formData = new FormData();
        formData.append('data', JSON.stringify(payload));

        if (editNewSlipFiles.length > 0) {
            editNewSlipFiles.forEach(file => {
                formData.append('slip_images[]', file);
            });
        }

        Swal.fire({ title: 'ກຳລັງບັນທຶກ...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });

        fetch('history_pos.php?ajax=update_full', {
            method: 'POST',
            body: formData
        })
            .then(r => r.json())
            .then(res => {
                if (res.status === 'success') {
                    Swal.fire({ icon: 'success', title: 'ບັນທຶກສຳເລັດ!', timer: 1500, showConfirmButton: false });
                    closeModal('edit-modal');
                    loadTablePage(1);
                } else {
                    Swal.fire({ icon: 'error', title: 'ຜິດພາດ', text: res.message || 'Update failed' });
                }
            })
            .catch(err => {
                Swal.fire({ icon: 'error', title: 'ຜິດພາດ', text: err.message });
            });
    }

    function printOrder(oid) {
        window.open('print_invoice.php?order_ids=' + oid, '_blank');
    }

    function confirmDeleteOrder(oid) {
        document.getElementById('delete-order-id').value = oid;
        document.getElementById('delete-modal').classList.add('show');
    }

    function closeModal(id) {
        document.getElementById(id).classList.remove('show');
    }

    function resetBulkSelection() {
        bulkSelectActive = false;
        document.getElementById('bulk-actions').style.display = 'none';
        document.getElementById('toggle-bulk-select').innerHTML = '<i class="fas fa-check-square"></i> ເລືອກຫຼາຍລາຍການ';
        document.querySelectorAll('.bulk-checkbox').forEach(el => el.classList.remove('show'));
        document.querySelectorAll('.order-checkbox').forEach(cb => cb.checked = false);
        document.getElementById('select-all').checked = false;
        updatePrintButton();
    }

    function updatePrintButton() {
        const checked = document.querySelectorAll('.order-checkbox:checked').length;
        document.getElementById('print-selected').disabled = checked === 0;
    }
</script>

<?php require_once '../includes/footer.php'; ?>