<?php
// File: admin/bulk_upload_produk.php
// Bulk upload produk via file XLSX

ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once '../includes/db_connect.php';
require_once '../includes/cache.php';
require_once '../includes/functions.php';
require_once '../includes/security.php';

secureSessionStart();
if (!isset($_SESSION['admin_id']) || !validateAdminSession()) {
    header("Location: login.php"); exit;
}

// ================================================================
// HELPER: Parse XLSX di server menggunakan ZipArchive + XML
// Tanpa library eksternal — hanya PHP native
// ================================================================
function parseXlsxFile($filePath) {
    $zip = new ZipArchive();
    if ($zip->open($filePath) !== true) {
        throw new Exception("File XLSX tidak bisa dibuka. Pastikan file valid dan tidak corrupt.");
    }

    // Baca shared strings (teks yang di-share antar cell)
    $sharedStrings = [];
    $ssXml = $zip->getFromName('xl/sharedStrings.xml');
    if ($ssXml) {
        $ss = simplexml_load_string($ssXml);
        foreach ($ss->si as $si) {
            // Gabungkan semua <t> dalam satu <si> (untuk rich text)
            $text = '';
            foreach ($si->xpath('.//t') as $t) {
                $text .= (string)$t;
            }
            $sharedStrings[] = $text;
        }
    }

    // Baca sheet pertama
    $sheetXml = $zip->getFromName('xl/worksheets/sheet1.xml');
    if (!$sheetXml) {
        // Coba cari nama sheet lain
        $workbookXml = $zip->getFromName('xl/workbook.xml');
        if ($workbookXml) {
            $wb = simplexml_load_string($workbookXml);
            $wb->registerXPathNamespace('x', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
            $sheets = $wb->xpath('//x:sheet');
            if ($sheets) {
                $relId = (string)$sheets[0]->attributes('r', true)->id;
                // Baca rels
                $relsXml = $zip->getFromName('xl/_rels/workbook.xml.rels');
                if ($relsXml) {
                    $rels = simplexml_load_string($relsXml);
                    foreach ($rels->Relationship as $rel) {
                        if ((string)$rel['Id'] === $relId) {
                            $target = 'xl/' . ltrim((string)$rel['Target'], '/');
                            $sheetXml = $zip->getFromName($target);
                            break;
                        }
                    }
                }
            }
        }
    }
    $zip->close();

    if (!$sheetXml) {
        throw new Exception("Sheet data tidak ditemukan di dalam file XLSX.");
    }

    $sheet = simplexml_load_string($sheetXml);
    $sheet->registerXPathNamespace('x', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');

    $rows = [];
    foreach ($sheet->sheetData->row as $row) {
        $rowNum = (int)$row['r'];
        $rowData = [];
        foreach ($row->c as $cell) {
            $cellRef  = (string)$cell['r'];
            $cellType = (string)$cell['t'];
            $cellVal  = (string)$cell->v;

            // Ekstrak kolom dari referensi (A1 → A, B12 → B, dst)
            preg_match('/^([A-Z]+)/', $cellRef, $colMatch);
            $colLetter = $colMatch[1] ?? 'A';
            $colIndex  = 0;
            foreach (str_split($colLetter) as $ch) {
                $colIndex = $colIndex * 26 + (ord($ch) - ord('A') + 1);
            }
            $colIndex--; // 0-based

            // Decode nilai
            if ($cellType === 's') {
                // Shared string
                $value = $sharedStrings[(int)$cellVal] ?? '';
            } elseif ($cellType === 'inlineStr') {
                $value = (string)$cell->is->t;
            } else {
                $value = $cellVal;
            }

            $rowData[$colIndex] = trim($value);
        }
        $rows[$rowNum] = $rowData;
    }

    return $rows;
}

// ================================================================
// HELPER: Konversi kolom letter ke index 0-based
// ================================================================
function colToIndex($letter) {
    $letter = strtoupper(trim($letter));
    $index  = 0;
    for ($i = 0; $i < strlen($letter); $i++) {
        $index = $index * 26 + (ord($letter[$i]) - ord('A') + 1);
    }
    return $index - 1;
}

// ================================================================
// PROSES UPLOAD
// ================================================================
$results    = null; // hasil preview / import
$error      = '';
$success    = '';
$preview    = [];
$importDone = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = $_POST['action'] ?? 'preview';

    // --- VALIDASI FILE ---
    if (empty($_FILES['xlsx_file']['name']) || $_FILES['xlsx_file']['error'] !== UPLOAD_ERR_OK) {
        $error = "Harap pilih file XLSX untuk diupload.";
    } else {
        $file     = $_FILES['xlsx_file'];
        $ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $maxSize  = 5 * 1024 * 1024; // 5MB

        if ($ext !== 'xlsx') {
            $error = "File harus berformat .xlsx (bukan .xls, .csv, atau format lain).";
        } elseif ($file['size'] > $maxSize) {
            $error = "Ukuran file terlalu besar. Maksimal 5MB.";
        } else {
            // Validasi MIME
            if (function_exists('finfo_open')) {
                $finfo    = finfo_open(FILEINFO_MIME_TYPE);
                $mimeReal = finfo_file($finfo, $file['tmp_name']);
                finfo_close($finfo);
                $validMime = [
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    'application/zip',
                    'application/octet-stream',
                ];
                if (!in_array($mimeReal, $validMime)) {
                    $error = "File bukan XLSX yang valid (MIME: $mimeReal).";
                }
            }
        }
    }

    if (empty($error)) {
        try {
            // Pindahkan ke tmp sementara
            $tmpPath = sys_get_temp_dir() . '/bulk_' . uniqid() . '.xlsx';
            move_uploaded_file($file['tmp_name'], $tmpPath);

            $rows = parseXlsxFile($tmpPath);
            @unlink($tmpPath);

            // Temukan header row (baris yang punya "model" dan "tipe")
            $headerRow = null;
            $colModel  = null;
            $colTipe   = null;
            $colHarga  = null;
            $colKat    = null;
            $colFeat   = null;

            foreach ($rows as $rowNum => $rowData) {
                // Cari baris yang isinya header
                foreach ($rowData as $idx => $val) {
                    $v = mb_strtolower(trim($val));
                    if (in_array($v, ['model', 'nama model', 'nama mobil'])) {
                        $headerRow = $rowNum;
                        $colModel  = $idx;
                        break;
                    }
                }
                if ($headerRow !== null) break;
            }

            if ($headerRow === null) {
                throw new Exception("Tidak menemukan baris header. Pastikan baris ke-4 berisi kolom: Model, Tipe, Harga.");
            }

            // Petakan kolom dari header row
            $headerData = $rows[$headerRow];
            foreach ($headerData as $idx => $val) {
                $v = mb_strtolower(trim($val));
                if (in_array($v, ['tipe', 'nama tipe', 'varian'])) $colTipe  = $idx;
                if (in_array($v, ['harga', 'harga (rp)', 'harga otr', 'harga (rp)*'])) $colHarga = $idx;
                if (in_array($v, ['kategori', 'category']))      $colKat   = $idx;
                if (in_array($v, ['unggulan', 'featured']))       $colFeat  = $idx;
            }

            if ($colTipe === null || $colHarga === null) {
                throw new Exception("Kolom 'Tipe' dan 'Harga' wajib ada. Cek nama header di baris ke-4.");
            }

            // Parse data rows
            $parsed   = []; // array produk yang sudah digabung
            $rowCount = 0;

            foreach ($rows as $rowNum => $rowData) {
                if ($rowNum <= $headerRow) continue; // skip header & atasnya
                if ($rowCount >= 200) break; // batas 200 baris

                $model = trim($rowData[$colModel] ?? '');
                $tipe  = trim($rowData[$colTipe]  ?? '');
                $harga = trim($rowData[$colHarga]  ?? '');
                $kat   = trim($rowData[$colKat]    ?? 'MPV');
                $feat  = strtoupper(trim($rowData[$colFeat] ?? ''));

                // Skip baris kosong
                if (empty($model) && empty($tipe)) continue;
                if (empty($model) && !empty($tipe)) {
                    // Jika model kosong, ambil dari baris sebelumnya
                    if (!empty($parsed)) {
                        $model = array_key_last($parsed);
                    } else {
                        continue; // tidak bisa inferensi, skip
                    }
                }

                // Bersihkan harga
                $hargaNum = (float) preg_replace('/[^0-9.]/', '', $harga);

                if (empty($tipe) || $hargaNum <= 0) continue;

                if (!isset($parsed[$model])) {
                    $parsed[$model] = [
                        'model'    => $model,
                        'kategori' => !empty($kat) ? $kat : 'MPV',
                        'featured' => ($feat === 'YA' || $feat === 'YES' || $feat === '1') ? 1 : 0,
                        'tipes'    => [],
                        'errors'   => [],
                    ];
                }

                $parsed[$model]['tipes'][] = [
                    'nama'  => $tipe,
                    'harga' => $hargaNum,
                ];

                $rowCount++;
            }

            if (empty($parsed)) {
                throw new Exception("Tidak ada data valid yang ditemukan. Pastikan kolom Model, Tipe, dan Harga terisi.");
            }

            // Simpan ke session untuk konfirmasi import
            $_SESSION['bulk_preview'] = $parsed;

            if ($action === 'preview') {
                $preview = $parsed;
            } elseif ($action === 'import') {
                // ============= PROSES IMPORT KE DATABASE =============
                $importResults = [];
                $successCount  = 0;
                $skipCount     = 0;

                foreach ($parsed as $modelName => $data) {
                    try {
                        $tipes     = $data['tipes'];
                        $varianArr = array_map(fn($t) => ['nama' => $t['nama'], 'harga' => $t['harga']], $tipes);
                        $hargaMin  = min(array_column($tipes, 'harga'));
                        $varianJson = json_encode($varianArr, JSON_UNESCAPED_UNICODE);
                        $kategori  = $data['kategori'];
                        $featured  = $data['featured'];

                        // Cek apakah model sudah ada
                        $existing = $pdo->prepare("SELECT id, varian, is_featured FROM produk WHERE nama_mobil = ?");
                        $existing->execute([$modelName]);
                        $existRow = $existing->fetch();

                        if ($existRow) {
                            // Merge tipe baru ke varian yang sudah ada
                            $existingVarian = [];
                            if (!empty($existRow['varian'])) {
                                $existingVarian = json_decode($existRow['varian'], true) ?: [];
                            }
                            // Tambah tipe yang belum ada (cek berdasarkan nama)
                            $existingNames = array_column($existingVarian, 'nama');
                            $added = 0;
                            foreach ($varianArr as $newTipe) {
                                if (!in_array($newTipe['nama'], $existingNames)) {
                                    $existingVarian[] = $newTipe;
                                    $added++;
                                }
                            }
                            // Update harga min dari semua tipe
                            $allHarga = array_column($existingVarian, 'harga');
                            $newMin   = !empty($allHarga) ? min($allHarga) : $hargaMin;
                            $newJson  = json_encode($existingVarian, JSON_UNESCAPED_UNICODE);

                            $pdo->prepare("UPDATE produk SET varian=?, harga_otr=? WHERE id=?")
                                ->execute([$newJson, $newMin, $existRow['id']]);

                            $importResults[] = [
                                'model'  => $modelName,
                                'status' => 'updated',
                                'detail' => "$added tipe baru ditambahkan",
                            ];
                        } else {
                            // Insert baru
                            $pdo->prepare(
                                "INSERT INTO produk (nama_mobil, harga_otr, kategori, varian, is_featured)
                                 VALUES (?, ?, ?, ?, ?)"
                            )->execute([$modelName, $hargaMin, $kategori, $varianJson, $featured]);

                            $importResults[] = [
                                'model'  => $modelName,
                                'status' => 'created',
                                'detail' => count($tipes) . " tipe",
                            ];
                        }
                        $successCount++;
                    } catch (Exception $e) {
                        $importResults[] = [
                            'model'  => $modelName,
                            'status' => 'error',
                            'detail' => $e->getMessage(),
                        ];
                    }
                }

                cacheFlush();
                unset($_SESSION['bulk_preview']);
                $results    = $importResults;
                $importDone = true;
                $success    = "$successCount model berhasil diproses dari total " . count($parsed) . " model.";
            }

        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
}

// Restore preview dari session jika ada (setelah konfirmasi)
if (empty($preview) && !empty($_SESSION['bulk_preview']) && !$importDone) {
    $preview = $_SESSION['bulk_preview'];
}

$page_title = 'Bulk Upload Produk';
require 'includes/header.php';
?>

<main class="flex-1 overflow-y-auto p-4 md:p-8 bg-gray-50 w-full">

    <!-- Header -->
    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
        <div>
            <h1 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
                <i class="fa-solid fa-file-excel text-green-600"></i> Bulk Upload Produk
            </h1>
            <p class="text-sm text-gray-500 mt-1">Upload banyak produk sekaligus via file XLSX</p>
        </div>
        <a href="crud_produk.php"
           class="flex items-center gap-2 text-gray-600 hover:text-gray-800 font-bold text-sm px-4 py-2 rounded-lg hover:bg-gray-200 transition border border-gray-300">
            <i class="fa-solid fa-arrow-left"></i> Kembali ke Produk
        </a>
    </div>

    <!-- Alert error -->
    <?php if ($error): ?>
    <div class="bg-red-50 border border-red-200 text-red-700 p-4 rounded-xl mb-6 flex items-start gap-3">
        <i class="fa-solid fa-circle-exclamation text-xl mt-0.5 flex-shrink-0"></i>
        <div><strong>Error:</strong> <?= htmlspecialchars($error) ?></div>
    </div>
    <?php endif; ?>

    <!-- Alert success (setelah import) -->
    <?php if ($success && $importDone): ?>
    <div class="bg-green-50 border border-green-200 text-green-700 p-4 rounded-xl mb-6 flex items-start gap-3">
        <i class="fa-solid fa-circle-check text-xl mt-0.5 flex-shrink-0"></i>
        <div><strong>Berhasil!</strong> <?= htmlspecialchars($success) ?></div>
    </div>
    <?php endif; ?>

    <!-- ============================================================
         LANGKAH 1: Download Template + Upload Form
         ============================================================ -->
    <?php if (!$importDone): ?>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">

        <!-- Step 1: Download Template -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <div class="flex items-center gap-3 mb-4">
                <div class="w-8 h-8 rounded-full bg-blue-600 text-white flex items-center justify-center font-black text-sm">1</div>
                <h3 class="font-bold text-gray-800">Download Template</h3>
            </div>
            <p class="text-sm text-gray-500 mb-5">
                Download file template Excel, isi data produk, lalu upload kembali.
            </p>
            <a href="template_bulk_produk.xlsx" download
               class="w-full flex items-center justify-center gap-2 bg-green-600 text-white font-bold py-3 px-4 rounded-xl hover:bg-green-700 transition shadow text-sm">
                <i class="fa-solid fa-download"></i> Download Template .xlsx
            </a>
            <p class="text-xs text-gray-400 mt-3 text-center">File berisi contoh data & petunjuk pengisian</p>
        </div>

        <!-- Step 2: Upload -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 lg:col-span-2">
            <div class="flex items-center gap-3 mb-4">
                <div class="w-8 h-8 rounded-full bg-blue-600 text-white flex items-center justify-center font-black text-sm">2</div>
                <h3 class="font-bold text-gray-800">Upload & Preview</h3>
            </div>

            <form method="POST" enctype="multipart/form-data" id="upload-form">
                <?= csrfInput() ?>
                <input type="hidden" name="action" id="form-action" value="preview">

                <!-- Drop zone -->
                <div id="drop-zone"
                     class="border-2 border-dashed border-gray-300 rounded-xl p-8 text-center mb-4 cursor-pointer hover:border-blue-400 hover:bg-blue-50 transition"
                     onclick="document.getElementById('xlsx-input').click()">
                    <i class="fa-solid fa-file-excel text-4xl text-green-500 mb-3"></i>
                    <p class="text-gray-600 font-semibold">Klik untuk pilih file atau drag & drop di sini</p>
                    <p class="text-xs text-gray-400 mt-1">Format: .xlsx saja — Maks. 5MB — Maks. 200 baris</p>
                    <p id="file-name-display" class="mt-3 text-sm font-bold text-blue-600 hidden"></p>
                </div>
                <input type="file" name="xlsx_file" id="xlsx-input" accept=".xlsx"
                       class="hidden" onchange="handleFileSelect(this)">

                <button type="submit"
                        class="w-full bg-blue-600 text-white font-bold py-3 rounded-xl hover:bg-blue-700 transition shadow flex items-center justify-center gap-2">
                    <i class="fa-solid fa-eye"></i> Preview Data
                </button>
            </form>
        </div>
    </div>

    <!-- ============================================================
         PREVIEW HASIL PARSING
         ============================================================ -->
    <?php if (!empty($preview)): ?>

    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden mb-6">
        <div class="p-5 border-b border-gray-100 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3">
            <div>
                <h2 class="text-lg font-bold text-gray-800 flex items-center gap-2">
                    <i class="fa-solid fa-table-list text-blue-500"></i>
                    Preview Data — <?= count($preview) ?> Model Terdeteksi
                </h2>
                <p class="text-sm text-gray-500 mt-1">Cek kebenaran data di bawah sebelum klik Import.</p>
            </div>
            <!-- Tombol Import -->
            <form method="POST" enctype="multipart/form-data" id="import-form">
                <?= csrfInput() ?>
                <input type="hidden" name="action" value="import">
                <!-- Re-upload file karena $_FILES tidak bisa di-session -->
                <div class="flex items-center gap-3">
                    <label class="text-sm text-gray-500">Re-upload file:</label>
                    <input type="file" name="xlsx_file" accept=".xlsx" required
                           class="text-xs text-gray-600 border rounded p-1">
                    <button type="submit"
                            onclick="return confirm('Yakin akan import <?= count($preview) ?> model ke database?')"
                            class="bg-green-600 text-white font-bold py-2.5 px-6 rounded-xl hover:bg-green-700 transition shadow flex items-center gap-2 whitespace-nowrap">
                        <i class="fa-solid fa-database"></i> Import ke Database
                    </button>
                </div>
            </form>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead class="bg-gray-50 text-gray-500 text-xs uppercase border-b">
                    <tr>
                        <th class="py-3 px-4 text-left">Model</th>
                        <th class="py-3 px-4 text-left">Kategori</th>
                        <th class="py-3 px-4 text-center">Unggulan</th>
                        <th class="py-3 px-4 text-right">Jumlah Tipe</th>
                        <th class="py-3 px-4 text-right">Harga Min</th>
                        <th class="py-3 px-4 text-right">Harga Maks</th>
                        <th class="py-3 px-4 text-left">Tipe-Tipe</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php foreach ($preview as $modelName => $data):
                        $tipes     = $data['tipes'];
                        $hargaMin  = min(array_column($tipes, 'harga'));
                        $hargaMax  = max(array_column($tipes, 'harga'));
                        $tipeNames = implode(', ', array_map(fn($t) => htmlspecialchars($t['nama']), $tipes));

                        // Cek apakah sudah ada di DB
                        $existCheck = $pdo->prepare("SELECT id FROM produk WHERE nama_mobil = ?");
                        $existCheck->execute([$modelName]);
                        $isExist = $existCheck->fetch();
                    ?>
                    <tr class="hover:bg-gray-50 transition">
                        <td class="py-3 px-4 font-semibold text-gray-800">
                            <?= htmlspecialchars($modelName) ?>
                            <?php if ($isExist): ?>
                            <span class="ml-1 text-xs bg-yellow-100 text-yellow-700 px-2 py-0.5 rounded font-bold border border-yellow-200">
                                <i class="fa-solid fa-arrow-up-right-from-square text-[9px]"></i> Update
                            </span>
                            <?php else: ?>
                            <span class="ml-1 text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded font-bold border border-green-200">
                                <i class="fa-solid fa-plus text-[9px]"></i> Baru
                            </span>
                            <?php endif; ?>
                        </td>
                        <td class="py-3 px-4 text-gray-600"><?= htmlspecialchars($data['kategori']) ?></td>
                        <td class="py-3 px-4 text-center">
                            <?php if ($data['featured']): ?>
                            <span class="inline-flex items-center gap-1 bg-yellow-100 text-yellow-700 px-2 py-0.5 rounded text-[10px] font-bold border border-yellow-200">
                                <i class="fa-solid fa-star text-[9px]"></i> YA
                            </span>
                            <?php else: ?>
                            <span class="text-gray-300 text-xs">-</span>
                            <?php endif; ?>
                        </td>
                        <td class="py-3 px-4 text-right font-bold text-blue-600"><?= count($tipes) ?></td>
                        <td class="py-3 px-4 text-right font-mono text-xs text-green-700">
                            Rp <?= number_format($hargaMin, 0, ',', '.') ?>
                        </td>
                        <td class="py-3 px-4 text-right font-mono text-xs text-gray-600">
                            Rp <?= number_format($hargaMax, 0, ',', '.') ?>
                        </td>
                        <td class="py-3 px-4 text-gray-500 text-xs max-w-xs truncate" title="<?= $tipeNames ?>">
                            <?= $tipeNames ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="p-4 bg-blue-50 border-t border-blue-100 text-xs text-blue-700 flex flex-wrap gap-4">
            <span><span class="font-bold bg-yellow-100 text-yellow-700 px-1.5 py-0.5 rounded border border-yellow-200">Update</span> = model sudah ada di DB, tipe baru akan ditambahkan</span>
            <span><span class="font-bold bg-green-100 text-green-700 px-1.5 py-0.5 rounded border border-green-200">Baru</span> = model belum ada, akan dibuat baru</span>
        </div>
    </div>

    <?php endif; // end preview ?>

    <?php else: // $importDone = true ?>

    <!-- ============================================================
         HASIL IMPORT
         ============================================================ -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden mb-6">
        <div class="p-5 border-b border-gray-100">
            <h2 class="text-lg font-bold text-gray-800 flex items-center gap-2">
                <i class="fa-solid fa-clipboard-check text-green-500"></i>
                Hasil Import
            </h2>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead class="bg-gray-50 text-gray-500 text-xs uppercase border-b">
                    <tr>
                        <th class="py-3 px-4 text-left">Model</th>
                        <th class="py-3 px-4 text-center">Status</th>
                        <th class="py-3 px-4 text-left">Detail</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php foreach ($results as $r): ?>
                    <tr class="hover:bg-gray-50">
                        <td class="py-3 px-4 font-semibold text-gray-800"><?= htmlspecialchars($r['model']) ?></td>
                        <td class="py-3 px-4 text-center">
                            <?php if ($r['status'] === 'created'): ?>
                            <span class="bg-green-100 text-green-700 text-xs font-bold px-2 py-1 rounded-full">✓ Dibuat</span>
                            <?php elseif ($r['status'] === 'updated'): ?>
                            <span class="bg-blue-100 text-blue-700 text-xs font-bold px-2 py-1 rounded-full">↑ Diperbarui</span>
                            <?php else: ?>
                            <span class="bg-red-100 text-red-700 text-xs font-bold px-2 py-1 rounded-full">✗ Error</span>
                            <?php endif; ?>
                        </td>
                        <td class="py-3 px-4 text-gray-600 text-xs"><?= htmlspecialchars($r['detail']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div class="p-5 border-t border-gray-100 flex flex-wrap gap-3">
            <a href="crud_produk.php"
               class="bg-blue-600 text-white font-bold py-2.5 px-6 rounded-xl hover:bg-blue-700 transition shadow flex items-center gap-2">
                <i class="fa-solid fa-list"></i> Lihat Semua Produk
            </a>
            <a href="bulk_upload_produk.php"
               class="bg-gray-100 text-gray-700 font-bold py-2.5 px-6 rounded-xl hover:bg-gray-200 transition flex items-center gap-2 border border-gray-300">
                <i class="fa-solid fa-upload"></i> Upload Lagi
            </a>
        </div>
    </div>

    <?php endif; // importDone ?>

    <!-- Aturan / Info -->
    <div class="bg-amber-50 border border-amber-200 rounded-xl p-5 text-sm text-amber-800">
        <h4 class="font-bold mb-2 flex items-center gap-2">
            <i class="fa-solid fa-triangle-exclamation"></i> Ketentuan Bulk Upload
        </h4>
        <ul class="space-y-1 text-xs list-disc list-inside text-amber-700">
            <li>Format file: <strong>.xlsx</strong> saja. Bukan .xls, .csv, atau .ods.</li>
            <li>Kolom wajib: <strong>Model</strong>, <strong>Tipe</strong>, <strong>Harga (Rp)</strong> — nama kolom harus persis sama.</li>
            <li>Beberapa baris dengan Model yang sama = satu produk dengan beberapa tipe.</li>
            <li>Jika model sudah ada di database, tipe baru <strong>ditambahkan</strong> (bukan menimpa data lama).</li>
            <li>Gambar, brosur, video, dan deskripsi harus diisi manual via halaman <strong>Edit Produk</strong>.</li>
            <li>Maksimal <strong>200 baris</strong> per file. Lebih dari itu, bagi menjadi beberapa file.</li>
        </ul>
    </div>

</main>

<script>
function handleFileSelect(input) {
    const display = document.getElementById('file-name-display');
    const dropZone = document.getElementById('drop-zone');
    if (input.files && input.files[0]) {
        const f = input.files[0];
        display.textContent = '✓  ' + f.name + '  (' + (f.size / 1024).toFixed(1) + ' KB)';
        display.classList.remove('hidden');
        dropZone.classList.add('border-blue-400', 'bg-blue-50');
        dropZone.classList.remove('border-gray-300');
    }
}

// Drag & drop
const dz = document.getElementById('drop-zone');
if (dz) {
    dz.addEventListener('dragover', e => { e.preventDefault(); dz.classList.add('border-blue-500', 'bg-blue-50'); });
    dz.addEventListener('dragleave', () => { dz.classList.remove('border-blue-500'); });
    dz.addEventListener('drop', e => {
        e.preventDefault();
        dz.classList.remove('border-blue-500');
        const fi = document.getElementById('xlsx-input');
        fi.files = e.dataTransfer.files;
        handleFileSelect(fi);
    });
}
</script>

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