<?php
// ===== AJAX: Paginated Product Fetch =====
if (isset($_GET['ajax']) && $_GET['ajax'] === 'products') {
    if (session_status() === PHP_SESSION_NONE)
        session_start();
    require_once '../../include/con_data.php'; // Assuming this now provides a PDO connection as $pdo
    header('Content-Type: application/json');

    $shop_id = $_SESSION['shop_id'] ?? null;
    if (!$shop_id) {
        echo json_encode(['success' => false, 'message' => 'No shop']);
        exit;
    }

    $page = max(1, intval($_GET['page'] ?? 1));
    $limit = 16;
    $offset = ($page - 1) * $limit;
    $search = trim($_GET['search'] ?? '');
    $group = trim($_GET['group'] ?? '');

    $where = "deleted_at IS NULL AND shop_id = :shop_id";
    $params = [':shop_id' => $shop_id];

    if ($search !== '') {
        $where .= " AND (products_name LIKE :s1 OR product_code LIKE :s2 OR barcode LIKE :s3)";
        $params[':s1'] = "%$search%";
        $params[':s2'] = "%$search%";
        $params[':s3'] = "%$search%";
    }
    if ($group !== '') {
        $where .= " AND product_group = :grp";
        $params[':grp'] = $group;
    }

    try {
        $sql = "SELECT SQL_CALC_FOUND_ROWS id, product_code, products_name, price_1, price_2, product_group, image
                FROM products WHERE $where ORDER BY id ASC LIMIT $limit OFFSET $offset";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $total = intval($pdo->query("SELECT FOUND_ROWS()")->fetchColumn());

        echo json_encode([
            'success' => true,
            'data' => $data,
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'totalPages' => max(1, ceil($total / $limit))
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// ===== AJAX: Save Price Level =====
if (isset($_GET['ajax']) && $_GET['ajax'] === 'save_price_level') {
    if (session_status() === PHP_SESSION_NONE)
        session_start();
    require_once '../../include/con_data.php';

    $shop_id = $_SESSION['shop_id'] ?? null;
    if (!$shop_id) {
        echo json_encode(['success' => false, 'message' => 'No shop']);
        exit;
    }

    $data = json_decode(file_get_contents('php://input'), true);
    $price_level = isset($data['price_level']) ? intval($data['price_level']) : 1;

    try {
        $stmt = $pdo->prepare("UPDATE shops SET price_level = :price_level WHERE shop_id = :shop_id");
        $stmt->execute([':price_level' => $price_level, ':shop_id' => $shop_id]);

        $_SESSION['price_level'] = $price_level;

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

$page_title = 'ລະບົບຂາຍ (POS)';
require_once '../includes/header.php';

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

if (!$shop_id) {
    echo '<div class="alert alert-danger">ກະລຸນາເລືອກຮ້ານກ່ອນ</div>';
    require_once '../includes/footer.php';
    exit;
}

// Get categories (groups)
$categories = [];
try {
    $cResult = $conn->query("SELECT GP_id as id, group_name as category_name FROM product_group WHERE shop_id = $shop_id ORDER BY group_name");
    if ($cResult)
        $categories = $cResult->fetch_all(MYSQLI_ASSOC);
} catch (Exception $e) {
    // categories query failed
}

// Get customers
$customers = [];
try {
    $cuResult = $conn->query("SELECT id, name, phone FROM customers WHERE shop_id = $shop_id ORDER BY name");
    if ($cuResult)
        $customers = $cuResult->fetch_all(MYSQLI_ASSOC);
} catch (Exception $e) {
    // customers query failed
}

// Get shipping companies
$shippingCompanies = [];
try {
    $scResult = $conn->query("SELECT id, SC_id, company_name FROM shipping_companies WHERE shop_id = $shop_id ORDER BY company_name");
    if ($scResult)
        $shippingCompanies = $scResult->fetch_all(MYSQLI_ASSOC);
} catch (Exception $e) {
    // Table might not exist
}

// Get shipping branches
$shippingBranches = [];
try {
    $sbResult = $conn->query("SELECT id, branch_name FROM shipping_branches WHERE shop_id = " . intval($shop_id) . " ORDER BY branch_name");
    if ($sbResult)
        $shippingBranches = $sbResult->fetch_all(MYSQLI_ASSOC);
} catch (Exception $e) {
    // Table might not exist
}

// Get currencies with latest rates (simple correlated subquery like rates.php)
$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
}

// Default to LAK if no currencies
if (empty($currencies)) {
    $currencies = [['currencys_id' => 'LAK', 'currencys_name' => 'Lao Kip', 'currencys_symbol' => '₭', 'rate_amount' => 1]];
}

$user_price_level = $_SESSION['price_level'] ?? 1;
?>

<style>
    /* Prevent SweetAlert scrollbar jitter */
    html {
        scrollbar-gutter: stable;
    }

    body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) {
        padding-right: 0 !important;
        overflow: auto !important;
    }

    .swal2-container {
        overflow-y: auto !important;
    }

    /* POS Layout */
    .pos-wrapper {
        display: grid;
        grid-template-columns: 1fr 420px;
        gap: 20px;
        height: calc(100vh - 120px);
        padding: 0;
    }

    /* Products Panel */
    .products-panel {
        display: flex;
        flex-direction: column;
        background: var(--card-bg);
        border-radius: 16px;
        border: 1px solid var(--border-color);
        overflow: hidden;
    }

    .products-header {
        padding: 20px;
        border-bottom: 1px solid var(--border-color);
        display: flex;
        gap: 15px;
        flex-wrap: wrap;
        align-items: center;
    }

    .search-box {
        flex: 1;
        min-width: 200px;
        position: relative;
    }

    .search-box input {
        width: 100%;
        padding: 12px 15px 12px 45px;
        border-radius: 12px;
        border: 2px solid var(--border-color);
        background: var(--bg-primary);
        color: var(--text-primary);
        font-size: 16px;
        transition: all 0.2s;
    }

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

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

    .filter-select {
        padding: 12px 15px;
        border-radius: 12px;
        border: 2px solid var(--border-color);
        background: var(--bg-primary);
        color: var(--text-primary);
        font-size: 16px;
        min-width: 150px;
        cursor: pointer;
    }

    .filter-select:focus {
        border-color: var(--accent);
        outline: none;
    }

    .vat-toggle {
        padding: 12px 20px;
        border-radius: 12px;
        border: 2px solid var(--border-color);
        background: var(--bg-primary);
        color: var(--text-secondary);
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 8px;
        transition: all 0.2s;
    }

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

    .vat-toggle:hover {
        transform: translateY(-2px);
    }

    /* Products Grid */
    .products-grid {
        flex: 1;
        overflow-y: auto;
        padding: 20px;
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
        gap: 15px;
        align-content: start;
    }

    .products-pagination {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 20px;
        border-top: 1px solid var(--border-color);
        background: var(--bg-secondary);
        flex-shrink: 0;
    }

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

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

    .pagination-btns button {
        min-width: 34px;
        height: 34px;
        border: 1px solid var(--border-color);
        background: var(--bg-primary);
        color: var(--text-primary);
        border-radius: 8px;
        cursor: pointer;
        font-size: 13px;
        transition: all 0.2s;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 8px;
    }

    .pagination-btns button:hover:not(:disabled):not(.active) {
        background: var(--accent);
        color: #000;
        border-color: var(--accent);
    }

    .pagination-btns button.active {
        background: var(--accent);
        color: #000;
        border-color: var(--accent);
        font-weight: 700;
    }

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

    .product-card {
        background: var(--bg-primary);
        border: 2px solid var(--border-color);
        border-radius: 12px;
        padding: 12px;
        text-align: center;
        cursor: pointer;
        transition: all 0.2s;
        position: relative;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        height: 100%;
        min-height: 240px;
    }

    .product-card:hover {
        border-color: var(--accent);
        background: var(--card-bg);
        transform: translateY(-2px);
    }

    .product-card h4 {
        margin: 0 0 8px;
        font-size: 14px;
        font-weight: 600;
        color: var(--text-primary);
        line-height: 1.4;

        /* Multi-line clamp */
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        height: 40px;
        /* Fixed height for 2 lines */
    }

    .product-card .price {
        font-size: 16px;
        font-weight: 700;
        color: var(--accent);
        margin-top: auto;
        /* Push to bottom */
    }

    .product-card .stock {
        font-size: 14px;
        color: var(--text-secondary);
    }

    .product-img {
        width: 100%;
        height: 140px;
        background: var(--bg-secondary);
        border-radius: 8px;
        margin-bottom: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        position: relative;
    }

    .product-img img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .product-card .product-img i {
        font-size: 28px;
        color: var(--accent);
        opacity: 0.5;
    }

    .product-card .add-icon {
        position: absolute;
        bottom: 10px;
        right: 10px;
        width: 30px;
        height: 30px;
        background: var(--accent);
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transform: scale(0.5);
        transition: all 0.2s;
    }

    .product-card:hover .add-icon {
        opacity: 1;
        transform: scale(1);
    }

    /* Cart Panel */
    .cart-panel {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 16px;
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }

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

    .cart-header h3 {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 18px;
        color: var(--text-primary);
    }

    .clear-cart-btn {
        padding: 8px 15px;
        border-radius: 8px;
        border: none;
        background: rgba(220, 53, 69, 0.1);
        color: #dc3545;
        font-size: 13px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s;
    }

    .clear-cart-btn:hover {
        background: #dc3545;
        color: white;
    }

    .cart-items {
        flex: 1;
        overflow-y: auto;
        padding: 15px;
    }

    .cart-item {
        background: var(--bg-primary);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        padding: 12px;
        margin-bottom: 10px;
    }

    .cart-item-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 10px;
    }

    .cart-item-name {
        font-weight: 600;
        font-size: 14px;
        color: var(--text-primary);
    }

    .cart-item-remove {
        background: none;
        border: none;
        color: var(--text-secondary);
        cursor: pointer;
        padding: 5px;
        font-size: 16px;
    }

    .cart-item-remove:hover {
        color: #dc3545;
    }

    .cart-item-controls {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .qty-controls {
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .qty-btn {
        width: 32px;
        height: 32px;
        border-radius: 8px;
        border: 1px solid var(--border-color);
        background: var(--bg-primary);
        color: var(--text-primary);
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;
    }

    .qty-btn:hover {
        background: var(--accent);
        color: white;
        border-color: var(--accent);
    }

    .qty-display {
        font-weight: 600;
        width: 40px;
        text-align: center;
    }

    .item-total {
        font-weight: 700;
        color: var(--accent);
        font-size: 15px;
    }

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

    .empty-cart i {
        font-size: 48px;
        margin-bottom: 15px;
        opacity: 0.3;
    }

    /* Cart Summary */
    .cart-summary {
        padding: 20px;
        border-top: 1px solid var(--border-color);
        background: var(--bg-primary);
    }

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

    .summary-row.vat-row {
        color: #28a745;
    }

    .summary-row.total-row {
        font-size: 24px;
        font-weight: 700;
        color: var(--accent);
        padding-top: 12px;
        border-top: 2px dashed var(--border-color);
        margin-top: 12px;
    }

    .summary-row.discount-row {
        color: #dc3545;
    }

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

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

    .currency-note {
        font-size: 14px;
        color: var(--text-secondary);
        margin-top: 10px;
    }

    /* Checkout Button */
    .checkout-btn {
        width: 100%;
        padding: 16px;
        margin-top: 15px;
        border-radius: 12px;
        border: none;
        background: linear-gradient(135deg, var(--accent), #d4ac4a);
        color: white;
        font-size: 18px;
        font-weight: 700;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        transition: all 0.3s;
        box-shadow: 0 4px 15px rgba(193, 153, 42, 0.3);
    }

    .checkout-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(193, 153, 42, 0.4);
    }

    .checkout-btn:disabled {
        background: var(--border-color);
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
    }

    /* Checkout Modal */
    .pos-modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0);
        backdrop-filter: blur(0px);
        z-index: 2000;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }

    .pos-modal.show {
        opacity: 1;
        visibility: visible;
        background: rgba(0, 0, 0, 0.6);
        backdrop-filter: blur(8px);
        -webkit-backdrop-filter: blur(8px);
    }

    .pos-modal-content {
        background: var(--card-bg);
        border-radius: 20px;
        width: 100%;
        max-width: 550px;
        max-height: 90vh;
        overflow-y: auto;
        border: 1px solid var(--border-color);
        box-shadow: 0 25px 50px rgba(0, 0, 0, 0.3);
        transform: scale(0.9) translateY(-20px);
        opacity: 0;
        transition: all 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);
    }

    .pos-modal.show .pos-modal-content {
        transform: scale(1) translateY(0);
        opacity: 1;
    }

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

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

    .modal-close {
        background: none;
        border: none;
        font-size: 24px;
        color: var(--text-secondary);
        cursor: pointer;
    }

    .modal-body {
        padding: 24px;
    }

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

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

    .form-section h4 {
        font-size: 16px;
        color: var(--text-secondary);
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .form-group {
        margin-bottom: 15px;
    }

    .form-group:last-child {
        margin-bottom: 0;
    }

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

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

    .form-control:focus {
        border-color: var(--accent);
        outline: none;
    }

    .form-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 15px;
    }

    /* Input with Button */
    .input-with-btn {
        display: flex;
        gap: 8px;
    }

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

    /* Searchable Select Component */
    .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);
        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);
        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);
    }

    .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);
    }

    .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;
    }

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

    .quick-add-btn:hover {
        background: var(--accent);
        color: white;
        border-color: var(--accent);
        transform: scale(1.05);
    }

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

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

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

    .quick-add-form input {
        margin-bottom: 10px;
    }

    .quick-add-actions {
        display: flex;
        gap: 8px;
    }

    .btn-quick-save {
        flex: 1;
        padding: 8px 12px;
        border-radius: 8px;
        border: none;
        background: var(--accent);
        color: white;
        font-size: 12px;
        font-weight: 600;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5px;
        transition: all 0.2s;
    }

    .btn-quick-save:hover {
        opacity: 0.9;
        transform: translateY(-1px);
    }

    .btn-quick-cancel {
        padding: 8px 12px;
        border-radius: 8px;
        border: 2px solid var(--border-color);
        background: transparent;
        color: var(--text-secondary);
        cursor: pointer;
        transition: all 0.2s;
    }

    .btn-quick-cancel:hover {
        background: rgba(220, 53, 69, 0.1);
        color: #dc3545;
        border-color: #dc3545;
    }

    .radio-group {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
    }

    .radio-label {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 10px 15px;
        border: 2px solid var(--border-color);
        border-radius: 10px;
        cursor: pointer;
        transition: all 0.2s;
        font-size: 15px;
    }

    .radio-label:hover {
        border-color: var(--accent);
    }

    .radio-label input {
        display: none;
    }

    .radio-label.active {
        background: var(--accent);
        color: white;
        border-color: var(--accent);
    }

    .cash-section {
        background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
        border-radius: 12px;
        padding: 15px;
        margin-top: 15px;
        border: 1px solid var(--border-color);
    }

    .input-group-custom {
        position: relative;
        display: flex;
        align-items: center;
    }

    .input-group-custom .form-control {
        padding-right: 40px;
    }

    .currency-addon {
        position: absolute;
        right: 12px;
        color: var(--text-secondary);
        font-weight: 600;
        pointer-events: none;
    }

    .discount-type-toggle {
        pointer-events: auto !important;
        cursor: pointer !important;
        background: var(--border-color);
        padding: 4px 10px;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 700;
        transition: all 0.2s;
        right: 6px;
    }

    .discount-type-toggle:hover {
        background: var(--accent);
        color: white;
    }

    [data-theme="dark"] .cash-section {
        background: linear-gradient(135deg, var(--bg-secondary) 0%, var(--card-bg) 100%);
    }

    .cash-section h4 {
        margin-bottom: 15px;
        color: var(--text-primary);
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .quick-amounts {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-bottom: 12px;
    }

    .quick-amount-btn {
        padding: 8px 12px;
        border-radius: 8px;
        border: 1px solid var(--border-color);
        background: var(--bg-primary);
        color: var(--text-primary);
        font-size: 12px;
        cursor: pointer;
        transition: all 0.2s;
    }

    .quick-amount-btn:hover {
        background: var(--accent);
        color: white;
        border-color: var(--accent);
    }

    .change-display {
        background: linear-gradient(135deg, #28a745, #20c997);
        padding: 15px;
        border-radius: 10px;
        text-align: center;
        margin-top: 12px;
    }

    .change-display label {
        color: rgba(255, 255, 255, 0.9);
        font-size: 12px;
        margin-bottom: 5px;
    }

    .change-display .amount {
        font-size: 24px;
        font-weight: 700;
        color: white;
    }

    .modal-summary {
        background: var(--bg-primary);
        border-radius: 12px;
        padding: 15px;
        margin-top: 20px;
    }

    .modal-summary h4 {
        margin-bottom: 15px;
        font-size: 14px;
        color: var(--text-secondary);
    }

    .modal-order-table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 15px;
        font-size: 14px;
    }

    .modal-order-table thead th {
        text-align: left;
        padding: 8px 6px;
        font-weight: 600;
        color: var(--text-secondary);
        border-bottom: 2px solid var(--border-color);
        font-size: 12px;
        white-space: nowrap;
    }

    .modal-order-table thead th:first-child {
        width: 30px;
    }

    .modal-order-table thead th:nth-child(3) {
        width: 50px;
    }

    .modal-order-table thead th:last-child {
        width: 120px;
    }

    .modal-order-table tbody td {
        padding: 8px 6px;
        border-bottom: 1px solid var(--border-color);
        color: var(--text-primary);
        vertical-align: top;
    }

    .modal-order-table tbody td:first-child {
        color: var(--text-secondary);
    }

    .modal-order-table tbody td:last-child {
        white-space: nowrap;
        font-weight: 600;
    }

    .modal-footer {
        padding: 20px 24px;
        border-top: 1px solid var(--border-color);
        display: flex;
        gap: 10px;
    }

    .btn-cancel {
        flex: 1;
        padding: 14px;
        border-radius: 10px;
        border: 2px solid var(--border-color);
        background: transparent;
        color: var(--text-primary);
        font-weight: 600;
        cursor: pointer;
    }

    .btn-confirm {
        flex: 2;
        padding: 14px;
        border-radius: 10px;
        border: none;
        background: var(--accent);
        color: white;
        font-weight: 600;
        cursor: pointer;
    }

    /* Responsive */
    @media (max-width: 991px) {
        .pos-wrapper {
            grid-template-columns: 1fr;
            height: auto;
        }

        .products-panel {
            max-height: 60vh;
        }

        .cart-panel {
            max-height: 50vh;
        }
    }
</style>

<div class="pos-wrapper">
    <!-- Products Panel -->
    <div class="products-panel">
        <div class="products-header">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" id="searchProduct" placeholder="ຄົ້ນຫາ ຫຼື scan ສິນຄ້າ...">
            </div>
            <select id="priceLevelSelect" class="filter-select"
                onchange="savePriceLevel(this.value); updateCartPrices(); loadProducts()">
                <option value="1" <?= $user_price_level == 1 ? 'selected' : '' ?>>ລາຄາ 1</option>
                <option value="2" <?= $user_price_level == 2 ? 'selected' : '' ?>>ລາຄາ 2</option>
            </select>
            <div class="searchable-select" id="categoryFilterWrapper" style="min-width: 200px;">
                <div class="searchable-select-display" onclick="toggleSearchableSelect('categoryFilterWrapper')">
                    <span class="searchable-select-text" 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="filterSearchableSelect('categoryFilterWrapper', this.value)">
                    </div>
                    <div class="searchable-select-options">
                        <div class="searchable-select-option" data-value=""
                            onclick="selectSearchableOption('categoryFilterWrapper', '', 'ທຸກປະເພດ', {})">ທຸກປະເພດ</div>
                        <?php foreach ($categories as $cat): ?>
                            <div class="searchable-select-option" data-value="<?= $cat['id'] ?>"
                                onclick="selectSearchableOption('categoryFilterWrapper', '<?= $cat['id'] ?>', this.textContent.trim(), {})">
                                <?= htmlspecialchars($cat['category_name']) ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <input type="hidden" id="categoryFilter" value="">
            </div>
            <select id="currencySelect" class="filter-select">
                <?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'] ?? '' ?>"
                        <?= ($cur['base_currency'] ?? '') === 'YES' ? 'selected' : '' ?>>
                        <?= $cur['currencys_symbol'] ?? '₭' ?>
                        <?= htmlspecialchars($cur['currencys_name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <button id="vatToggle" class="vat-toggle" onclick="toggleVAT()">
                <i class="fas fa-percent"></i> VAT 10%
            </button>
        </div>

        <div class="products-grid" id="productsGrid">
            <div class="empty-cart" style="grid-column: 1/-1">
                <i class="fas fa-spinner fa-spin"></i>
                <p>ກຳລັງໂຫຼດ...</p>
            </div>
        </div>
        <div class="products-pagination" id="productsPagination"></div>
    </div>

    <!-- Cart Panel -->
    <div class="cart-panel">
        <div class="cart-header">
            <h3><i class="fas fa-shopping-cart"></i> ກະຕ່າສິນຄ້າ</h3>
            <button class="clear-cart-btn" onclick="clearCart()">
                <i class="fas fa-trash"></i> ລ້າງ
            </button>
        </div>

        <div class="cart-items" id="cartItems">
            <div class="empty-cart">
                <i class="fas fa-shopping-cart"></i>
                <p>ບໍ່ມີສິນຄ້າໃນກະຕ່າ</p>
            </div>
        </div>

        <div class="cart-summary">
            <div class="summary-row">
                <span>ລວມຍ່ອຍ:</span>
                <span id="subtotal">0 ₭</span>
            </div>
            <div class="summary-row discount-row">
                <span>ສ່ວນຫຼຸດ:</span>
                <div class="input-group-custom">
                    <input type="number" id="discountAmountCart" class="discount-input form-control" value="0" min="0"
                        oninput="updateDiscountBase()">
                    <span class="currency-addon discount-type-toggle" id="discountTypeToggle"
                        onclick="toggleDiscountType()"
                        style="cursor:pointer; user-select:none; min-width:30px; text-align:center;"
                        title="ກົດເພື່ອສະຫຼັບ">₭</span>
                </div>
            </div>
            <div class="summary-row vat-row" id="vatRow" style="display: none;">
                <span>VAT (10%):</span>
                <span id="vatAmount">0 ₭</span>
            </div>
            <div class="summary-row total-row">
                <span>ລວມທັງໝົດ:</span>
                <span id="grandTotal">0 ₭</span>
            </div>
            <div class="currency-note" id="currencyNote">ລາຄາເປັນ: ກີບລາວ</div>

            <button class="checkout-btn" id="checkoutBtn" onclick="startCheckout()" disabled>
                <i class="fas fa-check-circle"></i> ຊໍາລະເງິນ
            </button>
        </div>
    </div>
</div>

<!-- Checkout Modal -->
<div class="pos-modal" id="checkoutModal">
    <div class="pos-modal-content">
        <div class="modal-header">
            <h2><i class="fas fa-receipt"></i> <span id="modalTitle">ຢືນຢັນການຊໍາລະ</span></h2>
            <button class="modal-close" onclick="closeCheckoutModal()">&times;</button>
        </div>
        <div class="modal-body">
            <!-- Section 1: Customer Info (Online Only) -->
            <div class="form-section" id="sectionCustomer">
                <h4><i class="fas fa-user"></i> 1. ຂໍ້ມູນລູກຄ້າ</h4>
                <div class="form-row">
                    <div class="form-group">
                        <label>ເລືອກລູກຄ້າ:</label>
                        <div class="input-with-btn">
                            <div class="searchable-select" id="customerSelectWrapper">
                                <div class="searchable-select-display"
                                    onclick="toggleSearchableSelect('customerSelectWrapper')">
                                    <span class="searchable-select-text"
                                        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="filterSearchableSelect('customerSelectWrapper', this.value)">
                                    </div>
                                    <div class="searchable-select-options">
                                        <div class="searchable-select-option" data-value=""
                                            onclick="selectSearchableOption('customerSelectWrapper', '', 'ເລືອກລູກຄ້າ', {})">
                                            ເລືອກລູກຄ້າ</div>
                                        <?php foreach ($customers as $cust): ?>
                                            <div class="searchable-select-option" data-value="<?= $cust['id'] ?>"
                                                data-name="<?= htmlspecialchars($cust['name']) ?>"
                                                data-phone="<?= htmlspecialchars($cust['phone'] ?? '') ?>"
                                                onclick="selectSearchableOption('customerSelectWrapper', '<?= $cust['id'] ?>', this.textContent.trim(), {name:'<?= htmlspecialchars(addslashes($cust['name'])) ?>', phone:'<?= htmlspecialchars(addslashes($cust['phone'] ?? '')) ?>'})">
                                                <?= htmlspecialchars($cust['name']) ?> -
                                                <?= htmlspecialchars($cust['phone'] ?? '') ?>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <input type="hidden" id="customerSelect" value="">
                            </div>
                            <button type="button" class="quick-add-btn" onclick="showQuickAddCustomer()"
                                title="ເພີ່ມລູກຄ້າໃໝ່">
                                <i class="fas fa-plus"></i>
                            </button>
                        </div>
                        <!-- Quick Add Customer Form -->
                        <div id="quickAddCustomerForm" class="quick-add-form" style="display:none;">
                            <input type="text" id="newCustomerName" class="form-control" placeholder="ຊື່ລູກຄ້າ"
                                style="margin-bottom:8px;">
                            <input type="text" id="newCustomerPhone" class="form-control" placeholder="ເບີໂທ">
                            <div class="quick-add-actions">
                                <button type="button" class="btn-quick-save" onclick="saveQuickCustomer()">
                                    <i class="fas fa-check"></i> ບັນທຶກ
                                </button>
                                <button type="button" class="btn-quick-cancel" onclick="hideQuickAddCustomer()">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Hidden inputs for customer data -->
                <input type="hidden" id="customerName">
                <input type="hidden" id="customerPhone">
            </div>

            <!-- Section 2: Shipping Info (Online Only) -->
            <div class="form-section" id="sectionShipping">
                <h4><i class="fas fa-truck"></i> 2. ຂໍ້ມູນຂົນສົ່ງ</h4>
                <div class="form-row">
                    <div class="form-group">
                        <label>ບໍລິສັດຂົນສົ່ງ:</label>
                        <div class="input-with-btn">
                            <div class="searchable-select" id="shippingCompanyWrapper">
                                <div class="searchable-select-display"
                                    onclick="toggleSearchableSelect('shippingCompanyWrapper')">
                                    <span class="searchable-select-text"
                                        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="filterSearchableSelect('shippingCompanyWrapper', this.value)">
                                    </div>
                                    <div class="searchable-select-options">
                                        <div class="searchable-select-option" data-value=""
                                            onclick="selectSearchableOption('shippingCompanyWrapper', '', 'ເລືອກບໍລິສັດ', {})">
                                            ເລືອກບໍລິສັດ</div>
                                        <?php foreach ($shippingCompanies as $sc): ?>
                                            <div class="searchable-select-option" data-value="<?= $sc['id'] ?>"
                                                onclick="selectSearchableOption('shippingCompanyWrapper', '<?= $sc['id'] ?>', this.textContent.trim(), {})">
                                                <?= htmlspecialchars($sc['company_name']) ?>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <input type="hidden" id="shippingCompany" value="">
                            </div>
                            <button type="button" class="quick-add-btn" onclick="showQuickAddCompany()"
                                title="ເພີ່ມບໍລິສັດໃໝ່">
                                <i class="fas fa-plus"></i>
                            </button>
                        </div>
                        <!-- Quick Add Company Form -->
                        <div id="quickAddCompanyForm" class="quick-add-form" style="display:none;">
                            <input type="text" id="newCompanyName" class="form-control" placeholder="ຊື່ບໍລິສັດໃໝ່">
                            <div class="quick-add-actions">
                                <button type="button" class="btn-quick-save" onclick="saveQuickCompany()">
                                    <i class="fas fa-check"></i> ບັນທຶກ
                                </button>
                                <button type="button" class="btn-quick-cancel" onclick="hideQuickAddCompany()">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>ສາຂາຂົນສົ່ງ:</label>
                        <div class="input-with-btn">
                            <div class="searchable-select" id="shippingBranchWrapper">
                                <div class="searchable-select-display"
                                    onclick="toggleSearchableSelect('shippingBranchWrapper')">
                                    <span class="searchable-select-text" 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="filterSearchableSelect('shippingBranchWrapper', this.value)">
                                    </div>
                                    <div class="searchable-select-options">
                                        <div class="searchable-select-option" data-value=""
                                            onclick="selectSearchableOption('shippingBranchWrapper', '', 'ເລືອກສາຂາ', {})">
                                            ເລືອກສາຂາ</div>
                                        <?php foreach ($shippingBranches as $sb): ?>
                                            <div class="searchable-select-option" data-value="<?= $sb['id'] ?>"
                                                onclick="selectSearchableOption('shippingBranchWrapper', '<?= $sb['id'] ?>', this.textContent.trim(), {})">
                                                <?= htmlspecialchars($sb['branch_name']) ?>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <input type="hidden" id="shippingBranch" value="">
                            </div>
                            <button type="button" class="quick-add-btn" onclick="showQuickAddBranch()"
                                title="ເພີ່ມສາຂາໃໝ່">
                                <i class="fas fa-plus"></i>
                            </button>
                        </div>
                        <!-- Quick Add Branch Form -->
                        <div id="quickAddBranchForm" class="quick-add-form" style="display:none;">
                            <input type="text" id="newBranchName" class="form-control" placeholder="ຊື່ສາຂາໃໝ່">
                            <div class="quick-add-actions">
                                <button type="button" class="btn-quick-save" onclick="saveQuickBranch()">
                                    <i class="fas fa-check"></i> ບັນທຶກ
                                </button>
                                <button type="button" class="btn-quick-cancel" onclick="hideQuickAddBranch()">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Section 3: COD Type (Online Only) -->
            <div class="form-section" id="sectionCOD">
                <h4><i class="fas fa-money-check-alt"></i> 3. ຄ່າຝາກ</h4>
                <div class="radio-group" id="codTypeGroup">
                    <label class="radio-label" onclick="selectRadio(this, 'codType')">
                        <input type="radio" name="codType" value="ຕົ້ນທາງ"> ຕົ້ນທາງ
                    </label>
                    <label class="radio-label" onclick="selectRadio(this, 'codType')">
                        <input type="radio" name="codType" value="ປາຍທາງ"> ປາຍທາງ
                    </label>
                </div>
            </div>

            <!-- Section 4: Payment Status -->
            <div class="form-section" id="sectionPaymentStatus">
                <h4><i class="fas fa-credit-card"></i> <span class="section-number">4</span>. ສະຖານະການຈ່າຍ</h4>
                <div class="radio-group" id="paymentStatusGroup">
                    <label class="radio-label" onclick="selectPaymentStatus(this, 'paid')">
                        <input type="radio" name="paymentStatus" value="paid"> ຈ່າຍແລ້ວ
                    </label>
                    <label class="radio-label" onclick="selectPaymentStatus(this, 'partial')">
                        <input type="radio" name="paymentStatus" value="partial"> ມັດຈຳ
                    </label>
                    <label class="radio-label" onclick="selectPaymentStatus(this, 'pending')">
                        <input type="radio" name="paymentStatus" value="pending"> ຍັງບໍ່ຈ່າຍ
                    </label>
                </div>
                <div class="form-group" id="depositGroup" st yle="display: none; margin-top: 15px;">
                    <label>ຈຳນວນມັດຈຳ:</label>
                    <div class="input-group-custom">
                        <input type="number" id="depositAmount" class="form-control" placeholder="0"
                            oninput="updateModalTotals()">
                        <span class="currency-addon">₭</span>
                    </div>
                </div>
            </div>

            <!-- Section 5: Payment Method -->
            <div class="form-section" id="sectionPaymentMethod">
                <h4><i class="fas fa-wallet"></i> <span class="section-number">5</span>. ວິທີຊໍາລະ</h4>
                <div class="radio-group" id="paymentMethodGroup">
                    <label class="radio-label" onclick="selectPaymentMethod(this, 'cash')">
                        <input type="radio" name="paymentMethod" value="cash"> ເງິນສົດ
                    </label>
                    <label class="radio-label" onclick="selectPaymentMethod(this, 'transfer')">
                        <input type="radio" name="paymentMethod" value="transfer"> ໂອນ
                    </label>
                </div>

                <!-- Transfer Section -->
                <div class="transfer-section" id="transferSection" style="display: none;">
                    <h4><i class="fas fa-file-invoice-dollar"></i> ອັບໂຫລດຮູບສະລິບ (ຖ້າມີ)</h4>
                    <div class="form-group">
                        <input type="file" id="slipImage" class="form-control" accept="image/*" multiple
                            style="display:none" onchange="previewSlipImages(event)">

                        <button type="button" class="btn-pro secondary"
                            onclick="document.getElementById('slipImage').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="slip-count" style="margin-left:8px;font-size:13px;color:var(--text-secondary)"></span>

                        <!-- Paste & Drop Zone -->
                        <div id="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)'">

                            <div id="slipPreviewContainer" style="display: none; margin-top: 10px;">
                                <div id="slipPreviewGrid" style="display:flex;flex-wrap:wrap;gap:10px;"></div>
                            </div>

                            <div id="slip-empty-state" class="od-slip-empty"
                                style="text-align:center;color:var(--text-secondary)">
                                <i class="fas fa-image"
                                    style="font-size:32px;opacity:0.3;margin-bottom:8px;display:block"></i>
                                ບໍ່ມີຫຼັກຖານການໂອນ<br>
                                <span style="font-size:12px;opacity:0.7;">(ຄລິກທີ່ນີ້ແລ້ວກົດ Paste)</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Cash Section -->
                <div class="cash-section" id="cashSection" style="display: none;">
                    <h4><i class="fas fa-cash-register"></i> ການຮັບເງິນສົດ</h4>
                    <div class="quick-amounts" id="quickAmounts"></div>
                    <div class="form-group">
                        <label>ຮັບເງິນ:</label>
                        <input type="number" id="cashReceived" class="form-control" placeholder="0"
                            oninput="calculateChange()">
                    </div>
                    <div class="change-display">
                        <label>ເງິນທອນ:</label>
                        <div class="amount" id="changeAmount">0 ₭</div>
                    </div>
                </div>
            </div>


            <!-- Order Summary -->
            <div class="modal-summary">
                <h4>ສະຫຼຸບລາຍການ</h4>
                <table class="modal-order-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>ສິນຄ້າ</th>
                            <th style="text-align:center;">ຈຳນວນ</th>
                            <th style="text-align:right;">ລາຄາ</th>
                        </tr>
                    </thead>
                    <tbody id="modalOrderItems"></tbody>
                </table>
                <div class="summary-row" style="margin-top: 15px;">
                    <span>ລວມຍ່ອຍ:</span>
                    <span id="modalSubtotal">0 ₭</span>
                </div>
                <div class="summary-row">
                    <span>ສ່ວນຫຼຸດ:</span>
                    <span id="modalDiscount">0 ₭</span>
                </div>
                <div class="summary-row" id="modalDepositRow" style="display: none;">
                    <span>ມັດຈຳ:</span>
                    <span id="modalDeposit">0 ₭</span>
                </div>
                <div class="summary-row vat-row" id="modalVatRow">
                    <span>VAT (10%):</span>
                    <span id="modalVat">0 ₭</span>
                </div>
                <div class="summary-row total-row">
                    <span>ຍອດລວມ:</span>
                    <span id="modalTotal">0 ₭</span>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn-cancel" onclick="closeCheckoutModal()">ຍົກເລີກ</button>
            <button class="btn-confirm" id="confirmOrderBtn" onclick="submitOrder()">
                <i class="fas fa-check"></i> ຢືນຢັນ
            </button>
        </div>
    </div>

    <script>
        // Initialize Data
        let shippingBranches = <?= json_encode($shippingBranches) ?>;
        let cart = [];
        let vatEnabled = false;
        let saleMode = 'pos'; // 'online' or 'pos'
        let baseDiscountLAK = 0; // Discount in LAK (Base Currency)
        let currentPage = 1;
        let totalPages = 1;
        let searchTimer = null;

        // Currency Setup
        const currencySelect = document.getElementById('currencySelect');
        let currentCurrency = {
            id: currencySelect.value,
            symbol: currencySelect.options[currencySelect.selectedIndex].dataset.symbol,
            rate: parseFloat(currencySelect.options[currencySelect.selectedIndex].dataset.rate),
            rateId: currencySelect.options[currencySelect.selectedIndex].dataset.rateId
        };

        // Event Listeners - debounce search (with barcode decode)
        document.getElementById('searchProduct').addEventListener('input', function () {
            clearTimeout(searchTimer);
            searchTimer = setTimeout(function () {
                var searchBox = document.getElementById('searchProduct');
                var val = searchBox.value.trim();
                // Auto-decode ASCII-encoded barcodes
                var decoded = decodeAsciiBarcode(val);
                if (decoded !== val) {
                    searchBox.value = decoded;
                    // Auto-add to cart via barcode
                    scanAndAddToCart(decoded);
                    return;
                }
                // If it looks like a normal barcode (all digits, 8-14 chars), auto-add
                if (/^\d{8,14}$/.test(val)) {
                    scanAndAddToCart(val);
                    return;
                }
                currentPage = 1;
                loadProducts();
            }, 500);
        });

        // Handle Enter key on search box for barcode scanning
        document.getElementById('searchProduct').addEventListener('keydown', function (e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                clearTimeout(searchTimer);
                var val = this.value.trim();
                var decoded = decodeAsciiBarcode(val);
                if (decoded !== val) {
                    this.value = decoded;
                    val = decoded;
                }
                if (/^\d{4,}$/.test(val)) {
                    scanAndAddToCart(val);
                } else {
                    currentPage = 1;
                    loadProducts();
                }
            }
        });
        // Observer for custom searchable select change
        // Since searchable-select updates a hidden input, we listen to its value change
        var categoryObserver = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                if (mutation.type === 'attributes' && mutation.attributeName === 'value') {
                    currentPage = 1;
                    loadProducts();
                }
            });
        });

        var categoryInput = document.getElementById('categoryFilter');
        if (categoryInput) {
            categoryObserver.observe(categoryInput, { attributes: true });
        }

        currencySelect.addEventListener('change', function () {
            const opt = this.options[this.selectedIndex];
            currentCurrency = {
                id: this.value,
                symbol: opt.dataset.symbol,
                rate: parseFloat(opt.dataset.rate),
                rateId: opt.dataset.rateId
            };

            // Update Discount Inputs based on new rate
            let newDiscountDisp = convertPrice(baseDiscountLAK);

            if (currentCurrency.id === 'CUR_3' || currentCurrency.symbol === '$') {
                newDiscountDisp = parseFloat(newDiscountDisp.toFixed(2));
            } else {
                newDiscountDisp = Math.round(newDiscountDisp);
            }

            document.getElementById('discountAmountCart').value = newDiscountDisp;

            // Update Currency Addons (skip discount toggle)
            document.querySelectorAll('.currency-addon').forEach(el => {
                if (!el.classList.contains('discount-type-toggle')) {
                    el.textContent = currentCurrency.symbol;
                }
            });
            // Update discount toggle only if it's in fixed mode
            if (discountType === 'fixed') {
                document.getElementById('discountTypeToggle').textContent = currentCurrency.symbol;
            }

            // Update UI
            loadProducts();
            renderCart();
            updateTotals();

            // Update currency note
            document.getElementById('currencyNote').textContent = `ລາຄາເປັນ: ${opt.text.trim()}`;
        });

        // ===== Product Logic (AJAX Paginated) =====
        let loadingProducts = false;

        function savePriceLevel(level) {
            fetch('pos.php?ajax=save_price_level', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ price_level: level })
            }).then(res => res.json()).then(data => {
                if (!data.success) {
                    console.error('Failed to save price level:', data.message);
                }
            }).catch(err => console.error('Error saving price level:', err));
        }

        function loadProducts(page) {
            if (loadingProducts) return;
            loadingProducts = true;

            if (page) currentPage = page;
            const search = document.getElementById('searchProduct').value.trim();
            const group = document.getElementById('categoryFilter').value;

            const grid = document.getElementById('productsGrid');
            grid.innerHTML = '<div class="loading-products" style="grid-column:1/-1;text-align:center;padding:40px;"><i class="fas fa-spinner fa-spin" style="font-size:24px;color:var(--accent)"></i><p style="margin-top:10px;color:var(--text-secondary)">ກຳລັງໂຫຼດ...</p></div>';

            const params = new URLSearchParams({ ajax: 'products', page: currentPage, search, group });
            fetch(`pos.php?${params}`)
                .then(r => r.json())
                .then(data => {
                    loadingProducts = false;
                    if (data.success) {
                        totalPages = data.totalPages;
                        renderProducts(data.data, data.total);
                        renderPagination(data.page, data.totalPages, data.total);
                    } else {
                        grid.innerHTML = '<div class="empty-cart" style="grid-column:1/-1"><i class="fas fa-exclamation-triangle"></i><p>ເກີດຂໍ້ຜິດພາດ</p></div>';
                    }
                })
                .catch(() => {
                    loadingProducts = false;
                    grid.innerHTML = '<div class="empty-cart" style="grid-column:1/-1"><i class="fas fa-exclamation-triangle"></i><p>ເກີດຂໍ້ຜິດພາດ</p></div>';
                });
        }

        function renderProducts(products, total) {
            const grid = document.getElementById('productsGrid');
            grid.innerHTML = '';

            if (products.length === 0) {
                grid.innerHTML = `
                <div class="empty-cart" style="grid-column: 1/-1">
                    <i class="fas fa-box-open"></i>
                    <p>ບໍ່ພົບສິນຄ້າ</p>
                </div>`;
                return;
            }

            const priceLevel = document.getElementById('priceLevelSelect') ? document.getElementById('priceLevelSelect').value : '1';

            products.forEach(p => {
                const rawPrice2 = parseFloat(p.price_2);
                const priceVal = priceLevel === '2' && !isNaN(rawPrice2) ? rawPrice2 : parseFloat(p.price_1);
                const price = convertPrice(priceVal);
                const card = document.createElement('div');
                card.className = 'product-card';
                card.onclick = (e) => {
                    // Fly to Cart Animation
                    // Target image OR icon
                    const flyEl = card.querySelector('.product-img img') || card.querySelector('.product-img i');
                    // Get cart icon destination (top right of cart panel)
                    // Get cart icon destination (top right of cart panel)
                    const cartPanel = document.querySelector('.cart-header h3 i');
                    const cartContainer = document.querySelector('.cart-panel');

                    // Fallback destination
                    const dest = cartPanel || cartContainer;

                    if (flyEl && dest) {
                        animateFlyToCart(flyEl, dest);
                    }
                    addToCart(p);
                };
                card.innerHTML = `
                <div class="product-img">
                    ${p.image ? `<img src="../api/get_image.php?f=${p.image}&w=200" alt="" loading="lazy" decoding="async">` : '<i class="fas fa-box"></i>'}
                </div>
                <h4>${p.products_name}</h4>
                <div class="price">${formatNumber(price)} ${currentCurrency.symbol}</div>
                <div class="add-icon"><i class="fas fa-plus"></i></div>
            `;
                grid.appendChild(card);
            });
        }

        function renderPagination(page, pages, total) {
            const container = document.getElementById('productsPagination');
            if (pages <= 1) { container.innerHTML = ''; return; }

            let html = `<span class="pagination-info">ໜ້າ ${page}/${pages} (${total.toLocaleString()} ລາຍການ)</span><div class="pagination-btns">`;

            // Prev
            html += `<button ${page <= 1 ? 'disabled' : ''} onclick="loadProducts(${page - 1})"><i class="fas fa-chevron-left"></i></button>`;

            // Page numbers (show max 5 around current)
            let start = Math.max(1, page - 2);
            let end = Math.min(pages, start + 4);
            if (end - start < 4) start = Math.max(1, end - 4);

            if (start > 1) {
                html += `<button onclick="loadProducts(1)">1</button>`;
                if (start > 2) html += `<button disabled>...</button>`;
            }
            for (let i = start; i <= end; i++) {
                html += `<button class="${i === page ? 'active' : ''}" onclick="loadProducts(${i})">${i}</button>`;
            }
            if (end < pages) {
                if (end < pages - 1) html += `<button disabled>...</button>`;
                html += `<button onclick="loadProducts(${pages})">${pages}</button>`;
            }

            // Next
            html += `<button ${page >= pages ? 'disabled' : ''} onclick="loadProducts(${page + 1})"><i class="fas fa-chevron-right"></i></button>`;
            html += '</div>';

            container.innerHTML = html;
        }

        // ===== Cart Logic =====
        function addToCart(product) {
            const priceLevel = document.getElementById('priceLevelSelect') ? document.getElementById('priceLevelSelect').value : '1';
            const rawPrice2 = parseFloat(product.price_2);
            const priceVal = priceLevel === '2' && !isNaN(rawPrice2) ? rawPrice2 : parseFloat(product.price_1);

            const existing = cart.find(i => i.id === product.id);
            if (existing) {
                existing.qty++;
            } else {
                cart.push({
                    id: product.id,
                    name: product.products_name,
                    basePriceLAK: priceVal,
                    qty: 1,
                    price_1: product.price_1,
                    price_2: product.price_2
                });
            }
            renderCart();
            updateTotals();
        }

        function removeFromCart(index) {
            cart.splice(index, 1);
            renderCart();
            updateTotals();
        }

        function updateCartPrices() {
            const priceLevel = document.getElementById('priceLevelSelect') ? document.getElementById('priceLevelSelect').value : '1';
            cart.forEach(item => {
                const rawPrice2 = parseFloat(item.price_2);
                item.basePriceLAK = priceLevel === '2' && !isNaN(rawPrice2) ? rawPrice2 : parseFloat(item.price_1);
            });
            renderCart();
            updateTotals();
        }

        function updateQty(index, change) {
            const item = cart[index];
            const newQty = item.qty + change;

            if (newQty > 0) {
                item.qty = newQty;
                renderCart();
                updateTotals();
            }
        }

        function clearCart() {
            if (cart.length === 0) return;

            Swal.fire({
                title: 'ຢືນຢັນການລ້າງກະຕ່າ?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'ລ້າງເລີຍ'
            }).then((result) => {
                if (result.isConfirmed) {
                    cart = [];
                    baseDiscountLAK = 0;
                    discountType = 'fixed';
                    document.getElementById('discountAmountCart').value = 0;
                    const dt = document.getElementById('discountTypeToggle');
                    dt.textContent = currentCurrency.symbol;
                    dt.style.background = '';
                    dt.style.color = '';
                    renderCart();
                    updateTotals();
                }
            });
        }

        function renderCart() {
            const container = document.getElementById('cartItems');
            container.innerHTML = '';

            if (cart.length === 0) {
                container.innerHTML = `
                <div class="empty-cart">
                    <i class="fas fa-shopping-cart"></i>
                    <p>ບໍ່ມີສິນຄ້າໃນກະຕ່າ</p>
                </div>`;
                document.getElementById('checkoutBtn').disabled = true;
                return;
            }

            document.getElementById('checkoutBtn').disabled = false;

            cart.forEach((item, index) => {
                const price = convertPrice(item.basePriceLAK);
                const div = document.createElement('div');
                div.className = 'cart-item';
                div.innerHTML = `
                <div class="cart-item-header">
                    <span class="cart-item-name">${item.name}</span>
                    <button class="cart-item-remove" onclick="removeFromCart(${index})"><i class="fas fa-times"></i></button>
                </div>
                <div class="cart-item-controls">
                    <div class="qty-controls">
                        <button class="qty-btn" onclick="updateQty(${index}, -1)"><i class="fas fa-minus"></i></button>
                        <span class="qty-display">${item.qty}</span>
                        <button class="qty-btn" onclick="updateQty(${index}, 1)"><i class="fas fa-plus"></i></button>
                    </div>
                    <span class="item-total">${formatNumber(price * item.qty)} ${currentCurrency.symbol}</span>
                </div>
            `;
                container.appendChild(div);
            });
        }

        // ===== Calculation Logic =====
        function toggleVAT() {
            vatEnabled = !vatEnabled;
            const btn = document.getElementById('vatToggle');
            if (vatEnabled) btn.classList.add('active');
            else btn.classList.remove('active');

            updateTotals();
        }

        function convertPrice(lakAmount) {
            if (currentCurrency.rate === 1) return lakAmount;
            return lakAmount / currentCurrency.rate;
        }

        // Reverse conversion: Display Amount -> LAK
        // Note: Used when inputting discount in foreign currency
        function convertToLAK(displayAmount) {
            if (currentCurrency.rate === 1) return displayAmount; // LAK
            return displayAmount * currentCurrency.rate;
        }

        // Calculates tip/rounding difference for foreign currencies
        // Logic from source: Tip = Rounded Total - Raw Total
        function convertPriceRaw(lakAmount) {
            if (currentCurrency.rate === 1) return lakAmount;
            return lakAmount / currentCurrency.rate;
        }

        let discountType = 'fixed'; // 'fixed' or 'percent'

        function toggleDiscountType() {
            const toggle = document.getElementById('discountTypeToggle');
            if (discountType === 'fixed') {
                discountType = 'percent';
                toggle.textContent = '%';
                toggle.style.background = 'linear-gradient(135deg, #28a745, #20c997)';
                toggle.style.color = 'white';
            } else {
                discountType = 'fixed';
                toggle.textContent = currentCurrency.symbol;
                toggle.style.background = '';
                toggle.style.color = '';
            }
            updateDiscountBase();
        }

        function updateDiscountBase() {
            const val = parseFloat(document.getElementById('discountAmountCart').value) || 0;
            const subtotalLAK = cart.reduce((sum, i) => sum + (i.basePriceLAK * i.qty), 0);

            if (discountType === 'percent') {
                const pct = Math.min(val, 100);
                baseDiscountLAK = subtotalLAK * (pct / 100);
            } else {
                baseDiscountLAK = convertToLAK(val);
            }

            // Sync modal totals if open
            if (document.getElementById('checkoutModal').classList.contains('show')) {
                updateModalTotals();
            }

            updateTotals();
        }

        function updateTotals() {
            const subtotalLAK = cart.reduce((sum, i) => sum + (i.basePriceLAK * i.qty), 0);

            // Calculate VAT
            // Logic: VAT is applied to (Subtotal - Discount)
            // If discount > subtotal, tax base is 0
            const taxableLAK = Math.max(0, subtotalLAK - baseDiscountLAK);
            const vatLAK = vatEnabled ? taxableLAK * 0.1 : 0;
            const totalLAK = taxableLAK + vatLAK;

            // Display Data
            const subtotalDisp = convertPrice(subtotalLAK);
            const vatDisp = convertPrice(vatLAK);
            const totalDisp = convertPrice(totalLAK);

            document.getElementById('subtotal').textContent = formatNumber(subtotalDisp) + ' ' + currentCurrency.symbol;
            document.getElementById('vatAmount').textContent = formatNumber(vatDisp) + ' ' + currentCurrency.symbol;
            document.getElementById('grandTotal').textContent = formatTotal(totalDisp) + ' ' + currentCurrency.symbol;

            document.getElementById('vatRow').style.display = vatEnabled ? 'flex' : 'none';
        }

        // ===== Checkout Modal =====
        function startCheckout() {
            if (cart.length === 0) return;

            // ປິດການໃຊ້ງານ ຂາຍໜ້າຮ້ານ ຊົ່ວຄາວ - ໃຊ້ແຕ່ຂາຍອອນລາຍ
            // Swal.fire({
            //     title: 'ປະເພດການຂາຍ',
            //     text: 'ທ່ານຕ້ອງການຂາຍແບບໃດ?',
            //     icon: 'question',
            //     showDenyButton: true,
            //     showCancelButton: true,
            //     confirmButtonText: '<i class="fas fa-globe"></i> ຂາຍອອນລາຍ',
            //     denyButtonText: '<i class="fas fa-store"></i> ຂາຍໜ້າຮ້ານ',
            //     cancelButtonText: 'ຍົກເລີກ',
            //     confirmButtonColor: '#3085d6',
            //     denyButtonColor: '#28a745'
            // }).then((result) => {
            //     if (result.isConfirmed) {
            //         openCheckoutModal('online');
            //     } else if (result.isDenied) {
            //         openCheckoutModal('pos');
            //     }
            // });

            // ເປີດ checkout ແບບອອນລາຍໂດຍກົງ
            openCheckoutModal('online');
        }

        function openCheckoutModal(mode) {
            saleMode = mode;
            const modal = document.getElementById('checkoutModal');
            const title = document.getElementById('modalTitle');

            // Toggle Sections
            const onlineSections = ['sectionCustomer', 'sectionShipping', 'sectionCOD'];
            onlineSections.forEach(id => {
                document.getElementById(id).style.display = mode === 'online' ? 'block' : 'none';
            });

            title.textContent = mode === 'online' ? 'ຊໍາລະເງິນ (ອອນລາຍ)' : 'ຊໍາລະເງິນ (ໜ້າຮ້ານ)';

            // Populate specific fields based on mode
            if (mode === 'pos') {
                // Uncheck unnecessary inputs to avoid validation errors
                document.querySelectorAll('input[name="codType"]').forEach(el => el.checked = false);
            } else {
                // Reset customer inputs
                resetSearchableSelect('customerSelectWrapper');
                document.getElementById('customerName').value = "";
                document.getElementById('customerPhone').value = "";
                resetSearchableSelect('shippingCompanyWrapper');
                resetSearchableSelect('shippingBranchWrapper');
            }

            // Reset payment to no selection
            document.querySelectorAll('input[name="paymentStatus"]').forEach(el => el.checked = false);
            document.querySelectorAll('input[name="paymentMethod"]').forEach(el => el.checked = false);
            // Reset inputs
            document.getElementById('depositAmount').value = '';
            document.getElementById('cashReceived').value = '';
            document.getElementById('slipImage').value = '';
            if (document.getElementById('slipPreviewContainer')) {
                document.getElementById('slipPreviewContainer').style.display = 'none';
                document.getElementById('slipPreviewGrid').innerHTML = '';
            }

            // Remove active classes
            document.querySelectorAll('#paymentStatusGroup .radio-label, #paymentMethodGroup .radio-label').forEach(el => el.classList.remove('active'));

            // Hide all conditional sections
            document.getElementById('depositGroup').style.display = 'none';
            document.getElementById('sectionPaymentMethod').style.display = 'none';
            document.getElementById('cashSection').style.display = 'none';
            document.getElementById('transferSection').style.display = 'none';
            document.getElementById('modalDepositRow').style.display = 'none';

            updateModalTotals();
            modal.classList.add('show');
        }

        function closeCheckoutModal() {
            document.getElementById('checkoutModal').classList.remove('show');
        }

        function previewSlipImages(event) {
            const input = event.target;
            const container = document.getElementById('slipPreviewContainer');
            const grid = document.getElementById('slipPreviewGrid');
            grid.innerHTML = '';

            if (input.files && input.files.length > 0) {
                container.style.display = 'block';
                Array.from(input.files).forEach((file, idx) => {
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        const wrapper = document.createElement('div');
                        wrapper.style.cssText = 'position:relative;display:inline-block;';
                        wrapper.innerHTML = `
                            <img src="${e.target.result}" style="width:120px;height:120px;object-fit:cover;border-radius:8px;border:1px solid var(--border-color);">
                            <div style="position:absolute;top:-6px;right:-6px;width:22px;height:22px;background:#dc3545;border-radius:50%;color:#fff;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:12px;box-shadow:0 2px 6px rgba(0,0,0,0.2);" onclick="removeSlipImage(${idx})">
                                <i class="fas fa-times"></i>
                            </div>
                        `;
                        grid.appendChild(wrapper);
                    };
                    reader.readAsDataURL(file);
                });
            } else {
                container.style.display = 'none';
            }
        }

        function removeSlipImage(idx) {
            const input = document.getElementById('slipImage');
            const dt = new DataTransfer();
            Array.from(input.files).forEach((file, i) => {
                if (i !== idx) dt.items.add(file);
            });
            input.files = dt.files;
            previewSlipImages({ target: input });
        }

        // Modal Interaction
        function selectRadio(el, groupName) {
            const input = el.querySelector('input');
            input.checked = true;

            // Update visual
            const labels = el.parentElement.querySelectorAll('.radio-label');
            labels.forEach(l => l.classList.remove('active'));
            el.classList.add('active');
        }

        function selectPaymentStatus(el, status) {
            selectRadio(el, 'paymentStatus');

            const depositGroup = document.getElementById('depositGroup');
            const modalDepositRow = document.getElementById('modalDepositRow');
            const paymentMethodSection = document.getElementById('sectionPaymentMethod');
            const cashSection = document.getElementById('cashSection');
            const transferSection = document.getElementById('transferSection');

            if (status === 'partial') {
                depositGroup.style.display = 'block';
                modalDepositRow.style.display = 'flex';
            } else {
                depositGroup.style.display = 'none';
                modalDepositRow.style.display = 'none';
                document.getElementById('depositAmount').value = '';
            }

            if (status === 'pending') {
                paymentMethodSection.style.display = 'none';
                cashSection.style.display = 'none';
                transferSection.style.display = 'none';
            } else {
                paymentMethodSection.style.display = 'block';
                // Re-trigger payment method visibility check
                const method = document.querySelector('input[name="paymentMethod"]:checked')?.value;
                if (method === 'cash') {
                    cashSection.style.display = 'block';
                    transferSection.style.display = 'none';
                } else if (method === 'transfer') {
                    cashSection.style.display = 'none';
                    transferSection.style.display = 'block';
                } else { // No method selected or other method
                    cashSection.style.display = 'none';
                    transferSection.style.display = 'none';
                }
            }

            updateModalTotals();
        }

        function selectPaymentMethod(el, method) {
            selectRadio(el, 'paymentMethod');

            const status = document.querySelector('input[name="paymentStatus"]:checked')?.value;
            const cashSection = document.getElementById('cashSection');
            const transferSection = document.getElementById('transferSection');

            if (status !== 'pending') {
                if (method === 'cash') {
                    cashSection.style.display = 'block';
                    transferSection.style.display = 'none';
                    generateQuickAmounts();
                } else if (method === 'transfer') {
                    cashSection.style.display = 'none';
                    transferSection.style.display = 'block';
                } else {
                    cashSection.style.display = 'none';
                    transferSection.style.display = 'none';
                }
            } else {
                cashSection.style.display = 'none';
                transferSection.style.display = 'none';
            }
        }




        // ===== Modal Updates =====
        function updateModalTotals() {
            const subtotalLAK = cart.reduce((sum, i) => sum + (i.basePriceLAK * i.qty), 0);
            const taxableLAK = Math.max(0, subtotalLAK - baseDiscountLAK);
            const vatLAK = vatEnabled ? taxableLAK * 0.1 : 0;
            let totalLAK = taxableLAK + vatLAK;

            // Handle Deposit deduction
            const status = document.querySelector('input[name="paymentStatus"]:checked')?.value;
            let depositLAK = 0;
            if (status === 'partial') {
                const depositVal = parseFloat(document.getElementById('depositAmount').value) || 0;
                depositLAK = convertToLAK(depositVal);
                totalLAK = Math.max(0, totalLAK - depositLAK);

                // Display deposit
                document.getElementById('modalDeposit').textContent = formatNumber(depositVal) + ' ' + currentCurrency.symbol;
            }

            // Render Items in Modal
            const itemsContainer = document.getElementById('modalOrderItems');
            itemsContainer.innerHTML = cart.map((i, idx) => `
            <tr>
                <td>${idx + 1}</td>
                <td>${i.name}</td>
                <td style="text-align:center;">${i.qty}</td>
                <td style="text-align:right;">${formatNumber(convertPrice(i.basePriceLAK * i.qty))} ${currentCurrency.symbol}</td>
            </tr>
        `).join('');

            // Update Summary Numbers
            document.getElementById('modalSubtotal').textContent = formatNumber(convertPrice(subtotalLAK)) + ' ' + currentCurrency.symbol;
            document.getElementById('modalDiscount').textContent = formatNumber(convertPrice(baseDiscountLAK)) + ' ' + currentCurrency.symbol;
            document.getElementById('modalVat').textContent = formatNumber(convertPrice(vatLAK)) + ' ' + currentCurrency.symbol;
            document.getElementById('modalVatRow').style.display = vatEnabled ? 'flex' : 'none';

            // Grand Total (Remaining to pay)
            const totalDisp = convertPrice(totalLAK);
            document.getElementById('modalTotal').textContent = formatTotal(totalDisp) + ' ' + currentCurrency.symbol;

            generateQuickAmounts();
            calculateChange();
        }

        function generateQuickAmounts() {
            // Get total remaining to pay in display currency
            // We reuse logic from updateModalTotals roughly or just grab text content (risky).
            // Best to re-calculate clean.
            const subtotalLAK = cart.reduce((sum, i) => sum + (i.basePriceLAK * i.qty), 0);
            const taxableLAK = Math.max(0, subtotalLAK - baseDiscountLAK);
            const vatLAK = vatEnabled ? taxableLAK * 0.1 : 0;
            let totalLAK = taxableLAK + vatLAK;

            const status = document.querySelector('input[name="paymentStatus"]:checked')?.value;
            if (status === 'partial') {
                const depositVal = parseFloat(document.getElementById('depositAmount').value) || 0;
                totalLAK = Math.max(0, totalLAK - convertToLAK(depositVal));
            }

            const total = convertPrice(totalLAK);
            let amounts = [];

            if (total <= 0) {
                document.getElementById('quickAmounts').innerHTML = '';
                return;
            }

            // Adaptive Quick Amounts
            if (currentCurrency.symbol === '₭') {
                const bases = [1000, 2000, 5000, 10000, 20000, 50000, 100000, 500000, 1000000];
                amounts = bases.filter(b => b >= total).slice(0, 4);
                if (amounts.length < 4) amounts.push(Math.ceil(total / 1000) * 1000);
            } else if (currentCurrency.symbol === '฿') {
                const bases = [20, 50, 100, 500, 1000];
                amounts = bases.filter(b => b >= total).slice(0, 4);
                if (amounts.length === 0) amounts.push(Math.ceil(total / 10) * 10);
            } else {
                const bases = [1, 5, 10, 20, 50, 100];
                amounts = bases.filter(b => b >= total).slice(0, 4);
                if (amounts.length === 0) amounts.push(Math.ceil(total));
            }

            // Unique and sort
            amounts = [...new Set([total, ...amounts])].sort((a, b) => a - b).slice(0, 5);

            const container = document.getElementById('quickAmounts');
            container.innerHTML = amounts.map(a =>
                `<button class="quick-amount-btn" onclick="setCashReceived(${a})">${formatNumber(a)}</button>`
            ).join('');
        }

        function setCashReceived(amount) {
            document.getElementById('cashReceived').value = amount;
            calculateChange();
        }

        function calculateChange() {
            const received = parseFloat(document.getElementById('cashReceived').value) || 0;

            // Recalculate Total for diff
            // NOTE: Optimization - could store this in a global var during updateModalTotals
            const subtotalLAK = cart.reduce((sum, i) => sum + (i.basePriceLAK * i.qty), 0);
            const taxableLAK = Math.max(0, subtotalLAK - baseDiscountLAK);
            const vatLAK = vatEnabled ? taxableLAK * 0.1 : 0;
            let totalLAK = taxableLAK + vatLAK;

            const status = document.querySelector('input[name="paymentStatus"]:checked')?.value;
            if (status === 'partial') {
                const depositVal = parseFloat(document.getElementById('depositAmount').value) || 0;
                totalLAK = Math.max(0, totalLAK - convertToLAK(depositVal));
            }

            // Show total with rounding applied (the amount user actually pays)
            // using formatTotal logic (round to int or 2 decimals)
            let totalDisplay = convertPrice(totalLAK);

            // Rounding simulation for check
            if (currentCurrency.id === 'CUR_2' || currentCurrency.id === 'LAK') { // THB or LAK
                totalDisplay = Math.round(totalDisplay);
            }

            const change = Math.max(0, received - totalDisplay);
            document.getElementById('changeAmount').textContent = formatNumber(change) + ' ' + currentCurrency.symbol;
        }

        // ===== Utilities =====
        function formatNumber(num) {
            // Enforce decimals for USD, Integer for others
            if (currentCurrency.id === 'CUR_3' || currentCurrency.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));
        }

        function formatTotal(num) {
            if (currentCurrency.id === 'CUR_3' || currentCurrency.symbol === '$') {
                return new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(Math.round(num * 100) / 100);
            }
            return new Intl.NumberFormat('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(Math.round(num));
        }

        function fillCustomerInfo() {
            // Now uses searchable select - data is set by selectSearchableOption callback
        }

        // ===== Searchable Select Functions =====
        function toggleSearchableSelect(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 = '';
                filterSearchableSelect(wrapperId, '');
                setTimeout(() => searchInput.focus(), 50);
            }
        }

        function filterSearchableSelect(wrapperId, query) {
            const wrapper = document.getElementById(wrapperId);
            const options = wrapper.querySelectorAll('.searchable-select-option');
            const q = query.toLowerCase().trim();

            options.forEach(opt => {
                if (opt.dataset.value === '') {
                    // Always show the placeholder/default option
                    opt.classList.remove('hidden');
                    return;
                }
                const text = opt.textContent.toLowerCase();
                if (q === '' || text.includes(q)) {
                    opt.classList.remove('hidden');
                } else {
                    opt.classList.add('hidden');
                }
            });
        }

        function selectSearchableOption(wrapperId, value, displayText, extraData) {
            const wrapper = document.getElementById(wrapperId);
            const hiddenInput = wrapper.querySelector('input[type="hidden"]');
            const displaySpan = wrapper.querySelector('.searchable-select-text');

            // Set the hidden input value
            hiddenInput.value = value;

            // Update display text
            if (value === '') {
                displaySpan.textContent = displaySpan.dataset.placeholder;
                displaySpan.classList.add('placeholder');
            } else {
                displaySpan.textContent = displayText;
                displaySpan.classList.remove('placeholder');
            }

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

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

            // Handle customer-specific logic
            if (wrapperId === 'customerSelectWrapper') {
                if (extraData && extraData.name) {
                    document.getElementById('customerName').value = extraData.name;
                    document.getElementById('customerPhone').value = extraData.phone || '';
                } else {
                    document.getElementById('customerName').value = '';
                    document.getElementById('customerPhone').value = '';
                }
            }
        }

        function resetSearchableSelect(wrapperId) {
            const wrapper = document.getElementById(wrapperId);
            if (!wrapper) return;
            const hiddenInput = wrapper.querySelector('input[type="hidden"]');
            const displaySpan = wrapper.querySelector('.searchable-select-text');

            hiddenInput.value = '';
            displaySpan.textContent = displaySpan.dataset.placeholder;
            displaySpan.classList.add('placeholder');

            wrapper.querySelectorAll('.searchable-select-option').forEach(opt => {
                opt.classList.remove('selected', 'hidden');
            });
            wrapper.classList.remove('open');
        }

        function addSearchableOption(wrapperId, value, text, extraData, autoSelect) {
            const wrapper = document.getElementById(wrapperId);
            const optionsContainer = wrapper.querySelector('.searchable-select-options');

            const div = document.createElement('div');
            div.className = 'searchable-select-option';
            div.dataset.value = value;
            if (extraData) {
                Object.keys(extraData).forEach(k => div.dataset[k] = extraData[k]);
            }
            div.textContent = text;
            div.onclick = function () {
                selectSearchableOption(wrapperId, value, text, extraData || {});
            };
            optionsContainer.appendChild(div);

            if (autoSelect) {
                selectSearchableOption(wrapperId, value, text, extraData || {});
            }
        }

        // Close searchable selects 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');
                });
            }
        });

        // ===== Submit Order =====
        function submitOrder() {
            // Validation
            if (saleMode === 'online') {
                if (!document.getElementById('customerName').value.trim()) {
                    Swal.fire({ icon: 'warning', title: 'ກະລຸນາປ້ອນຊື່ລູກຄ້າ' });
                    return;
                }
            }

            const paymentStatus = document.querySelector('input[name="paymentStatus"]:checked')?.value;
            if (!paymentStatus) {
                Swal.fire({ icon: 'warning', title: 'ກະລຸນາເລືອກສະຖານະການຈ່າຍ' });
                return;
            }

            if (paymentStatus !== 'pending') {
                const paymentMethod = document.querySelector('input[name="paymentMethod"]:checked')?.value;
                if (!paymentMethod) {
                    Swal.fire({ icon: 'warning', title: 'ກະລຸນາເລືອກວິທີຊໍາລະ' });
                    return;
                }
            }

            // Prepare Data Calculation
            const subtotalLAK = cart.reduce((sum, i) => sum + (i.basePriceLAK * i.qty), 0);
            const taxableLAK = Math.max(0, subtotalLAK - baseDiscountLAK);
            const vatLAK = vatEnabled ? taxableLAK * 0.1 : 0;
            const totalLAK = taxableLAK + vatLAK;

            // Display Values
            let subtotalDisplay = convertPrice(subtotalLAK);
            let discountDisplay = convertPrice(baseDiscountLAK);
            let vatDisplay = convertPrice(vatLAK);
            let totalDisplay = convertPrice(totalLAK);

            // Rounding for THB/LAK to match UI display
            if (currentCurrency.id === 'CUR_2' || currentCurrency.id === 'LAK') { // THB or LAK
                subtotalDisplay = Math.round(subtotalDisplay);
                discountDisplay = Math.round(discountDisplay);
                vatDisplay = Math.round(vatDisplay);
                totalDisplay = Math.round(totalDisplay);
            } else if (currentCurrency.id === 'CUR_3' || currentCurrency.symbol === '$') { // USD
                // Ensure 2 decimal places for consistency
                subtotalDisplay = parseFloat(subtotalDisplay.toFixed(2));
                discountDisplay = parseFloat(discountDisplay.toFixed(2));
                vatDisplay = parseFloat(vatDisplay.toFixed(2));
                totalDisplay = parseFloat(totalDisplay.toFixed(2));
            }

            // Deposit
            const depositVal = parseFloat(document.getElementById('depositAmount').value) || 0;

            // Calculate Tip (Foreign Currency Rounding)
            let tipData = null;
            if (currentCurrency.rate !== 1) {
                const rawTotal = convertPriceRaw(totalLAK);
                const roundedTotal = Math.round(rawTotal); // Assuming integer rounding
                const tipForeign = roundedTotal - rawTotal;
                if (Math.abs(tipForeign) > 0.0001) { // Tolerance
                    tipData = {
                        currencys_id: currentCurrency.id,
                        currency_rate: currentCurrency.rate,
                        original_total: rawTotal,
                        rounded_total: roundedTotal,
                        tip_amount_foreign: tipForeign,
                        tip_amount_lak: tipForeign * currentCurrency.rate,
                        calculation_note: `Rounding Tip: ${tipForeign.toFixed(2)}`
                    };
                }
            }

            const payload = {
                shop_id: <?= json_encode($shop_id) ?>,
                sale_type: saleMode,
                customer_name: document.getElementById('customerName').value.trim(),
                customer_phone: document.getElementById('customerPhone').value.trim(),
                shipping_company_id: document.getElementById('shippingCompany').value || null,
                shipping_branch_id: document.getElementById('shippingBranch').value || null,
                cod_type: document.querySelector('input[name="codType"]:checked')?.value || null,
                payment_status: paymentStatus,
                payment_method: document.querySelector('input[name="paymentMethod"]:checked')?.value || null,
                cart: cart.map(i => ({
                    product_id: i.id,
                    product_name: i.name,
                    quantity: i.qty,

                    // Prices
                    unit_price_lak: i.basePriceLAK,
                    unit_price_display: convertPrice(i.basePriceLAK),
                    subtotal_lak: i.basePriceLAK * i.qty,
                    subtotal_display: convertPrice(i.basePriceLAK * i.qty)
                })),

                // Totals
                subtotal_lak: subtotalLAK,
                discount_lak: baseDiscountLAK,
                vat_amount_lak: vatLAK,
                total_amount_lak: totalLAK,

                subtotal_display: subtotalDisplay,
                discount_display: discountDisplay,
                vat_display: vatDisplay,
                total_display: totalDisplay,

                // Meta
                currencys_id: currentCurrency.id,
                currency_rate: currentCurrency.rate,
                rate_id: currentCurrency.rateId,
                vat_enabled: vatEnabled ? 1 : 0,

                deposit_amount: paymentStatus === 'partial' ? depositVal : 0,
                amount_received: parseFloat(document.getElementById('cashReceived').value) || 0,
                change_amount: parseFloat(document.getElementById('changeAmount').textContent.replace(/[^0-9.]/g, '')) || 0,

                tip_data: tipData
            };

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

            const slipImageInput = document.getElementById('slipImage');
            if (slipImageInput && slipImageInput.files.length > 0) {
                Array.from(slipImageInput.files).forEach(file => {
                    formData.append('slip_images[]', file);
                });
            }

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

            fetch('../api/pos_submit_order.php', {
                method: 'POST',
                body: formData
            })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'ບັນທຶກສຳເລັດ!',
                            text: 'ຕ້ອງການພິມໃບບິນບໍ່?',
                            showCancelButton: true,
                            confirmButtonText: 'ພິມໃບບິນ',
                            cancelButtonText: 'ບໍ່ພິມ'
                        }).then(result => {
                            if (result.isConfirmed && data.order_id) {
                                window.open('print_invoice.php?id=' + data.order_id, '_blank');
                            }
                        });

                        // Reset
                        cart = [];
                        baseDiscountLAK = 0;
                        document.getElementById('discountAmountCart').value = '0';
                        discountType = 'fixed';
                        const dt = document.getElementById('discountTypeToggle');
                        dt.textContent = currentCurrency.symbol;
                        dt.style.background = '';
                        dt.style.color = '';
                        document.getElementById('slipImage').value = '';
                        if (document.getElementById('slipPreviewContainer')) {
                            document.getElementById('slipPreviewContainer').style.display = 'none';
                            document.getElementById('slipPreviewGrid').innerHTML = '';
                        }
                        renderCart();
                        updateTotals();
                        closeCheckoutModal();

                        // Reload products to update stock
                        loadProducts(1);
                    } else {
                        throw new Error(data.message || 'ເກີດຂໍ້ຜິດພາດ');
                    }
                })
                .catch(err => {
                    Swal.fire({ icon: 'error', title: 'ຜິດພາດ', text: 'Save failed: ' + err.message });
                });
        }

        // ===== Quick Adds (API) =====
        // Note: Assuming api/pos_quick_add.php exists or sharing logic
        // Using ../api/pos_quick_add.php to match structure
        function saveQuickCustomer() {
            const name = document.getElementById('newCustomerName').value.trim();
            const phone = document.getElementById('newCustomerPhone').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: name, phone: phone, shop_id: <?= json_encode($shop_id) ?> })
            }).then(r => r.json()).then(data => {
                if (data.success) {
                    addSearchableOption('customerSelectWrapper', data.id, name + ' - ' + phone, { name: name, phone: phone }, true);
                    document.getElementById('newCustomerName').value = '';
                    document.getElementById('newCustomerPhone').value = '';
                    hideQuickAddCustomer();
                    Swal.fire({ icon: 'success', title: 'ສຳເລັດ', timer: 1000, showConfirmButton: false });
                } else {
                    Swal.fire({ icon: 'error', title: 'Error', text: data.message });
                }
            });
        }

        function showQuickAddCustomer() { document.getElementById('quickAddCustomerForm').style.display = 'block'; }
        function hideQuickAddCustomer() { document.getElementById('quickAddCustomerForm').style.display = 'none'; }

        function showQuickAddCompany() { document.getElementById('quickAddCompanyForm').style.display = 'block'; }
        function hideQuickAddCompany() { document.getElementById('quickAddCompanyForm').style.display = 'none'; }

        function showQuickAddBranch() { document.getElementById('quickAddBranchForm').style.display = 'block'; }
        function hideQuickAddBranch() { document.getElementById('quickAddBranchForm').style.display = 'none'; }

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

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

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

            fetch('../api/pos_quick_add.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type: 'branch', name: name, shop_id: <?= json_encode($shop_id) ?> })
            }).then(r => r.json()).then(data => {
                if (data.success) {
                    addSearchableOption('shippingBranchWrapper', data.id, name, {}, true);

                    // Add to local array
                    shippingBranches.push({ id: data.id, branch_name: name });

                    document.getElementById('newBranchName').value = '';
                    hideQuickAddBranch();
                    Swal.fire({ icon: 'success', title: 'ສຳເລັດ', timer: 1000, showConfirmButton: false });
                } else {
                    Swal.fire({ icon: 'error', title: 'Error', text: data.message });
                }
            });
        }

        // Initial Render
        loadProducts();
        renderCart();

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

                // Keep existing files
                if (slipInput.files) {
                    Array.from(slipInput.files).forEach(f => dataTransfer.items.add(f));
                }

                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) {
                            dataTransfer.items.add(file);
                            hasImage = true;
                        }
                    }
                }

                if (hasImage) {
                    slipInput.files = dataTransfer.files;
                    previewSlipImages({ target: slipInput });
                    e.preventDefault();
                }
            });

            // Allow dragging over and dropping files
            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) {
                    const dataTransfer = new DataTransfer();
                    const slipInput = document.getElementById('slipImage');

                    // Keep existing files
                    if (slipInput.files) {
                        Array.from(slipInput.files).forEach(f => dataTransfer.items.add(f));
                    }

                    Array.from(e.dataTransfer.files).forEach(f => {
                        if (f.type.startsWith('image/')) {
                            dataTransfer.items.add(f);
                        }
                    });

                    slipInput.files = dataTransfer.files;
                    previewSlipImages({ target: slipInput });
                }
            });
        }

        function previewSlipImages(event) {
            const container = document.getElementById('slipPreviewContainer');
            const grid = document.getElementById('slipPreviewGrid');
            const emptyState = document.getElementById('slip-empty-state');
            const files = event.target.files;

            grid.innerHTML = '';

            if (files && files.length > 0) {
                container.style.display = 'block';
                if (emptyState) emptyState.style.display = 'none';
                document.getElementById('slip-count').textContent = `(${files.length} ຮູບ)`;

                Array.from(files).forEach((file, index) => {
                    if (file.type.startsWith('image/')) {
                        const reader = new FileReader();
                        reader.onload = function (e) {
                            grid.innerHTML += `
                                <div style="position:relative;display:inline-block">
                                    <img src="${e.target.result}" style="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)" onclick="removeSlipImage(${index})"><i class="fas fa-times" style="font-size:12px"></i></button>
                                </div>
                            `;
                        };
                        reader.readAsDataURL(file);
                    }
                });
            } else {
                container.style.display = 'none';
                if (emptyState) emptyState.style.display = 'block';
                document.getElementById('slip-count').textContent = '';
            }
        }

        function removeSlipImage(indexToRemove) {
            const slipInput = document.getElementById('slipImage');
            const dataTransfer = new DataTransfer();

            Array.from(slipInput.files).forEach((file, index) => {
                if (index !== indexToRemove) {
                    dataTransfer.items.add(file);
                }
            });

            slipInput.files = dataTransfer.files;
            previewSlipImages({ target: slipInput });
        }

    </script>

    <!-- GSAP Animation Library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/MotionPathPlugin.min.js"></script>

    <script>
        // Register GSAP Plugin
        gsap.registerPlugin(MotionPathPlugin);

        /**
         * Professional Fly to Cart Animation
         * Uses Bezier Curve path for natural movement
         */
        function animateFlyToCart(sourceEl, targetEl) {
            if (!sourceEl || !targetEl) return;

            // 1. Get positions
            const sourceRect = sourceEl.getBoundingClientRect();
            const targetRect = targetEl.getBoundingClientRect();

            // 2. Create clone of the image
            const clone = sourceEl.cloneNode(true);

            // Get computed styles for color/font if it's an icon
            const computed = window.getComputedStyle(sourceEl);

            // Style the clone to match source position initially
            Object.assign(clone.style, {
                position: 'fixed',
                left: sourceRect.left + 'px',
                top: sourceRect.top + 'px',
                width: sourceRect.width + 'px',
                height: sourceRect.height + 'px',
                color: computed.color, // Copy color (crucial for icons)
                fontSize: computed.fontSize, // Copy font size
                zIndex: 9999,
                pointerEvents: 'none',
                borderRadius: '12px',
                opacity: 0.9,
                margin: 0, // Reset margin
                display: 'flex', // Ensure centering if needed
                alignItems: 'center',
                justifyContent: 'center',
                willChange: 'transform' // GPU acceleration
            });

            document.body.appendChild(clone);

            // 3. Calculate path points
            // Start center
            const startX = sourceRect.left + sourceRect.width / 2;
            const startY = sourceRect.top + sourceRect.height / 2;

            // End center
            const endX = targetRect.left + targetRect.width / 2;
            const endY = targetRect.top + targetRect.height / 2;

            // 4. Animate using GSAP MotionPath
            gsap.to(clone, {
                duration: 0.8,
                ease: "power3.inOut",
                motionPath: {
                    path: [
                        // Control point 1: Move slightly out and up
                        { x: (endX - startX) * 0.2, y: -100 },
                        // Control point 2: Arc towards target
                        { x: (endX - startX) * 0.8, y: (endY - startY) * 0.5 },
                        // Final point: center of target relative to start
                        { x: endX - startX, y: endY - startY }
                    ],
                    curviness: 1.5,
                    autoRotate: false
                },
                width: 50,  // Shrink width
                height: 50, // Shrink height
                opacity: 0, // Fade out at the very end
                borderRadius: '50%', // Morph to circle
                onComplete: () => {
                    clone.remove();

                    // Shake effect on cart icon/panel
                    gsap.fromTo(targetEl,
                        { rotation: -10, scale: 1.1 },
                        { rotation: 0, scale: 1, duration: 0.4, ease: "elastic.out(1, 0.3)" }
                    );
                }
            });
        }
        // ===== Barcode Scanner Integration =====
        function decodeAsciiBarcode(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 scanAndAddToCart(barcode) {
            barcode = barcode.trim();
            if (!barcode || barcode.length < 4) return;

            var searchBox = document.getElementById('searchProduct');
            if (searchBox) searchBox.value = '';

            fetch('pos.php?ajax=products&page=1&search=' + encodeURIComponent(barcode) + '&group=')
                .then(function (r) { return r.json(); })
                .then(function (result) {
                    if (result.success && result.data && result.data.length > 0) {
                        var product = null;
                        for (var i = 0; i < result.data.length; i++) {
                            if (result.data[i].product_code === barcode ||
                                (result.data[i].barcode && result.data[i].barcode === barcode)) {
                                product = result.data[i];
                                break;
                            }
                        }
                        if (!product) product = result.data[0];

                        addToCart(product);
                        loadProducts(1);

                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                toast: true,
                                position: 'top-end',
                                icon: 'success',
                                title: '\u0ec0\u0e9e\u0eb5\u0ec8\u0ea1: ' + product.products_name,
                                showConfirmButton: false,
                                timer: 1500,
                                timerProgressBar: true
                            });
                        }
                    } else {
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                toast: true,
                                position: 'top-end',
                                icon: 'warning',
                                title: '\u0e9a\u0ecd\u0ec8\u0e9e\u0ebb\u0e9a\u0eaa\u0eb4\u0e99\u0e84\u0ec9\u0eb2: ' + barcode,
                                showConfirmButton: false,
                                timer: 2000
                            });
                        }
                    }
                })
                .catch(function (err) {
                    console.error('Barcode lookup error:', err);
                });
        }

    </script>

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