<?php
/**
 * =============================================================
 * ระบบ Import CSV/XLSX เพื่อ Bulk Update ข้อมูลสินค้าแบบ Dynamic
 * =============================================================
 * - รองรับไฟล์ CSV, XLSX, XLS (ใช้ SheetJS แปลงฝั่ง Client)
 * - รองรับการเลือก Field ค้นหา (product_code, barcode, id)
 * - รองรับการเลือก Field อัปเดตหลายรายการ (Multi-select)
 * - ใช้ CASE WHEN Bulk Update (ไม่ Loop ทีละแถว)
 * - ใช้ PDO Prepared Statements + Transaction
 * - อัปเดตเฉพาะ deleted_at IS NULL
 * - จำกัดไฟล์ไม่เกิน 5MB
 * =============================================================
 */

// ===== AJAX Handler: ประมวลผล CSV Upload =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['csv_action'])) {
    if (session_status() === PHP_SESSION_NONE)
        session_start();
    require_once dirname(__DIR__, 2) . '/include/con_data.php';

    // ตรวจสอบสิทธิ์ (Authentication Check)
    if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'manager') {
        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;
    }

    header('Content-Type: application/json');
    $username = $_SESSION['username'] ?? 'System';

    // ---------- ACTION: Preview (รับ JSON data จาก Client - รองรับ CSV/XLSX) ----------
    if ($_POST['csv_action'] === 'preview') {
        try {
            // รับค่า Field ที่ผู้ใช้เลือก
            $searchField = $_POST['search_field'] ?? '';
            $updateFieldsJson = $_POST['update_fields'] ?? '[]';
            $updateFields = json_decode($updateFieldsJson, true);
            if (!is_array($updateFields))
                $updateFields = [];

            // รับข้อมูลที่ Parse จาก Client (SheetJS)
            $parsedDataJson = $_POST['parsed_data'] ?? '[]';
            $parsedData = json_decode($parsedDataJson, true);
            if (!is_array($parsedData)) {
                throw new Exception('ข้อมูลไม่ถูกต้อง');
            }

            // ตรวจสอบ Field ค้นหาที่อนุญาต
            $allowedSearch = ['product_code', 'barcode', 'id'];
            if (!in_array($searchField, $allowedSearch)) {
                throw new Exception('Field ค้นหาไม่ถูกต้อง');
            }

            // ตรวจสอบ Field อัปเดตที่อนุญาต
            $allowedUpdate = ['price_1', 'price_2', 'brand', 'supplier', 'product_group'];
            $updateFields = array_intersect($updateFields, $allowedUpdate);
            if (empty($updateFields)) {
                throw new Exception('ກະລຸນາເລືອກ Field ທີ່ຕ້ອງການອັບເດດ');
            }

            // ===== Validate ข้อมูลแต่ละแถว =====
            $expectedFields = array_merge([$searchField], array_values($updateFields));
            $rows = [];
            $errors = [];

            foreach ($parsedData as $lineIdx => $dataRow) {
                $lineNum = $lineIdx + 2; // +2 เพราะ header=1, data เริ่มที่ 2

                $row = [];
                foreach ($expectedFields as $i => $field) {
                    $value = trim((string) ($dataRow[$field] ?? ''));

                    // ตรวจค่าว่างของ field ค้นหา
                    if ($i === 0 && $value === '') {
                        $errors[] = "ແຖວທີ $lineNum: ຄ່າ $searchField ເປັນຄ່າວ່າງ";
                        continue 2;
                    }

                    // ตรวจ price ต้องเป็นตัวเลข
                    if (in_array($field, ['price_1', 'price_2']) && $value !== '') {
                        if (!is_numeric($value) || $value < 0) {
                            $errors[] = "ແຖວທີ $lineNum: $field ຕ້ອງເປັນຕົວເລກ (ພົບ '$value')";
                            continue 2;
                        }
                    }

                    // ตรวจ id ต้องเป็นจำนวนเต็ม
                    if ($field === 'id' && !ctype_digit($value)) {
                        $errors[] = "ແຖວທີ $lineNum: id ຕ້ອງເປັນຕົວເລກຈຳນວນເຕັມ (ພົບ '$value')";
                        continue 2;
                    }

                    $row[$field] = $value;
                }
                $rows[] = $row;
            }

            if (empty($rows) && empty($errors)) {
                throw new Exception('ບໍ່ພົບຂໍ້ມູນໃນໄຟລ໌');
            }

            // ===== ตรวจสอบกับ Database ว่ามีสินค้าหรือไม่ =====
            $foundRows = [];
            $notFoundRows = [];

            if (!empty($rows)) {
                $searchValues = array_column($rows, $searchField);
                $placeholders = implode(',', array_fill(0, count($searchValues), '?'));

                $sql = "SELECT $searchField FROM products WHERE $searchField IN ($placeholders) AND deleted_at IS NULL AND shop_id = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute(array_merge($searchValues, [$shop_id]));
                $existingKeys = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);

                foreach ($rows as $row) {
                    $key = $row[$searchField];
                    $found = false;
                    foreach ($existingKeys as $existKey) {
                        if (strtolower((string) $key) === strtolower((string) $existKey)) {
                            $found = true;
                            break;
                        }
                    }
                    if ($found) {
                        $foundRows[] = $row;
                    } else {
                        $notFoundRows[] = $row;
                    }
                }
            }

            // ===== บันทึกใน Session =====
            $_SESSION['csv_import'] = [
                'search_field' => $searchField,
                'update_fields' => $updateFields,
                'found_rows' => $foundRows,
                'not_found_rows' => $notFoundRows,
                'timestamp' => time()
            ];

            echo json_encode([
                'success' => true,
                'search_field' => $searchField,
                'update_fields' => array_values($updateFields),
                'found' => $foundRows,
                'not_found' => $notFoundRows,
                'errors' => $errors,
                'total_rows' => count($rows),
                'found_count' => count($foundRows),
                'not_found_count' => count($notFoundRows)
            ]);

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

    // ---------- ACTION: Execute Bulk Update ----------
    if ($_POST['csv_action'] === 'execute') {
        try {
            // ตรวจสอบ Session data
            if (!isset($_SESSION['csv_import']) || empty($_SESSION['csv_import']['found_rows'])) {
                throw new Exception('ບໍ່ມີຂໍ້ມູນສຳລັບອັບເດດ. ກະລຸນາ Upload CSV ໃໝ່');
            }

            $importData = $_SESSION['csv_import'];

            // ตรวจ Session timeout (10 นาที)
            if (time() - $importData['timestamp'] > 600) {
                unset($_SESSION['csv_import']);
                throw new Exception('Session ໝົດອາຍຸ. ກະລຸນາ Upload CSV ໃໝ່');
            }

            $searchField = $importData['search_field'];
            $updateFields = $importData['update_fields'];
            $foundRows = $importData['found_rows'];

            if (empty($foundRows)) {
                throw new Exception('ບໍ່ມີລາຍການທີ່ຕ້ອງອັບເດດ');
            }

            // ===== สร้าง SQL แบบ CASE WHEN Bulk Update =====
            $pdo->beginTransaction();

            // ดึงค่า search key ทั้งหมด
            $searchValues = array_column($foundRows, $searchField);
            $placeholdersIn = implode(',', array_fill(0, count($searchValues), '?'));

            // สร้าง CASE WHEN สำหรับแต่ละ field ที่ต้องอัปเดต
            $setClauses = [];
            $params = [];

            foreach ($updateFields as $field) {
                $caseParts = [];
                foreach ($foundRows as $idx => $row) {
                    $searchParamName = ":search_{$field}_{$idx}";
                    $valueParamName = ":val_{$field}_{$idx}";
                    $caseParts[] = "WHEN $searchField = $searchParamName THEN $valueParamName";
                    $params[$searchParamName] = $row[$searchField];
                    $params[$valueParamName] = $row[$field];
                }
                $setClauses[] = "$field = CASE " . implode(' ', $caseParts) . " ELSE $field END";
            }

            // เพิ่ม updated_at และ updated_by อัตโนมัติ
            $setClauses[] = "updated_at = NOW()";
            $setClauses[] = "updated_by = :updated_by";
            $params[':updated_by'] = $username;

            // สร้าง WHERE clause ด้วย IN
            $whereParams = [];
            foreach ($searchValues as $idx => $val) {
                $pName = ":where_{$idx}";
                $whereParams[] = $pName;
                $params[$pName] = $val;
            }

            $sql = "UPDATE products SET " . implode(', ', $setClauses)
                . " WHERE $searchField IN (" . implode(',', $whereParams) . ")"
                . " AND deleted_at IS NULL AND shop_id = :shop_id";
            $params[':shop_id'] = $shop_id;

            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $affectedRows = $stmt->rowCount();

            $pdo->commit();

            // ล้าง Session data หลังใช้งาน
            unset($_SESSION['csv_import']);

            echo json_encode([
                'success' => true,
                'message' => "ອັບເດດສຳເລັດ $affectedRows ລາຍການ",
                'affected_rows' => $affectedRows,
                'total_submitted' => count($foundRows)
            ]);

        } catch (Exception $e) {
            // Rollback ถ้ามี error
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        exit;
    }
}

// ===== Regular Page Load =====
$page_title = 'Import CSV/XLSX - ອັບເດດສິນຄ້າ';
// Spoof PHP_SELF to highlight "Products" menu in sidebar
$_SERVER['PHP_SELF'] = '/manager/make_data/make_product.php';
require_once '../includes/header.php';
?>

<style>
    /* ===== CSV Import Page Styles ===== */
    .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;
    }

    .btn-back {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 10px 18px;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        color: var(--text-primary);
        text-decoration: none;
        font-family: inherit;
        font-size: 15px;
        transition: all 0.3s;
    }

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

    /* Wizard Steps Indicator */
    .wizard-steps {
        display: flex;
        justify-content: center;
        gap: 0;
        margin-bottom: 30px;
        position: relative;
    }

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

    .wizard-step::before {
        content: '';
        position: absolute;
        top: 20px;
        left: -50%;
        right: 50%;
        height: 3px;
        background: var(--border-color);
        z-index: -1;
    }

    /* Fix Z-Index Stacking: Previous steps must be higher than next steps 
       so the "left" connector of the next step goes BEHIND the previous step's circle */
    .wizard-step:nth-child(1) {
        z-index: 3;
    }

    .wizard-step:nth-child(2) {
        z-index: 2;
    }

    .wizard-step:nth-child(3) {
        z-index: 1;
    }

    .wizard-step:first-child::before {
        display: none;
    }

    .wizard-step.active::before,
    .wizard-step.completed::before {
        background: var(--accent);
        transition: background 0.4s ease;
    }

    .step-circle {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        font-size: 16px;
        background: var(--bg-primary);
        /* Solid background to hide line */
        border: 3px solid var(--border-color);
        color: var(--text-secondary);
        transition: all 0.3s;
        margin-bottom: 8px;
        position: relative;
        /* Stacking context */
        z-index: 2;
        /* Higher than line */
    }

    .wizard-step.active .step-circle {
        border-color: var(--accent);
        background: var(--accent);
        color: #fff;
        box-shadow: 0 0 20px rgba(193, 153, 42, 0.3);
    }

    .wizard-step.completed .step-circle {
        border-color: var(--success);
        background: var(--success);
        color: #fff;
    }

    .step-label {
        font-size: 13px;
        color: var(--text-secondary);
        font-weight: 500;
        text-align: center;
    }

    .wizard-step.active .step-label {
        color: var(--accent);
        font-weight: 600;
    }

    .wizard-step.completed .step-label {
        color: var(--success);
    }

    /* Import Card */
    .import-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 15px;
        overflow: hidden;
    }

    .import-card-header {
        padding: 18px 24px;
        border-bottom: 1px solid var(--border-color);
        display: flex;
        align-items: center;
        gap: 10px;
    }

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

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

    .import-card-body {
        padding: 24px;
    }

    /* Form Elements */
    .form-group {
        margin-bottom: 20px;
    }

    .form-group label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        font-size: 14px;
        color: var(--text-primary);
    }

    .form-group label i {
        color: var(--accent);
        margin-right: 6px;
    }

    .form-control {
        width: 100%;
        padding: 10px 14px;
        background: var(--bg-secondary);
        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, 0.15);
    }

    /* Checkbox Grid */
    .checkbox-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
        gap: 10px;
    }

    .checkbox-item {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px 14px;
        background: var(--bg-secondary);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.2s;
        user-select: none;
    }

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

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

    .checkbox-item.checked {
        border-color: var(--accent);
        background: rgba(193, 153, 42, 0.1);
    }

    .checkbox-item span {
        font-size: 14px;
        font-family: monospace;
        color: var(--text-primary);
    }

    /* File Upload Zone */
    .upload-zone {
        border: 2px dashed var(--border-color);
        border-radius: 12px;
        padding: 40px 20px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
        background: var(--bg-secondary);
    }

    .upload-zone:hover,
    .upload-zone.dragover {
        border-color: var(--accent);
        background: rgba(193, 153, 42, 0.05);
    }

    .upload-zone i {
        font-size: 40px;
        color: var(--accent);
        margin-bottom: 12px;
        display: block;
    }

    .upload-zone p {
        margin: 5px 0;
        color: var(--text-secondary);
        font-size: 14px;
    }

    .upload-zone .file-name {
        color: var(--accent);
        font-weight: 600;
        margin-top: 10px;
    }

    /* CSV Info Box */
    .csv-info {
        background: rgba(193, 153, 42, 0.08);
        border: 1px solid rgba(193, 153, 42, 0.2);
        border-radius: 10px;
        padding: 16px 20px;
        margin-top: 20px;
    }

    .csv-info h4 {
        margin: 0 0 8px;
        font-size: 14px;
        color: var(--accent);
    }

    .csv-info code {
        display: block;
        background: var(--bg-secondary);
        border: 1px solid var(--border-color);
        border-radius: 6px;
        padding: 10px 14px;
        font-family: 'Courier New', monospace;
        font-size: 13px;
        color: var(--text-primary);
        white-space: pre-line;
        margin-top: 6px;
    }

    /* Preview Table */
    .preview-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 10px;
    }

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

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

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

    /* Status Badges */
    .badge {
        display: inline-flex;
        align-items: center;
        gap: 5px;
        padding: 4px 10px;
        border-radius: 6px;
        font-size: 12px;
        font-weight: 600;
    }

    .badge-success {
        background: rgba(40, 167, 69, 0.15);
        color: #28a745;
    }

    .badge-danger {
        background: rgba(220, 53, 69, 0.15);
        color: #dc3545;
    }

    .badge-warning {
        background: rgba(255, 193, 7, 0.15);
        color: #ffc107;
    }

    /* Stats Row */
    .stats-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 15px;
        margin-bottom: 20px;
    }

    .stat-box {
        background: var(--bg-secondary);
        border: 1px solid var(--border-color);
        border-radius: 10px;
        padding: 16px;
        text-align: center;
    }

    .stat-box .stat-number {
        font-size: 28px;
        font-weight: 700;
        color: var(--accent);
    }

    .stat-box .stat-label {
        font-size: 13px;
        color: var(--text-secondary);
        margin-top: 4px;
    }

    .stat-box.success .stat-number {
        color: var(--success);
    }

    .stat-box.danger .stat-number {
        color: var(--danger);
    }

    /* Button Group */
    .btn-group {
        display: flex;
        gap: 10px;
        margin-top: 20px;
        flex-wrap: wrap;
    }

    .btn-execute {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 12px 24px;
        background: var(--success);
        color: #fff;
        border: none;
        border-radius: 8px;
        font-family: inherit;
        font-size: 15px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
    }

    .btn-execute:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 20px rgba(40, 167, 69, 0.3);
    }

    .btn-execute:disabled {
        opacity: 0.5;
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
    }

    .btn-reset {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 12px 24px;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        color: var(--text-primary);
        font-family: inherit;
        font-size: 15px;
        cursor: pointer;
        transition: all 0.3s;
    }

    .btn-reset:hover {
        border-color: var(--danger);
        color: var(--danger);
    }

    /* Error List */
    .error-list {
        background: rgba(220, 53, 69, 0.08);
        border: 1px solid rgba(220, 53, 69, 0.2);
        border-radius: 10px;
        padding: 16px 20px;
        margin-top: 15px;
        max-height: 200px;
        overflow-y: auto;
    }

    .error-list h4 {
        margin: 0 0 10px;
        color: var(--danger);
        font-size: 14px;
    }

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

    .error-list li {
        font-size: 13px;
        color: var(--text-secondary);
        margin-bottom: 4px;
    }

    /* Result Animation */
    .result-icon {
        text-align: center;
        margin: 20px 0;
    }

    .result-icon i {
        font-size: 60px;
        color: var(--success);
        animation: bounceIn 0.5s ease;
    }

    .result-icon.error i {
        color: var(--danger);
    }

    @keyframes bounceIn {
        0% {
            transform: scale(0);
            opacity: 0;
        }

        50% {
            transform: scale(1.2);
        }

        100% {
            transform: scale(1);
            opacity: 1;
        }
    }

    /* Hidden step panels */
    .step-panel {
        display: none;
    }

    .step-panel.active {
        display: block;
        animation: fadeInUp 0.3s ease;
    }

    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(15px);
        }

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

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

    .loading-overlay.show {
        display: flex;
    }

    .loading-box {
        background: var(--bg-primary);
        border: 1px solid var(--border-color);
        border-radius: 15px;
        padding: 30px 40px;
        text-align: center;
    }

    .loading-box i {
        font-size: 36px;
        color: var(--accent);
        margin-bottom: 12px;
        display: block;
    }

    .loading-box p {
        color: var(--text-primary);
        font-size: 16px;
        margin: 0;
    }

    /* Table scroll wrapper */
    .table-scroll {
        overflow-x: auto;
        border: 1px solid var(--border-color);
        border-radius: 10px;
    }

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

        .stats-row {
            grid-template-columns: 1fr 1fr;
        }

        .wizard-steps {
            gap: 0;
        }

        .step-label {
            font-size: 11px;
        }
    }
</style>

<!-- Loading Overlay -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-box">
        <i class="fas fa-spinner fa-spin"></i>
        <p>ກຳລັງປະມວນຜົນ...</p>
    </div>
</div>

<!-- Page Header -->
<div class="page-header">
    <h2><i class="fas fa-file-csv" style="color:var(--accent)"></i> Import CSV/XLSX ອັບເດດສິນຄ້າ</h2>
    <a href="make_product.php" class="btn-back">
        <i class="fas fa-arrow-left"></i> ກັບໄປໜ້າສິນຄ້າ
    </a>
</div>

<!-- Wizard Steps Indicator -->
<div class="wizard-steps">
    <div class="wizard-step active" id="wizardStep1">
        <div class="step-circle">1</div>
        <div class="step-label">ອັບໂຫຼດໄຟລ໌</div>
    </div>
    <div class="wizard-step" id="wizardStep2">
        <div class="step-circle">2</div>
        <div class="step-label">ກວດສອບ & Preview</div>
    </div>
    <div class="wizard-step" id="wizardStep3">
        <div class="step-circle">3</div>
        <div class="step-label">ຜົນລັບ</div>
    </div>
</div>

<!-- ===== STEP 1: Upload Form ===== -->
<div class="step-panel active" id="step1Panel">
    <div class="import-card">
        <div class="import-card-header">
            <h3><i class="fas fa-upload"></i> ຕັ້ງຄ່າ ແລະ ອັບໂຫຼດໄຟລ໌</h3>
        </div>
        <div class="import-card-body">
            <form id="csvForm" enctype="multipart/form-data">
                <!-- เลือก Field ค้นหา -->
                <div class="form-group">
                    <label><i class="fas fa-search"></i> ເລືອກ Field ທີ່ໃຊ້ຄົ້ນຫາ</label>
                    <select class="form-control" id="searchField" name="search_field" style="max-width:350px;">
                        <option value="product_code">product_code (ລະຫັດສິນຄ້າ)</option>
                        <option value="barcode">barcode (ບາໂຄດ)</option>
                        <option value="id">id (ລະຫັດ ID)</option>
                    </select>
                </div>

                <!-- เลือก Field อัปเดต (Multi-select) -->
                <div class="form-group">
                    <label><i class="fas fa-edit"></i> ເລືອກ Field ທີ່ຕ້ອງການອັບເດດ</label>
                    <div class="checkbox-grid">
                        <label class="checkbox-item" onclick="toggleCheck(this)">
                            <input type="checkbox" name="update_fields[]" value="price_1">
                            <span>price_1</span>
                        </label>
                        <label class="checkbox-item" onclick="toggleCheck(this)">
                            <input type="checkbox" name="update_fields[]" value="price_2">
                            <span>price_2</span>
                        </label>
                        <label class="checkbox-item" onclick="toggleCheck(this)">
                            <input type="checkbox" name="update_fields[]" value="brand">
                            <span>brand</span>
                        </label>
                        <label class="checkbox-item" onclick="toggleCheck(this)">
                            <input type="checkbox" name="update_fields[]" value="supplier">
                            <span>supplier</span>
                        </label>
                        <label class="checkbox-item" onclick="toggleCheck(this)">
                            <input type="checkbox" name="update_fields[]" value="product_group">
                            <span>product_group</span>
                        </label>
                    </div>
                </div>

                <!-- File Upload Zone -->
                <div class="form-group">
                    <label><i class="fas fa-file-csv"></i> ເລືອກໄຟລ໌ CSV / XLSX (ສູງສຸດ 5MB)</label>
                    <div class="upload-zone" id="uploadZone" onclick="document.getElementById('csvFile').click()">
                        <i class="fas fa-cloud-upload-alt"></i>
                        <p>ກົດເພື່ອເລືອກໄຟລ໌ ຫຼື ລາກໄຟລ໌ມາວາງ</p>
                        <p style="font-size:12px;">ຮອງຮັບໄຟລ໌ .csv, .xlsx, .xls</p>
                        <div class="file-name" id="fileName"></div>
                    </div>
                    <input type="file" id="csvFile" name="csv_file" accept=".csv,.xlsx,.xls" style="display:none"
                        onchange="onFileSelected(this)">
                </div>

                <!-- CSV/XLSX Format Info -->
                <div class="csv-info" id="csvInfo">
                    <h4><i class="fas fa-info-circle"></i> ຮູບແບບ CSV/XLSX ທີ່ຕ້ອງການ</h4>
                    <p style="font-size:13px;color:var(--text-secondary);margin:0 0 6px;">ຄໍລັມແຮກຕ້ອງເປັນ Field ຄົ້ນຫາ,
                        ຕາມດ້ວຍ Field ອັບເດດ (ໃຊ້ໄດ້ທັງ CSV ແລະ Excel XLSX/XLS)</p>
                    <code id="csvExample">product_code,price_1
SKU001,150000
SKU002,175000</code>
                </div>

                <!-- Submit Button -->
                <div class="btn-group" style="justify-content:flex-end;">
                    <button type="submit" class="btn btn-primary" id="btnPreview" style="padding:12px 28px;">
                        <i class="fas fa-eye"></i> Preview ຂໍ້ມູນ
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ===== STEP 2: Preview ===== -->
<div class="step-panel" id="step2Panel">
    <div class="import-card">
        <div class="import-card-header">
            <h3><i class="fas fa-table"></i> Preview ຂໍ້ມູນກ່ອນອັບເດດ</h3>
        </div>
        <div class="import-card-body">
            <!-- Stats -->
            <div class="stats-row" id="previewStats"></div>

            <!-- Error messages (if any) -->
            <div id="previewErrors" style="display:none;"></div>

            <!-- Found items table -->
            <h4 style="margin:15px 0 10px;display:flex;align-items:center;gap:8px;">
                <i class="fas fa-check-circle" style="color:var(--success)"></i>
                ລາຍການທີ່ພົບໃນລະບົບ (<span id="foundCount">0</span>)
            </h4>
            <div class="table-scroll" id="foundTableWrap" style="display:none;">
                <table class="preview-table" id="foundTable">
                    <thead id="foundTableHead"></thead>
                    <tbody id="foundTableBody"></tbody>
                </table>
            </div>
            <p id="foundEmpty" style="color:var(--text-secondary);font-size:14px;display:none;">
                <i class="fas fa-info-circle"></i> ບໍ່ພົບລາຍການ
            </p>

            <!-- Not Found items table -->
            <h4 style="margin:25px 0 10px;display:flex;align-items:center;gap:8px;">
                <i class="fas fa-times-circle" style="color:var(--danger)"></i>
                ລາຍການທີ່ບໍ່ພົບໃນລະບົບ (<span id="notFoundCount">0</span>)
            </h4>
            <div class="table-scroll" id="notFoundTableWrap" style="display:none;">
                <table class="preview-table" id="notFoundTable">
                    <thead id="notFoundTableHead"></thead>
                    <tbody id="notFoundTableBody"></tbody>
                </table>
            </div>
            <p id="notFoundEmpty" style="color:var(--text-secondary);font-size:14px;display:none;">
                <i class="fas fa-check-circle" style="color:var(--success)"></i> ທຸກລາຍການພົບໃນລະບົບ
            </p>

            <!-- Action Buttons -->
            <div class="btn-group" style="justify-content:space-between;">
                <button class="btn-reset" onclick="goToStep(1)">
                    <i class="fas fa-arrow-left"></i> ກັບໄປແກ້ໄຂ
                </button>
                <button class="btn-execute" id="btnExecute" onclick="executeUpdate()">
                    <i class="fas fa-database"></i> ຢືນຢັນອັບເດດ
                </button>
            </div>
        </div>
    </div>
</div>

<!-- ===== STEP 3: Results ===== -->
<div class="step-panel" id="step3Panel">
    <div class="import-card">
        <div class="import-card-header">
            <h3><i class="fas fa-chart-bar"></i> ຜົນລັບການອັບເດດ</h3>
        </div>
        <div class="import-card-body" id="resultContent">
            <!-- จะถูกเติมด้วย JavaScript -->
        </div>
    </div>
</div>

<!-- SheetJS Library สำหรับอ่านไฟล์ XLSX/XLS ฝั่ง Client -->
<script src="https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.min.js"></script>
<script>
    // ===== Global State =====
    let previewData = null;

    // ===== Wizard Navigation =====
    function goToStep(step) {
        // ซ่อนทุก panel
        document.querySelectorAll('.step-panel').forEach(p => p.classList.remove('active'));
        document.querySelectorAll('.wizard-step').forEach(s => {
            s.classList.remove('active', 'completed');
        });

        // แสดง panel ที่เลือก
        document.getElementById(`step${step}Panel`).classList.add('active');

        // อัปเดต wizard indicator
        for (let i = 1; i <= 3; i++) {
            const ws = document.getElementById(`wizardStep${i}`);
            if (i < step) ws.classList.add('completed');
            else if (i === step) ws.classList.add('active');
        }
    }

    // ===== Checkbox Toggle Visual =====
    function toggleCheck(el) {
        setTimeout(() => {
            const cb = el.querySelector('input[type="checkbox"]');
            if (cb.checked) {
                el.classList.add('checked');
            } else {
                el.classList.remove('checked');
            }
            updateCsvExample();
        }, 10);
    }

    // ===== อัปเดตตัวอย่าง CSV ตามที่เลือก =====
    function updateCsvExample() {
        const searchField = document.getElementById('searchField').value;
        const updateFields = [];
        document.querySelectorAll('input[name="update_fields[]"]:checked').forEach(cb => {
            updateFields.push(cb.value);
        });

        if (updateFields.length === 0) {
            document.getElementById('csvExample').textContent = searchField + '\nvalue1\nvalue2';
            return;
        }

        const header = [searchField, ...updateFields].join(',');
        let example1 = '', example2 = '';

        // สร้างตัวอย่างข้อมูล
        if (searchField === 'barcode') {
            example1 = '8851234567890'; example2 = '8851234567891';
        } else if (searchField === 'product_code') {
            example1 = 'SKU001'; example2 = 'SKU002';
        } else {
            example1 = '1'; example2 = '2';
        }

        const vals1 = updateFields.map(f => {
            if (f.includes('price')) return '150000';
            if (f === 'brand') return 'BR001';
            if (f === 'supplier') return 'SU001';
            if (f === 'product_group') return 'GP001';
            return 'value';
        });
        const vals2 = updateFields.map(f => {
            if (f.includes('price')) return '175000';
            if (f === 'brand') return 'BR002';
            if (f === 'supplier') return 'SU002';
            if (f === 'product_group') return 'GP002';
            return 'value';
        });

        document.getElementById('csvExample').textContent =
            header + '\n' + example1 + ',' + vals1.join(',') + '\n' + example2 + ',' + vals2.join(',');
    }

    // Event: เมื่อเปลี่ยน search field
    document.getElementById('searchField').addEventListener('change', updateCsvExample);

    // ===== File Upload Handling =====
    function onFileSelected(input) {
        const file = input.files[0];
        const nameEl = document.getElementById('fileName');
        const zone = document.getElementById('uploadZone');

        if (file) {
            // ตรวจขนาด client-side (5MB)
            if (file.size > 5 * 1024 * 1024) {
                Swal.fire({ icon: 'error', title: 'ໄຟລ໌ໃຫຍ່ເກີນ', text: 'ຂະໜາດໄຟລ໌ຕ້ອງບໍ່ເກີນ 5MB' });
                input.value = '';
                nameEl.textContent = '';
                return;
            }
            // ตรวจนามสกุลไฟล์
            const ext = file.name.split('.').pop().toLowerCase();
            if (!['csv', 'xlsx', 'xls'].includes(ext)) {
                Swal.fire({ icon: 'error', title: 'ໄຟລ໌ບໍ່ຖືກຕ້ອງ', text: 'ຮອງຮັບສະເພາະ .csv, .xlsx, .xls' });
                input.value = '';
                nameEl.textContent = '';
                return;
            }
            const icon = ext === 'csv' ? '📄' : '📊';
            nameEl.textContent = icon + ' ' + file.name + ' (' + (file.size / 1024).toFixed(1) + ' KB)';
            zone.style.borderColor = 'var(--accent)';
        } else {
            nameEl.textContent = '';
            zone.style.borderColor = '';
        }
    }

    // Drag & Drop
    const uploadZone = document.getElementById('uploadZone');
    uploadZone.addEventListener('dragover', (e) => { e.preventDefault(); uploadZone.classList.add('dragover'); });
    uploadZone.addEventListener('dragleave', () => { uploadZone.classList.remove('dragover'); });
    uploadZone.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadZone.classList.remove('dragover');
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            document.getElementById('csvFile').files = files;
            onFileSelected(document.getElementById('csvFile'));
        }
    });

    /**
     * ===== อ่านไฟล์ CSV/XLSX ด้วย SheetJS =====
     * แปลงไฟล์ทุกประเภทเป็น Array of Objects
     * คืนค่า { header: [...], rows: [{...}, ...] }
     */
    function parseFileToJSON(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = function (e) {
                try {
                    const data = new Uint8Array(e.target.result);
                    // SheetJS อ่านได้ทั้ง CSV, XLSX, XLS
                    const workbook = XLSX.read(data, { type: 'array', raw: false });
                    // ใช้ Sheet แรก
                    const sheetName = workbook.SheetNames[0];
                    const sheet = workbook.Sheets[sheetName];
                    // แปลงเป็น JSON (header = row แรก)
                    const jsonData = XLSX.utils.sheet_to_json(sheet, { defval: '' });

                    if (!jsonData || jsonData.length === 0) {
                        reject('ໄຟລ໌ວ່າງເປົ່າ ຫຼື ບໍ່ມີຂໍ້ມູນ');
                        return;
                    }

                    // ดึง header จาก key ของ row แรก
                    const header = Object.keys(jsonData[0]);
                    resolve({ header, rows: jsonData });
                } catch (err) {
                    reject('ບໍ່ສາມາດອ່ານໄຟລ໌ໄດ້: ' + err.message);
                }
            };
            reader.onerror = () => reject('ເກີດຂໍ້ຜິດພາດຂະນະອ່ານໄຟລ໌');
            reader.readAsArrayBuffer(file);
        });
    }

    // ===== Form Submit: Preview =====
    document.getElementById('csvForm').addEventListener('submit', async function (e) {
        e.preventDefault();

        // Validate: ต้องเลือก field อัปเดตอย่างน้อย 1 รายการ
        const checked = document.querySelectorAll('input[name="update_fields[]"]:checked');
        if (checked.length === 0) {
            Swal.fire({ icon: 'warning', title: 'ກະລຸນາເລືອກ', text: 'ເລືອກ Field ທີ່ຕ້ອງການອັບເດດຢ່າງໜ້ອຍ 1 ລາຍການ' });
            return;
        }

        // Validate: ต้องเลือกไฟล์
        const fileInput = document.getElementById('csvFile');
        if (!fileInput.files || fileInput.files.length === 0) {
            Swal.fire({ icon: 'warning', title: 'ກະລຸນາເລືອກໄຟລ໌', text: 'ກະລຸນາເລືອກໄຟລ໌ CSV ຫຼື XLSX' });
            return;
        }

        const file = fileInput.files[0];
        const searchField = document.getElementById('searchField').value;
        const updateFields = Array.from(checked).map(cb => cb.value);
        const expectedHeader = [searchField, ...updateFields];

        showLoading(true);

        try {
            // ===== อ่านไฟล์ด้วย SheetJS (รองรับ CSV + XLSX + XLS) =====
            const parsed = await parseFileToJSON(file);

            // ===== ตรวจสอบ Header =====
            const fileHeader = parsed.header.map(h => h.trim().toLowerCase());
            for (let i = 0; i < expectedHeader.length; i++) {
                if (i >= fileHeader.length || fileHeader[i] !== expectedHeader[i].toLowerCase()) {
                    showLoading(false);
                    const found = i < fileHeader.length ? parsed.header[i] : '(ບໍ່ມີ)';
                    Swal.fire({
                        icon: 'error', title: 'Header ບໍ່ຖືກຕ້ອງ',
                        text: `ຄໍລັມທີ ${i + 1} ຄວນເປັນ "${expectedHeader[i]}" ແຕ່ພົບ "${found}"`
                    });
                    return;
                }
            }

            // ===== แปลง rows ให้ใช้ expected field names =====
            const originalHeaders = parsed.header;
            const normalizedRows = parsed.rows.map(row => {
                const obj = {};
                expectedHeader.forEach((field, i) => {
                    obj[field] = String(row[originalHeaders[i]] ?? '').trim();
                });
                return obj;
            }).filter(row => {
                // กรองแถวว่าง
                return Object.values(row).some(v => v !== '');
            });

            // ===== ส่ง JSON ไปยัง Server =====
            const formData = new FormData();
            formData.append('csv_action', 'preview');
            formData.append('search_field', searchField);
            formData.append('update_fields', JSON.stringify(updateFields));
            formData.append('parsed_data', JSON.stringify(normalizedRows));

            const resp = await fetch('import_csv_product.php', { method: 'POST', body: formData });
            const data = await resp.json();

            showLoading(false);
            if (data.success) {
                previewData = data;
                renderPreview(data);
                goToStep(2);
            } else {
                Swal.fire({ icon: 'error', title: 'ຜິດພາດ', text: data.message });
            }
        } catch (err) {
            showLoading(false);
            const msg = typeof err === 'string' ? err : 'ບໍ່ສາມາດເຊື່ອມຕໍ່ Server ໄດ້';
            Swal.fire({ icon: 'error', title: 'Error', text: msg });
            console.error(err);
        }
    });

    // ===== Render Preview Data =====
    function renderPreview(data) {
        const fields = [data.search_field, ...data.update_fields];

        // Stats
        document.getElementById('previewStats').innerHTML = `
            <div class="stat-box">
                <div class="stat-number">${data.total_rows}</div>
                <div class="stat-label">ລາຍການທັງໝົດ</div>
            </div>
            <div class="stat-box success">
                <div class="stat-number">${data.found_count}</div>
                <div class="stat-label">ພົບໃນລະບົບ</div>
            </div>
            <div class="stat-box danger">
                <div class="stat-number">${data.not_found_count}</div>
                <div class="stat-label">ບໍ່ພົບໃນລະບົບ</div>
            </div>
        `;

        // Errors
        const errDiv = document.getElementById('previewErrors');
        if (data.errors && data.errors.length > 0) {
            errDiv.style.display = 'block';
            errDiv.innerHTML = `<div class="error-list">
                <h4><i class="fas fa-exclamation-triangle"></i> ແຖວທີ່ມີຂໍ້ຜິດພາດ (${data.errors.length})</h4>
                <ul>${data.errors.map(e => `<li>${e}</li>`).join('')}</ul>
            </div>`;
        } else {
            errDiv.style.display = 'none';
        }

        // Build table header
        const headerHtml = '<tr>' + fields.map(f => `<th>${f}</th>`).join('') + '<th>ສະຖານະ</th></tr>';

        // Found Table
        document.getElementById('foundCount').textContent = data.found_count;
        document.getElementById('foundTableHead').innerHTML = headerHtml;
        if (data.found.length > 0) {
            document.getElementById('foundTableWrap').style.display = 'block';
            document.getElementById('foundEmpty').style.display = 'none';
            document.getElementById('foundTableBody').innerHTML = data.found.map(row => {
                return '<tr>' + fields.map(f => `<td>${escapeHtml(row[f] || '')}</td>`).join('')
                    + '<td><span class="badge badge-success"><i class="fas fa-check"></i> ພົບ</span></td></tr>';
            }).join('');
        } else {
            document.getElementById('foundTableWrap').style.display = 'none';
            document.getElementById('foundEmpty').style.display = 'block';
        }

        // Not Found Table
        document.getElementById('notFoundCount').textContent = data.not_found_count;
        document.getElementById('notFoundTableHead').innerHTML = headerHtml;
        if (data.not_found.length > 0) {
            document.getElementById('notFoundTableWrap').style.display = 'block';
            document.getElementById('notFoundEmpty').style.display = 'none';
            document.getElementById('notFoundTableBody').innerHTML = data.not_found.map(row => {
                return '<tr>' + fields.map(f => `<td>${escapeHtml(row[f] || '')}</td>`).join('')
                    + '<td><span class="badge badge-danger"><i class="fas fa-times"></i> ບໍ່ພົບ</span></td></tr>';
            }).join('');
        } else {
            document.getElementById('notFoundTableWrap').style.display = 'none';
            document.getElementById('notFoundEmpty').style.display = 'block';
        }

        // Disable execute button if nothing to update
        document.getElementById('btnExecute').disabled = (data.found_count === 0);
    }

    // ===== Execute Bulk Update =====
    function executeUpdate() {
        if (!previewData || previewData.found_count === 0) return;

        Swal.fire({
            title: 'ຢືນຢັນການອັບເດດ?',
            html: `ຈະອັບເດດ <strong>${previewData.found_count}</strong> ລາຍການ.<br>ການກະທຳນີ້ບໍ່ສາມາດຍ້ອນກັບໄດ້.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<i class="fas fa-check"></i> ຢືນຢັນ',
            cancelButtonText: 'ຍົກເລີກ'
        }).then(result => {
            if (result.isConfirmed) {
                showLoading(true);

                const fd = new FormData();
                fd.append('csv_action', 'execute');

                fetch('import_csv_product.php', { method: 'POST', body: fd })
                    .then(r => r.json())
                    .then(data => {
                        showLoading(false);
                        renderResult(data);
                        goToStep(3);
                    })
                    .catch(err => {
                        showLoading(false);
                        Swal.fire({ icon: 'error', title: 'Error', text: 'ບໍ່ສາມາດເຊື່ອມຕໍ່ Server ໄດ້' });
                        console.error(err);
                    });
            }
        });
    }

    // ===== Render Results =====
    function renderResult(data) {
        const content = document.getElementById('resultContent');

        if (data.success) {
            let notFoundHtml = '';
            if (previewData && previewData.not_found && previewData.not_found.length > 0) {
                const nfFields = [previewData.search_field, ...previewData.update_fields];
                notFoundHtml = `
                    <h4 style="margin:25px 0 10px;color:var(--danger);"><i class="fas fa-times-circle"></i> ລາຍການທີ່ບໍ່ພົບໃນລະບົບ (${previewData.not_found.length})</h4>
                    <div class="table-scroll">
                        <table class="preview-table">
                            <thead><tr>${nfFields.map(f => `<th>${f}</th>`).join('')}</tr></thead>
                            <tbody>${previewData.not_found.map(row => '<tr>' + nfFields.map(f => `<td>${escapeHtml(row[f] || '')}</td>`).join('') + '</tr>').join('')}</tbody>
                        </table>
                    </div>`;
            }

            content.innerHTML = `
                <div class="result-icon">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div style="text-align:center;margin-bottom:25px;">
                    <h3 style="color:var(--success);margin-bottom:8px;">${data.message}</h3>
                    <p style="color:var(--text-secondary);font-size:14px;">ຂໍ້ມູນສິນຄ້າຖືກອັບເດດສຳເລັດແລ້ວ</p>
                </div>
                <div class="stats-row">
                    <div class="stat-box success">
                        <div class="stat-number">${data.affected_rows}</div>
                        <div class="stat-label">ອັບເດດສຳເລັດ</div>
                    </div>
                    <div class="stat-box">
                        <div class="stat-number">${data.total_submitted}</div>
                        <div class="stat-label">ລາຍການທີ່ສົ່ງ</div>
                    </div>
                </div>
                ${notFoundHtml}
                <div class="btn-group" style="justify-content:center;margin-top:25px;">
                    <button class="btn-reset" onclick="window.location.reload()">
                        <i class="fas fa-redo"></i> Import ໃໝ່
                    </button>
                    <a href="make_product.php" class="btn-execute" style="text-decoration:none;">
                        <i class="fas fa-arrow-left"></i> ກັບໄປໜ້າສິນຄ້າ
                    </a>
                </div>`;
        } else {
            content.innerHTML = `
                <div class="result-icon error">
                    <i class="fas fa-times-circle"></i>
                </div>
                <div style="text-align:center;margin-bottom:25px;">
                    <h3 style="color:var(--danger);margin-bottom:8px;">ອັບເດດບໍ່ສຳເລັດ</h3>
                    <p style="color:var(--text-secondary);">${escapeHtml(data.message)}</p>
                </div>
                <div class="btn-group" style="justify-content:center;">
                    <button class="btn-reset" onclick="goToStep(1)">
                        <i class="fas fa-redo"></i> ລອງໃໝ່
                    </button>
                </div>`;
        }
    }

    // ===== Utility: Loading =====
    function showLoading(show) {
        document.getElementById('loadingOverlay').classList.toggle('show', show);
    }

    // ===== Utility: Escape HTML =====
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // ===== Initial CSV example update =====
    updateCsvExample();
</script>

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