<?php
// Handle AJAX requests BEFORE any HTML output
if (isset($_POST['action']) || isset($_GET['ajax'])) {
    if (session_status() === PHP_SESSION_NONE)
        session_start();
    require_once dirname(__DIR__, 2) . '/include/con_data.php';

    // Check auth
    if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['manager', 'staff'])) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        exit;
    }

    // Multi-store: get shop_id
    $shop_id = $_SESSION['shop_id'] ?? null;
    if (!$shop_id) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'No shop assigned']);
        exit;
    }

    // AJAX: Fetch dropdown data (cached client-side)
    if (isset($_GET['ajax']) && $_GET['ajax'] === 'dropdowns') {
        header('Content-Type: application/json');
        header('Cache-Control: public, max-age=300'); // Cache 5 min

        $brands = $pdo->prepare("SELECT BR_id AS id, brand_name AS name FROM brand WHERE shop_id = ? ORDER BY brand_name ASC");
        $brands->execute([$shop_id]);
        $brands = $brands->fetchAll();

        $groups = $pdo->prepare("SELECT GP_id AS id, group_name AS name FROM product_group WHERE shop_id = ? ORDER BY group_name ASC");
        $groups->execute([$shop_id]);
        $groups = $groups->fetchAll();

        $suppliers = $pdo->prepare("SELECT SU_id AS id, supplier_name AS name FROM supplier WHERE shop_id = ? ORDER BY supplier_name ASC");
        $suppliers->execute([$shop_id]);
        $suppliers = $suppliers->fetchAll();

        echo json_encode(['success' => true, 'brands' => $brands, 'groups' => $groups, 'suppliers' => $suppliers]);
        exit;
    }

    // AJAX: Fetch paginated products (OPTIMIZED)
    if (isset($_GET['ajax']) && $_GET['ajax'] === 'list') {
        header('Content-Type: application/json');

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

        // Build WHERE clause
        $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%";
        }

        // Use SQL_CALC_FOUND_ROWS to get total in one pass
        $sql = "SELECT SQL_CALC_FOUND_ROWS id, product_code, barcode, products_name, price_1, price_2, product_group, brand, supplier, image
                FROM products WHERE $where ORDER BY id ASC LIMIT $limit OFFSET $offset";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

        // Names resolved client-side using cached dropdown data — no lookup queries here

        echo json_encode([
            'success' => true,
            'data' => $rows,
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'totalPages' => ceil($total / $limit)
        ]);
        exit;
    }

    // ===== NEW EXPORT SYSTEM: Export Products =====
    if (isset($_GET['ajax']) && $_GET['ajax'] === 'export_products') {
        $columns = isset($_GET['columns']) ? array_filter(explode(',', $_GET['columns'])) : [];
        $format = $_GET['format'] ?? 'csv';

        $allowedColumns = [
            'product_code' => 'p.product_code',
            'barcode' => 'p.barcode',
            'products_name' => 'p.products_name',
            'price_1' => 'p.price_1',
            'price_2' => 'p.price_2',
            'product_group' => 'pg.group_name AS product_group_name',
            'brand' => 'b.brand_name AS brand_name',
            'supplier' => 's.supplier_name AS supplier_name',
        ];

        $columnHeaders = [
            'product_code' => 'product_code',
            'barcode' => 'barcode',
            'products_name' => 'products_name',
            'price_1' => 'price_1',
            'price_2' => 'price_2',
            'product_group' => 'product_group_name',
            'brand' => 'brand_name',
            'supplier' => 'supplier_name',
        ];

        $selectedCols = array_filter($columns, fn($c) => isset($allowedColumns[$c]));
        if (empty($selectedCols))
            $selectedCols = array_keys($allowedColumns);

        $selectParts = [];
        $headers = [];
        foreach ($selectedCols as $col) {
            $selectParts[] = $allowedColumns[$col];
            $headers[] = $columnHeaders[$col];
        }

        $sql = "SELECT " . implode(', ', $selectParts) . "
                FROM products p
                LEFT JOIN product_group pg ON p.product_group = pg.GP_id
                LEFT JOIN brand b ON p.brand = b.BR_id
                LEFT JOIN supplier s ON p.supplier = s.SU_id
                WHERE p.deleted_at IS NULL AND p.shop_id = :shop_id
                GROUP BY p.id
                ORDER BY p.id ASC";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':shop_id' => $shop_id]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($format === 'excel') {
            header('Content-Type: application/vnd.ms-excel; charset=utf-8');
            header('Content-Disposition: attachment; filename="products_export_' . date('Y-m-d_His') . '.xls"');
            header('Cache-Control: max-age=0');
            echo '<html xmlns:x="urn:schemas-microsoft-com:office:excel"><head><meta charset="utf-8">';
            echo '<style>th{background:#c1992a;color:#fff;font-weight:bold;padding:8px}td{padding:6px;border:1px solid #ddd}</style></head><body>';
            echo '<table border="1"><thead><tr>';
            foreach ($headers as $h)
                echo '<th>' . htmlspecialchars($h) . '</th>';
            echo '</tr></thead><tbody>';
            foreach ($rows as $row) {
                echo '<tr>';
                foreach ($row as $val)
                    echo '<td>' . htmlspecialchars($val ?? '') . '</td>';
                echo '</tr>';
            }
            echo '</tbody></table></body></html>';
        } else {
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename="products_export_' . date('Y-m-d_His') . '.csv"');
            header('Cache-Control: max-age=0');
            echo "\xEF\xBB\xBF";
            $output = fopen('php://output', 'w');
            fputcsv($output, $headers);
            foreach ($rows as $row)
                fputcsv($output, array_values($row));
            fclose($output);
        }
        exit;
    }

    // AJAX: Add / Edit / Delete
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        header('Content-Type: application/json');
        $action = $_POST['action'];
        $username = $_SESSION['username'] ?? 'System';

        try {
            $imageName = null;
            if (!empty($_FILES['image']['name'])) {
                $target_dir = "../../img/products/";
                if (!file_exists($target_dir))
                    mkdir($target_dir, 0777, true);

                $ext = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));
                $allow = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
                if (in_array($ext, $allow)) {
                    $imageName = uniqid() . '_' . time() . '.' . $ext;
                    move_uploaded_file($_FILES["image"]["tmp_name"], $target_dir . $imageName);
                }
            }

            if ($action === 'add') {
                $stmt = $pdo->prepare("INSERT INTO products 
                    (product_code, barcode, products_name, price_1, price_2, product_group, brand, supplier, create_officer, image, shop_id) 
                    VALUES (:product_code, :barcode, :products_name, :price_1, :price_2, :product_group, :brand, :supplier, :create_officer, :image, :shop_id)");
                $stmt->execute([
                    ':product_code' => $_POST['product_code'],
                    ':barcode' => $_POST['barcode'],
                    ':products_name' => $_POST['products_name'],
                    ':price_1' => $_POST['price_1'],
                    ':price_2' => $_POST['price_2'] ?: null,
                    ':product_group' => $_POST['product_group'],
                    ':brand' => $_POST['brand'],
                    ':supplier' => $_POST['supplier'],
                    ':create_officer' => $username,
                    ':image' => $imageName,
                    ':shop_id' => $shop_id
                ]);
                echo json_encode(['success' => true, 'message' => 'ເພີ່ມສິນຄ້າສຳເລັດ']);
                exit;
            }

            if ($action === 'edit') {
                // Use COALESCE to keep existing image if no new one uploaded
                $imgSql = $imageName ? ", image = :image" : "";

                $sql = "UPDATE products SET 
                    product_code = :product_code, barcode = :barcode, products_name = :products_name,
                    price_1 = :price_1, price_2 = :price_2, product_group = :product_group,
                    brand = :brand, supplier = :supplier, updated_by = :updated_by
                    $imgSql
                    WHERE id = :id AND shop_id = :shop_id";

                $stmt = $pdo->prepare($sql);
                $params = [
                    ':product_code' => $_POST['product_code'],
                    ':barcode' => $_POST['barcode'],
                    ':products_name' => $_POST['products_name'],
                    ':price_1' => $_POST['price_1'],
                    ':price_2' => $_POST['price_2'] ?: null,
                    ':product_group' => $_POST['product_group'],
                    ':brand' => $_POST['brand'],
                    ':supplier' => $_POST['supplier'],
                    ':updated_by' => $username,
                    ':id' => $_POST['id'],
                    ':shop_id' => $shop_id
                ];
                if ($imageName)
                    $params[':image'] = $imageName;

                $stmt->execute($params);
                $stmt->execute($params);
                echo json_encode(['success' => true, 'message' => 'ແກ້ໄຂສິນຄ້າສຳເລັດ']);
                exit;
            }

            // === Quick Add Handlers ===
            if ($action === 'add_group') {
                $name = trim($_POST['name'] ?? '');
                if (!$name) {
                    echo json_encode(['success' => false, 'message' => 'Name required']);
                    exit;
                }

                $stmt = $pdo->prepare("INSERT INTO product_group (group_name, shop_id) VALUES (:name, :shop_id)");
                $stmt->execute([':name' => $name, ':shop_id' => $shop_id]);
                echo json_encode(['success' => true, 'id' => $pdo->lastInsertId(), 'name' => $name]);
                exit;
            }

            if ($action === 'add_brand') {
                $name = trim($_POST['name'] ?? '');
                if (!$name) {
                    echo json_encode(['success' => false, 'message' => 'Name required']);
                    exit;
                }

                $stmt = $pdo->prepare("INSERT INTO brand (brand_name, shop_id) VALUES (:name, :shop_id)");
                $stmt->execute([':name' => $name, ':shop_id' => $shop_id]);
                echo json_encode(['success' => true, 'id' => $pdo->lastInsertId(), 'name' => $name]);
                exit;
            }

            if ($action === 'add_supplier') {
                $name = trim($_POST['name'] ?? '');
                if (!$name) {
                    echo json_encode(['success' => false, 'message' => 'Name required']);
                    exit;
                }

                $stmt = $pdo->prepare("INSERT INTO supplier (supplier_name, shop_id) VALUES (:name, :shop_id)");
                $stmt->execute([':name' => $name, ':shop_id' => $shop_id]);
                echo json_encode(['success' => true, 'id' => $pdo->lastInsertId(), 'name' => $name]);
                exit;
            }

            if ($action === 'delete') {
                $stmt = $pdo->prepare("UPDATE products SET deleted_at = NOW(), deleted_by = :deleted_by WHERE id = :id AND shop_id = :shop_id");
                $stmt->execute([':deleted_by' => $username, ':id' => $_POST['id'], ':shop_id' => $shop_id]);
                echo json_encode(['success' => true, 'message' => 'ລຶບສິນຄ້າສຳເລັດ']);
                exit;
            }

            // ===== NEW IMPORT SYSTEM: Preview =====
            if ($action === 'import_products_preview') {
                $jsonData = $_POST['import_data'] ?? '';
                $searchField = trim($_POST['search_field'] ?? 'product_code');

                if (!in_array($searchField, ['product_code', 'barcode'])) {
                    echo json_encode(['success' => false, 'message' => 'Invalid search field']);
                    exit;
                }

                $parsedData = json_decode($jsonData, true);
                if (!$parsedData || !is_array($parsedData)) {
                    echo json_encode(['success' => false, 'message' => 'ບໍ່ສາມາດອ່ານຂໍ້ມູນໄດ້']);
                    exit;
                }

                $results = ['found' => [], 'new' => [], 'errors' => []];
                $missingGroups = [];
                $missingBrands = [];
                $missingSuppliers = [];

                // Load existing lookups
                $gStmt = $pdo->prepare("SELECT GP_id, group_name FROM product_group WHERE shop_id = ?");
                $gStmt->execute([$shop_id]);
                $groupMap = [];
                foreach ($gStmt->fetchAll() as $g)
                    $groupMap[mb_strtolower(trim($g['group_name']))] = $g['GP_id'];

                $bStmt = $pdo->prepare("SELECT BR_id, brand_name FROM brand WHERE shop_id = ?");
                $bStmt->execute([$shop_id]);
                $brandMap = [];
                foreach ($bStmt->fetchAll() as $b)
                    $brandMap[mb_strtolower(trim($b['brand_name']))] = $b['BR_id'];

                $sStmt = $pdo->prepare("SELECT SU_id, supplier_name FROM supplier WHERE shop_id = ?");
                $sStmt->execute([$shop_id]);
                $suppMap = [];
                foreach ($sStmt->fetchAll() as $s)
                    $suppMap[mb_strtolower(trim($s['supplier_name']))] = $s['SU_id'];

                foreach ($parsedData as $idx => $row) {
                    $lineNum = $idx + 2;
                    $rowErrors = [];
                    $row = array_map(fn($v) => trim((string) $v), $row);

                    if (empty($row['products_name'] ?? '')) {
                        $rowErrors[] = "ຊື່ສິນຄ້າ ຫວ່າງ";
                    }
                    if (isset($row['price_1']) && $row['price_1'] !== '' && !is_numeric($row['price_1'])) {
                        $rowErrors[] = "ລາຄາ 1 ບໍ່ຖືກ format";
                    }
                    if (isset($row['price_2']) && $row['price_2'] !== '' && !is_numeric($row['price_2'])) {
                        $rowErrors[] = "ລາຄາ 2 ບໍ່ຖືກ format";
                    }

                    $groupId = null;
                    $brandId = null;
                    $supplierId = null;

                    if (!empty($row['product_group_name'] ?? '')) {
                        $key = mb_strtolower(trim($row['product_group_name']));
                        if (isset($groupMap[$key]))
                            $groupId = $groupMap[$key];
                        else
                            $missingGroups[$row['product_group_name']] = true;
                    }
                    if (!empty($row['brand_name'] ?? '')) {
                        $key = mb_strtolower(trim($row['brand_name']));
                        if (isset($brandMap[$key]))
                            $brandId = $brandMap[$key];
                        else
                            $missingBrands[$row['brand_name']] = true;
                    }
                    if (!empty($row['supplier_name'] ?? '')) {
                        $key = mb_strtolower(trim($row['supplier_name']));
                        if (isset($suppMap[$key]))
                            $supplierId = $suppMap[$key];
                        else
                            $missingSuppliers[$row['supplier_name']] = true;
                    }

                    if (!empty($rowErrors)) {
                        $results['errors'][] = ['line' => $lineNum, 'data' => $row, 'errors' => $rowErrors];
                        continue;
                    }

                    $searchVal = $row[$searchField] ?? '';
                    $exists = false;
                    if (!empty($searchVal)) {
                        $chk = $pdo->prepare("SELECT id FROM products WHERE {$searchField} = :val AND shop_id = :sid AND deleted_at IS NULL LIMIT 1");
                        $chk->execute([':val' => $searchVal, ':sid' => $shop_id]);
                        $exists = (bool) $chk->fetch();
                    }

                    $processedRow = [
                        'line' => $lineNum,
                        'data' => $row,
                        'group_id' => $groupId,
                        'brand_id' => $brandId,
                        'supplier_id' => $supplierId,
                        'status' => $exists ? 'update' : 'new'
                    ];

                    if ($exists)
                        $results['found'][] = $processedRow;
                    else
                        $results['new'][] = $processedRow;
                }

                $results['missing_refs'] = [
                    'groups' => array_keys($missingGroups),
                    'brands' => array_keys($missingBrands),
                    'suppliers' => array_keys($missingSuppliers),
                ];

                $_SESSION['product_import'] = $results;
                $_SESSION['product_import_search_field'] = $searchField;

                echo json_encode([
                    'success' => true,
                    'found_count' => count($results['found']),
                    'new_count' => count($results['new']),
                    'error_count' => count($results['errors']),
                    'found' => $results['found'],
                    'new' => $results['new'],
                    'errors' => $results['errors'],
                    'missing_refs' => $results['missing_refs']
                ]);
                exit;
            }

            // ===== NEW IMPORT SYSTEM: Execute =====
            if ($action === 'import_products_execute') {
                if (!isset($_SESSION['product_import'])) {
                    echo json_encode(['success' => false, 'message' => 'ບໍ່ພົບຂໍ້ມູນ Preview, ກະລຸນາ Preview ໃໝ່']);
                    exit;
                }

                $importData = $_SESSION['product_import'];
                $searchField = $_SESSION['product_import_search_field'] ?? 'product_code';
                if (!in_array($searchField, ['product_code', 'barcode'])) {
                    echo json_encode(['success' => false, 'message' => 'Invalid search field']);
                    exit;
                }
                $autoCreate = ($_POST['auto_create'] ?? '0') === '1';
                $allRows = array_merge($importData['found'], $importData['new']);
                $missingRefs = $importData['missing_refs'];

                $hasMissing = !empty($missingRefs['groups']) || !empty($missingRefs['brands']) || !empty($missingRefs['suppliers']);
                if ($hasMissing && !$autoCreate) {
                    echo json_encode([
                        'success' => false,
                        'message' => 'ມີ ກຸ່ມ/ຍີ່ຫໍ້/ຜູ້ສະໜອງ ທີ່ບໍ່ພົບໃນລະບົບ, ກະລຸນາເປີດ Auto-create',
                        'missing_refs' => $missingRefs
                    ]);
                    exit;
                }

                try {
                    $pdo->beginTransaction();

                    $newGroupMap = [];
                    $newBrandMap = [];
                    $newSuppMap = [];

                    if ($autoCreate) {
                        foreach ($missingRefs['groups'] as $name) {
                            $ins = $pdo->prepare("INSERT INTO product_group (group_name, shop_id) VALUES (:n, :s)");
                            $ins->execute([':n' => trim($name), ':s' => $shop_id]);
                            $newGroupMap[mb_strtolower(trim($name))] = $pdo->lastInsertId();
                        }
                        foreach ($missingRefs['brands'] as $name) {
                            $ins = $pdo->prepare("INSERT INTO brand (brand_name, shop_id) VALUES (:n, :s)");
                            $ins->execute([':n' => trim($name), ':s' => $shop_id]);
                            $newBrandMap[mb_strtolower(trim($name))] = $pdo->lastInsertId();
                        }
                        foreach ($missingRefs['suppliers'] as $name) {
                            $ins = $pdo->prepare("INSERT INTO supplier (supplier_name, shop_id) VALUES (:n, :s)");
                            $ins->execute([':n' => trim($name), ':s' => $shop_id]);
                            $newSuppMap[mb_strtolower(trim($name))] = $pdo->lastInsertId();
                        }
                    }

                    $inserted = 0;
                    $updated = 0;

                    foreach ($allRows as $item) {
                        $row = array_map(fn($v) => trim((string) $v), $item['data']);

                        $groupId = $item['group_id'] ?: 0;
                        if (empty($item['group_id']) && !empty($row['product_group_name']))
                            $groupId = $newGroupMap[mb_strtolower(trim($row['product_group_name']))] ?? 0;

                        $brandId = $item['brand_id'] ?: 0;
                        if (empty($item['brand_id']) && !empty($row['brand_name']))
                            $brandId = $newBrandMap[mb_strtolower(trim($row['brand_name']))] ?? 0;

                        $supplierId = $item['supplier_id'] ?: 0;
                        if (empty($item['supplier_id']) && !empty($row['supplier_name']))
                            $supplierId = $newSuppMap[mb_strtolower(trim($row['supplier_name']))] ?? 0;

                        if ($item['status'] === 'update') {
                            $sets = [];
                            $params = [];
                            if (isset($row['products_name']) && $row['products_name'] !== '') {
                                $sets[] = 'products_name=:pn';
                                $params[':pn'] = $row['products_name'];
                            }
                            if (isset($row['product_code'])) {
                                $sets[] = 'product_code=:pc';
                                $params[':pc'] = $row['product_code'];
                            }
                            if (isset($row['barcode'])) {
                                $sets[] = 'barcode=:bc';
                                $params[':bc'] = $row['barcode'];
                            }
                            if (isset($row['price_1']) && $row['price_1'] !== '') {
                                $sets[] = 'price_1=:p1';
                                $params[':p1'] = $row['price_1'];
                            }
                            if (isset($row['price_2']) && $row['price_2'] !== '') {
                                $sets[] = 'price_2=:p2';
                                $params[':p2'] = $row['price_2'];
                            }
                            if ($groupId) {
                                $sets[] = 'product_group=:gid';
                                $params[':gid'] = $groupId;
                            }
                            if ($brandId) {
                                $sets[] = 'brand=:bid';
                                $params[':bid'] = $brandId;
                            }
                            if ($supplierId) {
                                $sets[] = 'supplier=:sid';
                                $params[':sid'] = $supplierId;
                            }
                            $sets[] = 'updated_by=:uby';
                            $params[':uby'] = $username;
                            $params[':sval'] = $row[$searchField] ?? '';
                            $params[':shopid'] = $shop_id;

                            if (!empty($sets)) {
                                $upd = $pdo->prepare("UPDATE products SET " . implode(',', $sets) . " WHERE {$searchField}=:sval AND shop_id=:shopid AND deleted_at IS NULL");
                                $upd->execute($params);
                                $updated++;
                            }
                        } else {
                            $ins = $pdo->prepare("INSERT INTO products (product_code, barcode, products_name, price_1, price_2, product_group, brand, supplier, create_officer, shop_id) 
                                VALUES (:pc,:bc,:pn,:p1,:p2,:gid,:bid,:supid,:officer,:shopid)");
                            $ins->execute([
                                ':pc' => $row['product_code'] ?? null,
                                ':bc' => $row['barcode'] ?? null,
                                ':pn' => $row['products_name'] ?? '',
                                ':p1' => $row['price_1'] ?? 0,
                                ':p2' => !empty($row['price_2']) ? $row['price_2'] : null,
                                ':gid' => $groupId,
                                ':bid' => $brandId,
                                ':supid' => $supplierId,
                                ':officer' => $username,
                                ':shopid' => $shop_id
                            ]);
                            $inserted++;
                        }
                    }

                    $pdo->commit();
                    unset($_SESSION['product_import'], $_SESSION['product_import_search_field']);

                    echo json_encode([
                        'success' => true,
                        'message' => "Import ສຳເລັດ: ເພີ່ມໃໝ່ {$inserted}, ອັບເດດ {$updated} ລາຍການ",
                        'inserted' => $inserted,
                        'updated' => $updated
                    ]);
                } catch (Exception $e) {
                    $pdo->rollBack();
                    echo json_encode(['success' => false, 'message' => 'Import ລົ້ມເຫຼວ: ' . $e->getMessage()]);
                }
                exit;
            }

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

// ===== Regular Page Load (HTML only, NO data fetch at all) =====
$page_title = 'ຈັດການຂໍ້ມູນ';
require_once '../includes/header.php';

// Dropdowns loaded via AJAX — no PHP queries on page load
?>

<!-- TomSelect CSS -->
<link href="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/css/tom-select.css" rel="stylesheet">
<script defer src="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/js/tom-select.complete.min.js"></script>

<style>
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        flex-wrap: wrap;
        gap: 12px;
    }

    .page-header h2 {
        margin: 0;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .search-wrap {
        display: flex;
        align-items: center;
        gap: 10px;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        padding: 8px 14px;
        width: 350px;
        max-width: 100%;
    }

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

    .search-wrap input::placeholder {
        color: var(--text-secondary);
    }

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

    .pro-table th {
        background: rgba(193, 153, 42, 0.1);
        padding: 12px 14px;
        font-weight: 600;
        font-size: 13px;
        text-transform: uppercase;
        color: var(--text-secondary);
        white-space: nowrap;
        text-align: left;
    }

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

    .pro-table tbody tr:hover {
        background: rgba(193, 153, 42, 0.03);
    }

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

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

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

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

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

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

    .badge-code {
        background: var(--bg-secondary);
        color: var(--accent);
        padding: 3px 8px;
        border-radius: 4px;
        font-size: 12px;
        border: 1px solid var(--border-color);
        font-family: monospace;
    }

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

    .empty-state i {
        font-size: 48px;
        opacity: .3;
        margin-bottom: 15px;
        display: block;
    }

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

    /* Barcode Cell */
    .barcode-cell {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        gap: 2px;
    }

    .barcode-svg {
        max-width: 140px;
        height: 45px;
        background: #ffffff;
        padding: 4px 6px;
        border-radius: 4px;
    }

    .barcode-text {
        font-size: 11px;
        font-family: 'Courier New', monospace;
        color: var(--text-secondary);
        letter-spacing: 1px;
    }

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

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

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

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

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

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

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

    /* Modal */
    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, .7);
        display: none;
        align-items: center;
        justify-content: center;
        z-index: 1000;
        backdrop-filter: blur(4px);
    }

    .modal-overlay.show {
        display: flex;
        animation: fadeIn .25s ease;
    }

    .modal-container {
        background: var(--bg-primary);
        width: 100%;
        max-width: 750px;
        border-radius: 15px;
        border: 1px solid var(--border-color);
        box-shadow: 0 15px 40px rgba(0, 0, 0, .4);
        max-height: 90vh;
        overflow-y: auto;
        animation: slideUp .3s ease;
    }

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

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

    .modal-header h3 i {
        color: var(--accent);
    }

    .modal-body {
        padding: 20px;
    }

    .modal-footer {
        padding: 15px 20px;
        border-top: 1px solid var(--border-color);
        text-align: right;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }

    .close-btn {
        background: none;
        border: none;
        color: var(--text-secondary);
        font-size: 22px;
        cursor: pointer;
        width: 34px;
        height: 34px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .close-btn:hover {
        background: rgba(220, 53, 69, .1);
        color: var(--danger);
    }

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

    .form-group label {
        display: block;
        margin-bottom: 6px;
        font-weight: 500;
        font-size: 14px;
    }

    .form-control {
        width: 100%;
        padding: 10px 14px;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        color: var(--text-primary);
        font-family: inherit;
        font-size: 14px;
        transition: border-color .2s;
    }

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

    .row {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -8px;
    }

    .col-md-6 {
        width: 50%;
        padding: 0 8px;
    }

    .text-danger {
        color: var(--danger);
    }

    @keyframes fadeIn {
        from {
            opacity: 0
        }

        to {
            opacity: 1
        }
    }

    @keyframes slideUp {
        from {
            opacity: 0;
            transform: translateY(20px)
        }

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

    /* Default hide mobile actions on desktop */
    .mobile-actions {
        display: none;
    }

    /* Mobile Card Layout (Professional Grid) */
    @media(max-width:768px) {

        .col-md-6,
        .search-wrap {
            width: 100%;
        }

        .page-header {
            flex-direction: column;
            align-items: flex-start;
        }

        .pro-table thead {
            display: none;
        }

        .pro-table {
            display: block;
            width: 100%;
        }

        /* Card Container */
        .pro-table tbody,
        .pro-table tr {
            display: block;
            width: 100%;
        }

        .pro-table tr {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px 15px;
            margin-bottom: 15px;
            border: 1px solid var(--border-color);
            background: var(--card-bg);
            border-radius: 12px;
            padding: 15px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            position: relative;
        }

        /* Default Cell Style */
        .pro-table td {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            text-align: left;
            padding: 0;
            border: none;
            font-size: 14px;
        }

        /* Label Style (Top of value) */
        .pro-table td::before {
            content: attr(data-label);
            font-size: 11px;
            text-transform: uppercase;
            color: var(--text-secondary);
            margin-bottom: 2px;
            font-weight: 600;
            position: static;
            width: auto;
        }

        /* --- Specific Field Layout --- */



        /* 1. Index # (Top Left) */
        .pro-table td[data-label="#"] {
            position: absolute;
            top: 15px;
            left: 15px;
            right: auto;
            width: auto;
            z-index: 5;
            background: rgba(0, 0, 0, 0.6);
            backdrop-filter: blur(2px);
            padding: 4px 12px;
            border-radius: 6px;
            font-size: 14px;
            font-weight: bold;
            color: #fff;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .pro-table td[data-label="#"]::before {
            display: none;
        }

        /* Mobile Grid Layout for Table Row */
        .pro-table tr {
            display: grid;
            grid-template-columns: 80px 1fr;
            gap: 10px 15px;
            position: relative;
        }

        /* Image (Top Left, Spans 2 Rows) */
        .pro-table td[data-label="ຮູບ"] {
            grid-column: 1 / 2;
            grid-row: 1 / 3;
            padding: 0;
            border: none;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .pro-table td[data-label="ຮູບ"] img {
            width: 80px;
            height: 80px;
            border-radius: 12px;
            object-fit: cover;
            border: 1px solid var(--border-color);
        }

        .pro-table td[data-label="ຮູບ"]::before {
            display: none;
        }

        /* Name (Top Right) */
        .pro-table td[data-label="ຊື່ສິນຄ້າ"] {
            grid-column: 2 / -1;
            grid-row: 1 / 2;
            font-size: 18px;
            /* Larger */
            font-weight: 600;
            color: var(--primary);
            margin-bottom: 0;
            padding: 10px 40px 0 0;
            /* Top padding, Right padding for Menu */
            order: unset;
            display: block;
        }

        .pro-table td[data-label="ຊື່ສິນຄ້າ"]::before {
            display: none;
        }

        /* Code & Barcode (Below Name) */
        .pro-table td[data-label="ລະຫັດສິນຄ້າ"] {
            grid-column: 2 / -1;
            grid-row: 2 / 3;
            font-size: 14px;
            color: var(--text-secondary);
            margin-bottom: 0;
            border-bottom: none;
            padding: 0;
            display: flex;
            align-items: center;
        }

        .pro-table td[data-label="ບາໂຄດ"] {
            grid-column: 2 / -1;
            grid-row: 3 / 4;
            font-size: 14px;
            color: var(--text-secondary);
            text-align: left;
            margin-bottom: 8px;
            border-bottom: 1px solid var(--border-color);
            padding: 0 0 10px 0;
            display: block;
        }

        .pro-table td[data-label="ລະຫັດສິນຄ້າ"]::before,
        .pro-table td[data-label="ບາໂຄດ"]::before {
            display: none;
        }

        /* Details Grid (Full Width Below) */
        .pro-table td[data-label="ກຸ່ມ"],
        .pro-table td[data-label="ຍີ່ຫໍ້"],
        .pro-table td[data-label="ລາຄາ 1"],
        .pro-table td[data-label="ລາຄາ 2"] {
            grid-column: 1 / -1;
        }

        .badge-code {
            background: none;
            padding: 0;
            border: none;
            font-family: monospace;
            font-size: 14px;
            font-weight: bold;
            color: var(--accent);
        }

        /* Details Grid - Larger Text */
        .pro-table td {
            font-size: 15px;
        }

        .pro-table td[data-label="ລາຄາ 1"] {
            color: var(--accent);
            font-weight: 600;
            font-size: 16px;
        }

        /* 5. Actions (Mobile Menu Top Right) */
        .desktop-only {
            display: none !important;
        }

        .mobile-actions {
            display: block;
            position: relative;
        }

        .pro-table td[data-label="ຈັດການ"] {
            position: absolute;
            top: 10px;
            right: 10px;
            width: auto;
            border: none;
            padding: 0;
            margin: 0;
            background: none;
            display: block;
            order: -10;
        }

        .pro-table td[data-label="ຈັດການ"]::before {
            display: none;
        }

        .btn-menu {
            background: none;
            border: none;
            font-size: 20px;
            color: var(--text-secondary);
            padding: 5px 10px;
            cursor: pointer;
        }

        .dropdown-menu {
            position: absolute;
            right: 0;
            top: 100%;
            width: 160px;
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            display: none;
            z-index: 100;
            flex-direction: column;
            overflow: hidden;
        }

        .dropdown-menu.show {
            display: flex;
            animation: fadeIn 0.1s ease;
        }

        .dropdown-menu a {
            padding: 12px 16px;
            color: var(--text-primary);
            text-decoration: none;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 15px;
            background: var(--bg-primary);
        }

        .dropdown-menu a:last-child {
            border-bottom: none;
            color: var(--danger);
        }

        .dropdown-menu a:hover {
            background: rgba(0, 0, 0, 0.03);
        }

        /* Ensure dropdown isn't clipped */
        div[style*="overflow-x:auto"] {
            overflow: visible !important;
        }
    }

    /* TomSelect Customization for Dark/Gold Theme */
    /* TomSelect Customization for Dark/Gold Theme */
    .ts-wrapper.single .ts-control,
    .ts-control {
        background: var(--card-bg) !important;
        border: 1px solid var(--border-color) !important;
        color: var(--text-primary) !important;
        border-radius: 8px;
        padding: 10px 14px;
        font-family: inherit;
        font-size: 14px;
        box-shadow: none !important;
        background-image: none !important;
        /* Remove any gradient/image */
    }

    .ts-control>input {
        color: var(--text-primary) !important;
        font-family: inherit;
        font-size: 14px;
    }

    /* Dropdown Menu */
    .ts-dropdown {
        background: var(--bg-secondary) !important;
        border: 1px solid var(--border-color) !important;
        color: var(--text-primary) !important;
        border-radius: 8px;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4) !important;
        z-index: 10000;
        margin-top: 5px;
    }

    .ts-dropdown .option {
        padding: 10px 14px;
        cursor: pointer;
        color: var(--text-primary);
        /* Ensure text is visible */
    }

    /* Active/Hover State */
    .ts-dropdown .option.active,
    .ts-dropdown .option:hover {
        background: var(--accent) !important;
        color: #fff !important;
    }

    /* Focus State */
    .ts-wrapper.focus .ts-control {
        border-color: var(--accent) !important;
        box-shadow: 0 0 0 2px rgba(193, 153, 42, .15) !important;
    }

    /* Input Group Fix */
    .form-group .ts-wrapper {
        margin-bottom: 0;
    }

    /* Remove default arrow background if needed or style it */
    .ts-wrapper.single .ts-control:after {
        border-color: var(--text-secondary) transparent transparent transparent !important;
    }

    .ts-wrapper.single.dropdown-active .ts-control:after {
        border-color: transparent transparent var(--text-secondary) transparent !important;
    }

    /* Quick Add Button Style */
    .quick-add-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 22px;
        height: 22px;
        border: 1px solid var(--accent);
        border-radius: 50%;
        color: var(--accent);
        font-size: 10px;
        margin-left: 8px;
        text-decoration: none;
        transition: all 0.2s;
        vertical-align: middle;
    }

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

    /* === Export/Import System === */
    .ei-modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, .7);
        display: none;
        align-items: center;
        justify-content: center;
        z-index: 1000;
        backdrop-filter: blur(4px);
    }

    .ei-modal-overlay.show {
        display: flex;
        animation: fadeIn .25s ease;
    }

    .ei-modal {
        background: var(--bg-primary);
        width: 100%;
        max-width: 750px;
        border-radius: 15px;
        border: 1px solid var(--border-color);
        box-shadow: 0 15px 40px rgba(0, 0, 0, .4);
        max-height: 90vh;
        overflow-y: auto;
        animation: slideUp .3s ease;
    }

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

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

    .ei-modal-header h3 i {
        color: var(--accent);
    }

    .ei-modal-body {
        padding: 20px;
    }

    .ei-modal-footer {
        padding: 15px 20px;
        border-top: 1px solid var(--border-color);
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }

    .ei-columns-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 10px;
        margin: 15px 0;
    }

    .ei-col-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 10px 14px;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        cursor: pointer;
        transition: all .2s;
    }

    .ei-col-item:hover {
        border-color: var(--accent);
    }

    .ei-col-item input[type="checkbox"] {
        accent-color: var(--accent);
        width: 16px;
        height: 16px;
    }

    .ei-format-group {
        display: flex;
        gap: 15px;
        margin: 15px 0;
    }

    .ei-format-item {
        flex: 1;
        padding: 14px;
        text-align: center;
        background: var(--card-bg);
        border: 2px solid var(--border-color);
        border-radius: 10px;
        cursor: pointer;
        transition: all .2s;
    }

    .ei-format-item:hover {
        border-color: var(--accent);
    }

    .ei-format-item.active {
        border-color: var(--accent);
        background: rgba(193, 153, 42, .1);
    }

    .ei-format-item i {
        font-size: 24px;
        display: block;
        margin-bottom: 6px;
        color: var(--accent);
    }

    .ei-dropzone {
        border: 2px dashed var(--border-color);
        border-radius: 12px;
        padding: 40px 20px;
        text-align: center;
        cursor: pointer;
        transition: all .2s;
        margin: 15px 0;
    }

    .ei-dropzone:hover,
    .ei-dropzone.dragover {
        border-color: var(--accent);
        background: rgba(193, 153, 42, .05);
    }

    .ei-dropzone i {
        font-size: 40px;
        color: var(--text-secondary);
        opacity: .4;
        display: block;
        margin-bottom: 10px;
    }

    .ei-preview-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 13px;
        margin: 15px 0;
    }

    .ei-preview-table th {
        background: rgba(193, 153, 42, .1);
        padding: 8px 10px;
        text-align: left;
        font-size: 12px;
        white-space: nowrap;
        font-weight: 600;
    }

    .ei-preview-table td {
        padding: 8px 10px;
        border-bottom: 1px solid var(--border-color);
    }

    .ei-badge {
        padding: 3px 8px;
        border-radius: 4px;
        font-size: 11px;
        font-weight: 600;
    }

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

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

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

    .ei-stats {
        display: flex;
        gap: 12px;
        margin: 15px 0;
        flex-wrap: wrap;
    }

    .ei-stat-item {
        padding: 10px 16px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .ei-stat-item.found {
        background: rgba(23, 162, 184, .1);
        color: #17a2b8;
    }

    .ei-stat-item.new-stat {
        background: rgba(40, 167, 69, .1);
        color: #28a745;
    }

    .ei-stat-item.err-stat {
        background: rgba(220, 53, 69, .1);
        color: #dc3545;
    }

    .ei-missing-list {
        background: rgba(255, 193, 7, .1);
        border: 1px solid rgba(255, 193, 7, .3);
        border-radius: 8px;
        padding: 12px 15px;
        margin: 10px 0;
    }

    .ei-missing-list h4 {
        margin: 0 0 8px;
        font-size: 14px;
        color: #ffc107;
    }

    .ei-missing-list ul {
        margin: 0;
        padding-left: 20px;
    }

    .ei-missing-list li {
        font-size: 13px;
        margin-bottom: 4px;
    }

    .ei-toggle {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 12px 15px;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        margin: 10px 0;
        cursor: pointer;
    }

    .ei-toggle input[type="checkbox"] {
        accent-color: var(--accent);
        width: 18px;
        height: 18px;
    }

    @media(max-width:768px) {
        .ei-columns-grid {
            grid-template-columns: 1fr
        }

        .ei-modal {
            max-width: 95%;
            margin: 10px
        }
    }
</style>

<!-- Page Header -->
<div class="page-header">
    <h2><i class="fas fa-box" style="color:var(--accent)"></i> ຈັດການສິນຄ້າ</h2>
    <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
        <div class="search-wrap">
            <i class="fas fa-search" style="color:var(--text-secondary)"></i>
            <input type="text" id="searchInput" placeholder="ຄົ້ນຫາ: ຊື່, ລະຫັດ, ບາໂຄດ..." oninput="debounceSearch()">
        </div>
        <?php if ($user_role !== 'staff'): ?>
            <button class="btn btn-secondary" onclick="openExportModal()"
                style="border:1px solid var(--success);color:var(--success);">
                <i class="fas fa-file-export"></i> Export all
            </button>
            <button class="btn btn-secondary" onclick="openImportModal()" style="border:1px solid #17a2b8;color:#17a2b8;">
                <i class="fas fa-file-import"></i> Import all
            </button>
            <button class="btn btn-secondary" onclick="window.location.href='import_csv_product.php'"
                style="border:1px solid var(--accent);color:var(--accent);">
                <i class="fas fa-file-csv"></i> ປ່ຽນຂໍ້ມູສີນຄ້າ
            </button>
        <?php endif; ?>
        <button class="btn btn-primary" onclick="openModal('add')">
            <i class="fas fa-plus-circle"></i> ເພີ່ມສິນຄ້າ
        </button>
    </div>
</div>

<!-- Data Card -->
<div class="card">
    <div style="overflow-x:auto;">
        <table class="pro-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>ຮູບ</th>
                    <th>ລະຫັດສິນຄ້າ</th>
                    <th>ບາໂຄດ</th>
                    <th>ຊື່ສິນຄ້າ</th>
                    <th>ກຸ່ມ</th>
                    <th>ຍີ່ຫໍ້</th>
                    <th>ລາຄາ 1</th>
                    <th>ລາຄາ 2</th>
                    <th style="text-align:center">ຈັດການ</th>
                </tr>
            </thead>
            <tbody id="tableBody">
                <tr>
                    <td colspan="10" class="loading-state"><i class="fas fa-spinner fa-spin"></i> ກຳລັງໂຫຼດ...</td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="pagination-wrap" id="paginationWrap">
        <div class="pagination-info" id="paginationInfo"></div>
        <div class="pagination-btns" id="paginationBtns"></div>
    </div>
</div>

<!-- Modal -->
<div class="modal-overlay" id="productModal">
    <div class="modal-container">
        <div class="modal-header">
            <h3 id="modalTitle"><i class="fas fa-plus-circle"></i> ເພີ່ມສິນຄ້າ</h3>
            <button class="close-btn" onclick="closeModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="productForm" onsubmit="saveProduct(event)">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="id" id="productId">

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>ລະຫັດສິນຄ້າ (SKU)</label>
                            <input type="text" class="form-control" id="product_code" name="product_code"
                                placeholder="ໃສ່ລະຫັດ">
                        </div>
                        <div class="form-group">
                            <label>ຊື່ສິນຄ້າ <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="products_name" name="products_name" required
                                placeholder="ໃສ່ຊື່ສິນຄ້າ">
                        </div>
                        <div class="form-group">
                            <label>ຮູບສິນຄ້າ</label>
                            <input type="file" class="form-control" name="image" id="imageInput" accept="image/*"
                                style="margin-bottom:8px;">
                            <span style="font-size:12px;color:var(--text-secondary);">(ຫຼື Ctrl+V
                                ວາງຮູບໃນກອບຂ້າງລຸ່ມ)</span>
                            <div id="imageDropzone" tabindex="0"
                                style="outline:none;min-height:120px;border:2px dashed var(--border-color);border-radius:12px;padding:16px;margin-top:8px;text-align:center;cursor:pointer;transition:all 0.2s;"
                                onmouseover="this.focus()" onfocus="this.style.borderColor='var(--accent)'"
                                onblur="this.style.borderColor='var(--border-color)'">
                                <img id="imagePreview" src="" alt="Image Preview"
                                    style="max-width: 100%; max-height: 150px; border-radius: 8px; display: none; border: 1px solid var(--border-color); object-fit: contain;">
                                <div id="imageDropzoneText" style="color:var(--text-secondary);padding:20px 0;">
                                    <i class="fas fa-image"
                                        style="font-size:32px;opacity:0.3;display:block;margin-bottom:8px;"></i>
                                    ຄລິກທີ່ນີ້ແລ້ວກົດ Ctrl+V ວາງຮູບ<br>
                                    <span style="font-size:12px;opacity:0.7;">ຫຼື ລາກຮູບມາວາງ</span>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>ກຸ່ມສິນຄ້າ <span class="text-danger">*</span>
                                <a href="javascript:void(0)" onclick="addOption('group')" class="quick-add-btn"><i
                                        class="fas fa-plus"></i></a>
                            </label>
                            <select class="form-control" id="product_group" name="product_group" required>
                                <option value="">-- ເລືອກກຸ່ມສິນຄ້າ --</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>ຍີ່ຫໍ້ <span class="text-danger">*</span>
                                <a href="javascript:void(0)" onclick="addOption('brand')" class="quick-add-btn"><i
                                        class="fas fa-plus"></i></a>
                            </label>
                            <select class="form-control" id="brand" name="brand" required>
                                <option value="">-- ເລືອກຍີ່ຫໍ້ --</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>ບາໂຄດ</label>
                            <input type="text" class="form-control" id="barcode" name="barcode" placeholder="ໃສ່ບາໂຄດ">
                        </div>
                        <div class="form-group">
                            <label>ລາຄາຂາຍ 1 <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" class="form-control" id="price_1" name="price_1" required
                                placeholder="0.00">
                        </div>
                        <div class="form-group">
                            <label>ລາຄາຂາຍ 2</label>
                            <input type="number" step="0.01" class="form-control" id="price_2" name="price_2"
                                placeholder="0.00">
                        </div>
                        <div class="form-group">
                            <label>ຜູ້ສະໜອງ
                                <a href="javascript:void(0)" onclick="addOption('supplier')" class="quick-add-btn"><i
                                        class="fas fa-plus"></i></a>
                            </label>
                            <select class="form-control" id="supplier" name="supplier">
                                <option value="">-- ເລືອກຜູ້ສະໜອງ --</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">ຍົກເລີກ</button>
                    <button type="submit" class="btn btn-primary" id="btnSave"><i class="fas fa-save"></i>
                        ບັນທຶກ</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ===== EXPORT MODAL ===== -->
<div class="ei-modal-overlay" id="exportModal" onclick="if(event.target===this)closeExportModal()">
    <div class="ei-modal">
        <div class="ei-modal-header">
            <h3><i class="fas fa-file-export"></i> Export ສິນຄ້າ</h3>
            <button class="close-btn" onclick="closeExportModal()">&times;</button>
        </div>
        <div class="ei-modal-body">
            <p style="margin-bottom:8px;font-weight:500;">ເລືອກຄອລັມທີ່ຕ້ອງການ Export:</p>
            <div style="margin-bottom:10px">
                <a href="javascript:void(0)" onclick="toggleAllExportCols(true)"
                    style="font-size:13px;color:var(--accent);margin-right:15px">✅ ເລືອກທັງໝົດ</a>
                <a href="javascript:void(0)" onclick="toggleAllExportCols(false)"
                    style="font-size:13px;color:var(--text-secondary)">❌ ຍົກເລີກທັງໝົດ</a>
            </div>
            <div class="ei-columns-grid">
                <label class="ei-col-item"><input type="checkbox" value="product_code" checked class="exp-col">
                    ລະຫັດສິນຄ້າ (SKU)</label>
                <label class="ei-col-item"><input type="checkbox" value="barcode" checked class="exp-col"> ບາໂຄດ</label>
                <label class="ei-col-item"><input type="checkbox" value="products_name" checked class="exp-col">
                    ຊື່ສິນຄ້າ</label>
                <label class="ei-col-item"><input type="checkbox" value="price_1" checked class="exp-col"> ລາຄາຂາຍ
                    1</label>
                <label class="ei-col-item"><input type="checkbox" value="price_2" checked class="exp-col"> ລາຄາຂາຍ
                    2</label>
                <label class="ei-col-item"><input type="checkbox" value="product_group" checked class="exp-col">
                    ກຸ່ມສິນຄ້າ</label>
                <label class="ei-col-item"><input type="checkbox" value="brand" checked class="exp-col"> ຍີ່ຫໍ້</label>
                <label class="ei-col-item"><input type="checkbox" value="supplier" checked class="exp-col">
                    ຜູ້ສະໜອງ</label>
            </div>
            <p style="margin:15px 0 8px;font-weight:500;">ເລືອກ Format:</p>
            <div class="ei-format-group">
                <div class="ei-format-item active" onclick="selectExportFormat('csv',this)">
                    <i class="fas fa-file-csv"></i> CSV
                </div>
                <div class="ei-format-item" onclick="selectExportFormat('excel',this)">
                    <i class="fas fa-file-excel"></i> Excel
                </div>
            </div>
            <input type="hidden" id="exportFormat" value="csv">
        </div>
        <div class="ei-modal-footer">
            <button class="btn btn-secondary" onclick="closeExportModal()">ຍົກເລີກ</button>
            <button class="btn btn-primary" onclick="executeExport()"><i class="fas fa-download"></i> Export</button>
        </div>
    </div>
</div>

<!-- ===== IMPORT MODAL ===== -->
<div class="ei-modal-overlay" id="importModal" onclick="if(event.target===this)closeImportModal()">
    <div class="ei-modal">
        <div class="ei-modal-header">
            <h3><i class="fas fa-file-import"></i> Import ສິນຄ້າ</h3>
            <button class="close-btn" onclick="closeImportModal()">&times;</button>
        </div>
        <div class="ei-modal-body">
            <!-- Step 1: Upload -->
            <div id="importStep1">
                <p style="font-weight:500;margin-bottom:10px">ຂັ້ນຕອນ 1: ເລືອກໄຟລ໌ ແລະ ຕັ້ງຄ່າ</p>
                <div class="form-group">
                    <label>ໃຊ້ field ໃດກວດສອບວ່າມີສິນຄ້າຢູ່ແລ້ວ:</label>
                    <select class="form-control" id="importSearchField">
                        <option value="product_code">product_code (ລະຫັດສິນຄ້າ)</option>
                        <option value="barcode">barcode (ບາໂຄດ)</option>
                    </select>
                </div>
                <div class="ei-dropzone" id="importDropzone"
                    onclick="document.getElementById('importFileInput').click()">
                    <i class="fas fa-cloud-upload-alt"></i>
                    <p style="color:var(--text-secondary)">ຄລິກ ຫຼື ລາກໄຟລ໌ CSV/Excel ມາທີ່ນີ້</p>
                    <p style="font-size:12px;color:var(--text-secondary);opacity:.6">ຮອງຮັບ .csv, .xlsx, .xls</p>
                </div>
                <input type="file" id="importFileInput" accept=".csv,.xlsx,.xls" style="display:none"
                    onchange="handleImportFile(this)">
                <div id="importFileName"
                    style="display:none;padding:10px 15px;background:var(--card-bg);border:1px solid var(--border-color);border-radius:8px;margin-top:10px">
                    <i class="fas fa-file" style="color:var(--accent);margin-right:8px"></i>
                    <span id="importFileNameText"></span>
                </div>
            </div>

            <!-- Step 2: Preview -->
            <div id="importStep2" style="display:none">
                <p style="font-weight:500;margin-bottom:10px">ຂັ້ນຕອນ 2: ກວດສອບຂໍ້ມູນ</p>
                <div class="ei-stats" id="importStats"></div>
                <div id="importMissingRefs"></div>
                <div id="importPreviewWrap" style="max-height:400px;overflow:auto"></div>
            </div>

            <!-- Step 3: Execute -->
            <div id="importStep3" style="display:none">
                <div style="text-align:center;padding:30px">
                    <i class="fas fa-check-circle"
                        style="font-size:60px;color:var(--success);display:block;margin-bottom:15px"></i>
                    <h3 id="importResultTitle" style="margin-bottom:10px"></h3>
                    <p id="importResultMsg" style="color:var(--text-secondary)"></p>
                </div>
            </div>
        </div>
        <div class="ei-modal-footer" id="importFooter">
            <button class="btn btn-secondary" onclick="closeImportModal()">ຍົກເລີກ</button>
            <button class="btn btn-primary" id="btnImportPreview" onclick="previewImport()" disabled><i
                    class="fas fa-search"></i> Preview</button>
            <button class="btn btn-primary" id="btnImportExecute" style="display:none" onclick="executeImport()"><i
                    class="fas fa-upload"></i> ດຳເນີນການ Import</button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js"></script>
<script>
    let currentPage = 1;
    let currentSearch = '';
    let searchTimer = null;

    // === Client-side Lookup Cache ===
    let lookupCache = null; // { brands: {id: name}, groups: {id: name}, suppliers: {id: name} }
    let lookupPromise = null;

    function fetchLookups() {
        if (lookupCache) return Promise.resolve(lookupCache);
        if (lookupPromise) return lookupPromise;

        lookupPromise = fetch('make_product.php?ajax=dropdowns')
            .then(r => r.json())
            .then(res => {
                if (!res.success) throw new Error('Failed to load dropdowns');
                lookupCache = {
                    brands: {},
                    groups: {},
                    suppliers: {},
                    brandsArr: res.brands,
                    groupsArr: res.groups,
                    suppliersArr: res.suppliers
                };
                res.brands.forEach(b => lookupCache.brands[b.id] = b.name);
                res.groups.forEach(g => lookupCache.groups[g.id] = g.name);
                res.suppliers.forEach(s => lookupCache.suppliers[s.id] = s.name);
                return lookupCache;
            });
        return lookupPromise;
    }

    const NO_IMG = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI4MCIgaGVpZ2h0PSI4MCIgdmlld0JveD0iMCAwIDgwIDgwIj48cmVjdCB3aWR0aD0iODAiIGhlaWdodD0iODAiIGZpbGw9IiNmMmYyZjIiLz48dGV4dCB4PSI1MCUiIHk9IjUwJSIgZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZm9udC1mYW1pbHk9InNhbnMtc2VyaWYiIGZvbnQtc2l6ZT0iMTIiIGZpbGw9IiM5OTkiPk5vIEltYWdlPC90ZXh0Pjwvc3ZnPg==';

    // Load data on page ready
    document.addEventListener('DOMContentLoaded', () => loadProducts(1));

    function debounceSearch() {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(() => {
            currentSearch = document.getElementById('searchInput').value;
            loadProducts(1);
        }, 400);
    }

    function loadProducts(page) {
        currentPage = page;
        const tbody = document.getElementById('tableBody');
        tbody.innerHTML = '<tr><td colspan="10" class="loading-state"><i class="fas fa-spinner fa-spin"></i> ກຳລັງໂຫຼດ...</td></tr>';

        const params = new URLSearchParams({ ajax: 'list', page: page, search: currentSearch });

        // Fetch products and lookups in parallel
        Promise.all([
            fetch('make_product.php?' + params.toString()).then(r => r.json()),
            fetchLookups()
        ])
            .then(([res, cache]) => {
                if (!res.success) { tbody.innerHTML = '<tr><td colspan="10" class="empty-state">Error</td></tr>'; return; }

                const rows = res.data;
                if (rows.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="10" class="empty-state"><i class="fas fa-inbox"></i> ບໍ່ພົບຂໍ້ມູນ</td></tr>';
                    document.getElementById('paginationInfo').textContent = '';
                    document.getElementById('paginationBtns').innerHTML = '';
                    return;
                }

                let html = '';
                const startNum = (res.page - 1) * res.limit;
                rows.forEach((p, i) => {
                    // Resolve names client-side
                    const groupName = cache.groups[p.product_group] || p.product_group || '-';
                    const brandName = cache.brands[p.brand] || p.brand || '-';
                    const rowData = JSON.stringify(p).replace(/'/g, "\\'").replace(/"/g, '&quot;');
                    const imgUrl = p.image ? `../api/get_image.php?f=${p.image}&w=100` : NO_IMG;
                    html += `<tr>
                    <td data-label="#"><span class="index-badge">${startNum + i + 1}</span></td>
                    <td data-label="ຮູບ"><img src="${imgUrl}" style="width:40px;height:40px;border-radius:4px;object-fit:cover;border:1px solid #eee" loading="lazy" decoding="async"></td>
                    <td data-label="ລະຫັດສິນຄ້າ"><span class="badge-code">${escHtml(p.product_code || '-')}</span></td>
                    <td data-label="ບາໂຄດ">${p.barcode ? '<div class="barcode-cell"><svg class="barcode-svg" data-barcode="' + escHtml(p.barcode) + '"></svg><span class="barcode-text">' + escHtml(p.barcode) + '</span></div>' : '-'}</td>
                    <td data-label="ຊື່ສິນຄ້າ">${escHtml(p.products_name)}</td>
                    <td data-label="ກຸ່ມ">${escHtml(groupName)}</td>
                    <td data-label="ຍີ່ຫໍ້">${escHtml(brandName)}</td>
                    <td data-label="ລາຄາ 1">${numFmt(p.price_1)}</td>
                    <td data-label="ລາຄາ 2">${numFmt(p.price_2)}</td>
                    <td style="text-align:center" data-label="ຈັດການ">
                        <!-- Desktop Actions -->
                        <div class="action-btns desktop-only" style="justify-content:center">
                            <button class="btn-icon edit" onclick='openModal("edit", ${rowData})'><i class="fas fa-pen"></i></button>
                            <?php if ($user_role !== 'staff'): ?>
                            <button class="btn-icon delete" onclick="deleteProduct(${p.id})"><i class="fas fa-trash"></i></button>
                            <?php endif; ?>
                        </div>
                        <!-- Mobile Dropdown -->
                        <div class="mobile-actions">
                            <button class="btn-menu" onclick="toggleMenu(event, ${p.id})"><i class="fas fa-ellipsis-v"></i></button>
                            <div id="menu-${p.id}" class="dropdown-menu">
                                <a href="javascript:void(0)" onclick='openModal("edit", ${rowData}); toggleMenu(event, ${p.id})'>
                                    <i class="fas fa-pen" style="color:var(--accent)"></i> ແກ້ໄຂຂໍ້ມູນ
                                </a>
                                <?php if ($user_role !== 'staff'): ?>
                                <a href="javascript:void(0)" onclick="deleteProduct(${p.id}); toggleMenu(event, ${p.id})">
                                    <i class="fas fa-trash"></i> ລຶບຂໍ້ມູນ
                                </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </td>
                </tr>`;
                });
                tbody.innerHTML = html;

                // Generate visual barcodes
                document.querySelectorAll('.barcode-svg[data-barcode]').forEach(svg => {
                    try {
                        const code = svg.dataset.barcode.trim();
                        let fmt = 'CODE128';
                        if (/^\d+$/.test(code)) {
                            if (code.length === 13) fmt = 'EAN13';
                            else if (code.length === 12) fmt = 'UPC';
                            else if (code.length === 8) fmt = 'EAN8';
                        }
                        JsBarcode(svg, code, {
                            format: fmt, width: 2, height: 50, displayValue: true,
                            fontSize: 12, margin: 2, background: '#ffffff', lineColor: '#000000'
                        });
                    } catch (e) { /* invalid barcode format, skip */ }
                });

                // Pagination
                const from = startNum + 1;
                const to = startNum + rows.length;
                document.getElementById('paginationInfo').textContent = `ສະແດງ ${from}-${to} ຈາກ ${res.total.toLocaleString()} ລາຍການ`;
                renderPagination(res.page, res.totalPages);
            })
            .catch(err => {
                console.error(err);
                tbody.innerHTML = '<tr><td colspan="10" class="empty-state">ເກີດຂໍ້ຜິດພາດ</td></tr>';
            });
    }

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

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

        let start = Math.max(1, current - 2);
        let end = Math.min(total, start + 4);
        if (end - start < 4) start = Math.max(1, end - 4);

        for (let p = start; p <= end; p++) {
            html += `<button onclick="loadProducts(${p})" class="${p === current ? 'active' : ''}">${p}</button>`;
        }

        html += `<button onclick="loadProducts(${current + 1})" ${current === total ? 'disabled' : ''}><i class="fas fa-chevron-right"></i></button>`;
        html += `<button onclick="loadProducts(${total})" ${current === total ? 'disabled' : ''}>»</button>`;
        container.innerHTML = html;
    }

    function escHtml(str) {
        if (!str) return '';
        const d = document.createElement('div');
        d.textContent = str;
        return d.innerHTML;
    }

    function numFmt(val) {
        if (!val || val == 0) return '-';
        return Number(val).toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
    }

    // === TomSelect — Lazy Init (only on first modal open) ===
    let tsGroup, tsBrand, tsSupplier;
    let tomSelectReady = false;

    function ensureTomSelect() {
        return new Promise((resolve) => {
            if (tomSelectReady) { resolve(); return; }
            if (typeof TomSelect === 'undefined') {
                // Wait for defer script
                const check = setInterval(() => {
                    if (typeof TomSelect !== 'undefined') {
                        clearInterval(check);
                        initTomSelect().then(resolve);
                    }
                }, 50);
            } else {
                initTomSelect().then(resolve);
            }
        });
    }

    async function initTomSelect() {
        const cache = await fetchLookups();
        const tsOptions = { create: false, sortField: { field: 'text', direction: 'asc' } };

        // Populate <select> options from cached data
        const groupSel = document.getElementById('product_group');
        cache.groupsArr.forEach(g => {
            const opt = document.createElement('option');
            opt.value = g.id; opt.textContent = g.name;
            groupSel.appendChild(opt);
        });

        const brandSel = document.getElementById('brand');
        cache.brandsArr.forEach(b => {
            const opt = document.createElement('option');
            opt.value = b.id; opt.textContent = b.name;
            brandSel.appendChild(opt);
        });

        const supplierSel = document.getElementById('supplier');
        cache.suppliersArr.forEach(s => {
            const opt = document.createElement('option');
            opt.value = s.id; opt.textContent = s.name;
            supplierSel.appendChild(opt);
        });

        tsGroup = new TomSelect('#product_group', tsOptions);
        tsBrand = new TomSelect('#brand', tsOptions);
        tsSupplier = new TomSelect('#supplier', tsOptions);
        tomSelectReady = true;
    }

    // === Modal Functions ===
    async function openModal(mode, data) {
        const modal = document.getElementById('productModal');
        const form = document.getElementById('productForm');
        const title = document.getElementById('modalTitle');

        modal.classList.add('show');
        await ensureTomSelect();

        if (mode === 'add') {
            title.innerHTML = '<i class="fas fa-plus-circle"></i> ເພີ່ມສິນຄ້າ';
            document.getElementById('formAction').value = 'add';
            form.reset();
            document.getElementById('productId').value = '';

            if (tsGroup) tsGroup.clear();
            if (tsBrand) tsBrand.clear();
            if (tsSupplier) tsSupplier.clear();

            const preview = document.getElementById('imagePreview');
            const dropText = document.getElementById('imageDropzoneText');
            preview.src = ''; preview.style.display = 'none';
            if (dropText) dropText.style.display = 'block';
        } else {
            title.innerHTML = '<i class="fas fa-edit"></i> ແກ້ໄຂສິນຄ້າ';
            document.getElementById('formAction').value = 'edit';

            if (typeof data === 'string') data = JSON.parse(data);

            document.getElementById('productId').value = data.id;
            document.getElementById('product_code').value = data.product_code || '';
            document.getElementById('barcode').value = data.barcode || '';
            document.getElementById('products_name').value = data.products_name || '';
            document.getElementById('price_1').value = data.price_1 || '';
            document.getElementById('price_2').value = data.price_2 || '';

            if (tsGroup) tsGroup.setValue(data.product_group || '');
            if (tsBrand) tsBrand.setValue(data.brand || '');
            if (tsSupplier) tsSupplier.setValue(data.supplier || '');

            const preview = document.getElementById('imagePreview');
            const dropText = document.getElementById('imageDropzoneText');
            if (data.image) {
                preview.src = '../../img/products/' + data.image;
                preview.style.display = 'block';
                if (dropText) dropText.style.display = 'none';
            } else {
                preview.src = ''; preview.style.display = 'none';
                if (dropText) dropText.style.display = 'block';
            }
        }
    }

    // Preview new image selection
    document.getElementById('imageInput').addEventListener('change', function (e) {
        const preview = document.getElementById('imagePreview');
        const dropText = document.getElementById('imageDropzoneText');
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function (e) {
                preview.src = e.target.result;
                preview.style.display = 'block';
                if (dropText) dropText.style.display = 'none';
            }
            reader.readAsDataURL(file);
        }
    });

    // Paste Image into product image dropzone
    const imageDropzone = document.getElementById('imageDropzone');
    if (imageDropzone) {
        imageDropzone.addEventListener('paste', function (e) {
            const items = (e.clipboardData || e.originalEvent.clipboardData).items;
            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) {
                        // Set the file to the input via DataTransfer
                        const dt = new DataTransfer();
                        dt.items.add(file);
                        document.getElementById('imageInput').files = dt.files;

                        // Show preview
                        const reader = new FileReader();
                        reader.onload = function (ev) {
                            const preview = document.getElementById('imagePreview');
                            const dropText = document.getElementById('imageDropzoneText');
                            preview.src = ev.target.result;
                            preview.style.display = 'block';
                            if (dropText) dropText.style.display = 'none';
                        };
                        reader.readAsDataURL(file);
                        e.preventDefault();
                        break;
                    }
                }
            }
        });

        // Drag and drop support
        imageDropzone.addEventListener('dragover', e => {
            e.preventDefault();
            imageDropzone.style.borderColor = 'var(--accent)';
            imageDropzone.style.backgroundColor = 'rgba(193, 153, 42, 0.05)';
        });
        imageDropzone.addEventListener('dragleave', e => {
            e.preventDefault();
            imageDropzone.style.borderColor = 'var(--border-color)';
            imageDropzone.style.backgroundColor = 'transparent';
        });
        imageDropzone.addEventListener('drop', e => {
            e.preventDefault();
            imageDropzone.style.borderColor = 'var(--border-color)';
            imageDropzone.style.backgroundColor = 'transparent';
            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
                const file = e.dataTransfer.files[0];
                if (file.type.startsWith('image/')) {
                    // Set the file to the input
                    const dt = new DataTransfer();
                    dt.items.add(file);
                    document.getElementById('imageInput').files = dt.files;

                    // Show preview
                    const reader = new FileReader();
                    reader.onload = function (ev) {
                        const preview = document.getElementById('imagePreview');
                        const dropText = document.getElementById('imageDropzoneText');
                        preview.src = ev.target.result;
                        preview.style.display = 'block';
                        if (dropText) dropText.style.display = 'none';
                    };
                    reader.readAsDataURL(file);
                }
            }
        });
    }

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

    function saveProduct(event) {
        event.preventDefault();
        const formData = new FormData(document.getElementById('productForm'));
        const btn = document.getElementById('btnSave');
        const btnOriginal = btn.innerHTML;

        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> ກຳລັງບັນທຶກ...';

        fetch('make_product.php', { method: 'POST', body: formData })
            .then(r => r.json())
            .then(data => {
                btn.disabled = false;
                btn.innerHTML = btnOriginal;
                if (data.success) {
                    closeModal();
                    Swal.fire({ icon: 'success', title: 'ສຳເລັດ!', text: data.message, timer: 1500, showConfirmButton: false });
                    loadProducts(currentPage);
                } else {
                    Swal.fire({ icon: 'error', title: 'ຜິດພາດ!', text: data.message });
                }
            })
            .catch(() => {
                btn.disabled = false;
                btn.innerHTML = btnOriginal;
                Swal.fire({ icon: 'error', title: 'Error', text: 'Something went wrong!' });
            });
    }

    function deleteProduct(id) {
        Swal.fire({
            title: 'ຢືນຢັນການລຶບ?',
            text: 'ທ່ານຕ້ອງການລຶບສິນຄ້ານີ້ແທ້ບໍ່?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'ລຶບ!',
            cancelButtonText: 'ຍົກເລີກ'
        }).then(result => {
            if (result.isConfirmed) {
                const fd = new FormData();
                fd.append('action', 'delete');
                fd.append('id', id);
                fetch('make_product.php', { method: 'POST', body: fd })
                    .then(r => r.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire('ລຶບສຳເລັດ!', data.message, 'success');
                            loadProducts(currentPage);
                        } else {
                            Swal.fire('ຜິດພາດ!', data.message, 'error');
                        }
                    });
            }
        });
    }

    // === Quick Add Function ===
    function addOption(type) {
        let title, action, field;
        if (type === 'group') { title = 'ເພີ່ມກຸ່ມສິນຄ້າ'; action = 'add_group'; field = 'ຊື່ກຸ່ມສິນຄ້າ'; }
        else if (type === 'brand') { title = 'ເພີ່ມຍີ່ຫໍ້'; action = 'add_brand'; field = 'ຊື່ຍີ່ຫໍ້'; }
        else if (type === 'supplier') { title = 'ເພີ່ມຜູ້ສະໜອງ'; action = 'add_supplier'; field = 'ຊື່ຜູ້ສະໜອງ'; }

        Swal.fire({
            title: title,
            input: 'text',
            inputLabel: field,
            inputPlaceholder: 'ໃສ່' + field,
            showCancelButton: true,
            confirmButtonText: 'ບັນທຶກ',
            cancelButtonText: 'ຍົກເລີກ',
            inputValidator: (value) => {
                if (!value) { return 'ກະລຸນາໃສ່ຂໍ້ມູນ!' }
            }
        }).then((result) => {
            if (result.isConfirmed) {
                const fd = new FormData();
                fd.append('action', action);
                fd.append('name', result.value);

                fetch('make_product.php', { method: 'POST', body: fd })
                    .then(r => r.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire('ສຳເລັດ!', 'ເພີ່ມຂໍ້ມູນຮຽບຮ້ອຍແລ້ວ', 'success');

                            // Add to TomSelect
                            let ts;
                            if (type === 'group') ts = tsGroup;
                            else if (type === 'brand') ts = tsBrand;
                            else if (type === 'supplier') ts = tsSupplier;

                            if (ts) {
                                ts.addOption({ value: data.id, text: data.name });
                                ts.addItem(data.id);

                                // Update Local Cache so it persists
                                if (lookupCache) {
                                    if (type === 'group') lookupCache.groups[data.id] = data.name;
                                    else if (type === 'brand') lookupCache.brands[data.id] = data.name;
                                    else if (type === 'supplier') lookupCache.suppliers[data.id] = data.name;
                                }
                            }
                        } else {
                            Swal.fire('ຜິດພາດ!', data.message, 'error');
                        }
                    });
            }
        });
    }

    // Close modal on overlay click
    document.getElementById('productModal').addEventListener('click', e => { if (e.target === document.getElementById('productModal')) closeModal(); });

    // === Dropdown Menu Logic ===
    function toggleMenu(e, id) {
        e.stopPropagation();
        document.querySelectorAll('.dropdown-menu.show').forEach(m => {
            if (m.id !== `menu-${id}`) m.classList.remove('show');
        });
        const menu = document.getElementById(`menu-${id}`);
        if (menu) menu.classList.toggle('show');
    }

    window.addEventListener('click', () => {
        document.querySelectorAll('.dropdown-menu.show').forEach(m => m.classList.remove('show'));
    });

    // ===== EXPORT SYSTEM =====
    let importParsedData = null;

    function openExportModal() { document.getElementById('exportModal').classList.add('show'); }
    function closeExportModal() { document.getElementById('exportModal').classList.remove('show'); }

    function toggleAllExportCols(state) {
        document.querySelectorAll('.exp-col').forEach(cb => cb.checked = state);
    }

    function selectExportFormat(fmt, el) {
        document.getElementById('exportFormat').value = fmt;
        document.querySelectorAll('.ei-format-item').forEach(e => e.classList.remove('active'));
        el.classList.add('active');
    }

    function executeExport() {
        const cols = [...document.querySelectorAll('.exp-col:checked')].map(c => c.value);
        if (cols.length === 0) {
            Swal.fire({ icon: 'warning', title: 'ກະລຸນາເລືອກຢ່າງໜ້ອຍ 1 ຄອລັມ' });
            return;
        }
        const fmt = document.getElementById('exportFormat').value;
        const url = `make_product.php?ajax=export_products&columns=${cols.join(',')}&format=${fmt}`;
        window.location.href = url;
        closeExportModal();
        Swal.fire({ icon: 'success', title: 'ກຳລັງ Export...', timer: 1500, showConfirmButton: false });
    }

    // ===== IMPORT SYSTEM =====
    function openImportModal() {
        document.getElementById('importModal').classList.add('show');
        resetImportModal();
    }
    function closeImportModal() {
        document.getElementById('importModal').classList.remove('show');
        resetImportModal();
    }

    function resetImportModal() {
        importParsedData = null;
        document.getElementById('importStep1').style.display = 'block';
        document.getElementById('importStep2').style.display = 'none';
        document.getElementById('importStep3').style.display = 'none';
        document.getElementById('btnImportPreview').disabled = true;
        document.getElementById('btnImportPreview').style.display = '';
        document.getElementById('btnImportExecute').style.display = 'none';
        document.getElementById('importFileName').style.display = 'none';
        document.getElementById('importFileInput').value = '';
        document.getElementById('importStats').innerHTML = '';
        document.getElementById('importMissingRefs').innerHTML = '';
        document.getElementById('importPreviewWrap').innerHTML = '';
    }

    function handleImportFile(input) {
        const file = input.files[0];
        if (!file) return;

        document.getElementById('importFileName').style.display = 'block';
        document.getElementById('importFileNameText').textContent = file.name;

        const reader = new FileReader();
        reader.onload = function (e) {
            try {
                const data = new Uint8Array(e.target.result);
                const wb = XLSX.read(data, { type: 'array' });
                const sheet = wb.Sheets[wb.SheetNames[0]];
                importParsedData = XLSX.utils.sheet_to_json(sheet, { defval: '' });

                if (!importParsedData || importParsedData.length === 0) {
                    Swal.fire({ icon: 'error', title: 'ບໍ່ພົບຂໍ້ມູນໃນໄຟລ໌' });
                    importParsedData = null;
                    return;
                }

                document.getElementById('btnImportPreview').disabled = false;
                Swal.fire({ icon: 'success', title: `ອ່ານໄດ້ ${importParsedData.length} ແຖວ`, timer: 1500, showConfirmButton: false });
            } catch (err) {
                Swal.fire({ icon: 'error', title: 'ບໍ່ສາມາດອ່ານໄຟລ໌ໄດ້', text: err.message });
            }
        };
        reader.readAsArrayBuffer(file);
    }

    // Drag and drop for import dropzone
    const impDZ = document.getElementById('importDropzone');
    if (impDZ) {
        impDZ.addEventListener('dragover', e => { e.preventDefault(); impDZ.classList.add('dragover'); });
        impDZ.addEventListener('dragleave', e => { e.preventDefault(); impDZ.classList.remove('dragover'); });
        impDZ.addEventListener('drop', e => {
            e.preventDefault(); impDZ.classList.remove('dragover');
            if (e.dataTransfer.files.length > 0) {
                const dt = new DataTransfer();
                dt.items.add(e.dataTransfer.files[0]);
                document.getElementById('importFileInput').files = dt.files;
                handleImportFile(document.getElementById('importFileInput'));
            }
        });
    }

    function previewImport() {
        if (!importParsedData) return;

        const btn = document.getElementById('btnImportPreview');
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> ກຳລັງກວດສອບ...';

        const fd = new FormData();
        fd.append('action', 'import_products_preview');
        fd.append('search_field', document.getElementById('importSearchField').value);
        fd.append('import_data', JSON.stringify(importParsedData));

        fetch('make_product.php', { method: 'POST', body: fd })
            .then(r => r.json())
            .then(res => {
                btn.innerHTML = '<i class="fas fa-search"></i> Preview';
                if (!res.success) {
                    Swal.fire({ icon: 'error', title: 'ຜິດພາດ', text: res.message });
                    btn.disabled = false;
                    return;
                }

                // Switch to step 2
                document.getElementById('importStep1').style.display = 'none';
                document.getElementById('importStep2').style.display = 'block';
                btn.style.display = 'none';
                document.getElementById('btnImportExecute').style.display = '';

                // Stats
                document.getElementById('importStats').innerHTML = `
                    <div class="ei-stat-item found"><i class="fas fa-sync"></i> ອັບເດດ: ${res.found_count}</div>
                    <div class="ei-stat-item new-stat"><i class="fas fa-plus"></i> ເພີ່ມໃໝ່: ${res.new_count}</div>
                    ${res.error_count > 0 ? `<div class="ei-stat-item err-stat"><i class="fas fa-times"></i> ຜິດພາດ: ${res.error_count}</div>` : ''}
                `;

                // Missing refs
                const mr = res.missing_refs;
                let mrHtml = '';
                if (mr.groups.length || mr.brands.length || mr.suppliers.length) {
                    mrHtml += '<div class="ei-missing-list"><h4><i class="fas fa-exclamation-triangle"></i> ພົບຊື່ທີ່ບໍ່ມີໃນລະບົບ:</h4><ul>';
                    mr.groups.forEach(n => mrHtml += `<li>ກຸ່ມ: <strong>${escHtml(n)}</strong></li>`);
                    mr.brands.forEach(n => mrHtml += `<li>ຍີ່ຫໍ້: <strong>${escHtml(n)}</strong></li>`);
                    mr.suppliers.forEach(n => mrHtml += `<li>ຜູ້ສະໜອງ: <strong>${escHtml(n)}</strong></li>`);
                    mrHtml += '</ul></div>';
                    mrHtml += '<label class="ei-toggle"><input type="checkbox" id="importAutoCreate" checked> <span>ສ້າງອັດຕະໂນມັດ (Auto-create) ລາຍການທີ່ບໍ່ພົບ</span></label>';
                }
                document.getElementById('importMissingRefs').innerHTML = mrHtml;

                // Preview table
                const allItems = [...(res.found || []), ...(res.new || []), ...(res.errors || [])];
                if (allItems.length > 0) {
                    const cols = Object.keys(allItems[0].data || {});
                    let tHtml = '<table class="ei-preview-table"><thead><tr><th>#</th><th>ສະຖານະ</th>';
                    cols.forEach(c => tHtml += `<th>${escHtml(c)}</th>`);
                    tHtml += '</tr></thead><tbody>';

                    const maxShow = Math.min(allItems.length, 50);
                    for (let i = 0; i < maxShow; i++) {
                        const item = allItems[i];
                        const st = item.status || 'error';
                        const badge = st === 'update' ? '<span class="ei-badge update">ອັບເດດ</span>'
                            : st === 'new' ? '<span class="ei-badge new">ເພີ່ມໃໝ່</span>'
                                : '<span class="ei-badge error">❌ ' + escHtml((item.errors || []).join(', ')) + '</span>';
                        tHtml += `<tr><td>${item.line}</td><td>${badge}</td>`;
                        cols.forEach(c => tHtml += `<td>${escHtml(item.data[c] ?? '')}</td>`);
                        tHtml += '</tr>';
                    }
                    if (allItems.length > 50) tHtml += `<tr><td colspan="${cols.length + 2}" style="text-align:center;color:var(--text-secondary)">... ແລະ ອີກ ${allItems.length - 50} ແຖວ</td></tr>`;
                    tHtml += '</tbody></table>';
                    document.getElementById('importPreviewWrap').innerHTML = tHtml;
                }
            })
            .catch(err => {
                btn.innerHTML = '<i class="fas fa-search"></i> Preview';
                btn.disabled = false;
                Swal.fire({ icon: 'error', title: 'Error', text: err.message });
            });
    }

    function executeImport() {
        const btn = document.getElementById('btnImportExecute');
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> ກຳລັງ Import...';

        const fd = new FormData();
        fd.append('action', 'import_products_execute');
        const acEl = document.getElementById('importAutoCreate');
        fd.append('auto_create', acEl && acEl.checked ? '1' : '0');

        fetch('make_product.php', { method: 'POST', body: fd })
            .then(r => r.json())
            .then(res => {
                if (res.success) {
                    document.getElementById('importStep2').style.display = 'none';
                    document.getElementById('importStep3').style.display = 'block';
                    document.getElementById('btnImportExecute').style.display = 'none';
                    document.getElementById('importResultTitle').textContent = 'Import ສຳເລັດ!';
                    document.getElementById('importResultMsg').textContent = res.message;

                    // Reload data & dropdowns cache
                    lookupCache = null;
                    lookupPromise = null;
                    tomSelectReady = false;
                    loadProducts(1);
                } else {
                    Swal.fire({ icon: 'error', title: 'Import ລົ້ມເຫຼວ', text: res.message });
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-upload"></i> ດຳເນີນການ Import';
                }
            })
            .catch(err => {
                Swal.fire({ icon: 'error', title: 'Error', text: err.message });
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-upload"></i> ດຳເນີນການ Import';
            });
    }
</script>

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