<?php
include "koneksi.php";
require __DIR__ . '/../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;

if (isset($_POST['import'])) {
    $file = $_FILES['file_excel']['tmp_name'];
    $filename = $_FILES['file_excel']['name'] ?? '';
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

    // Validasi ekstensi
    if (!in_array($ext, ['xls', 'xlsx'])) {
        echo "<script>alert('Format file tidak valid! Harap upload file Excel (.xls/.xlsx)'); history.back();</script>";
        exit;
    }

    if ($file) {
        $spreadsheet = IOFactory::load($file);
        $sheet = $spreadsheet->getActiveSheet();
        $rows = $sheet->toArray();

        $rowNum   = 0;
        $sukses   = 0;
        $duplikat = 0;

        foreach ($rows as $row) {
            $rowNum++;
            if ($rowNum == 1) continue; // Lewati header

            $kode_barang   = $conn->real_escape_string($row[0] ?? '');
            $nama_produk   = $conn->real_escape_string($row[1] ?? '');
            $stok          = (int)($row[2] ?? 0);
            $harga_beli    = (float)($row[3] ?? 0);
            $harga_eceran  = (float)($row[4] ?? 0);
            $kategori      = $conn->real_escape_string($row[5] ?? '');

            if ($kode_barang && $nama_produk) {
                // Cek duplikat
                $cek = $conn->query("SELECT id FROM tabel_produk 
                                     WHERE kode_barang='$kode_barang' OR nama_produk='$nama_produk'");
                if ($cek->num_rows == 0) {
                    $stmt = $conn->prepare("INSERT INTO tabel_produk 
                        (kode_barang,nama_produk,stok,harga_beli,harga_eceran,kategori) 
                        VALUES (?,?,?,?,?,?)");
                    $stmt->bind_param("ssidds", 
                        $kode_barang, $nama_produk, $stok, $harga_beli, $harga_eceran, $kategori
                    );
                    $stmt->execute();
                    $sukses++;
                } else {
                    $duplikat++;
                }
            }
        }

        echo "<script>
            alert('Import selesai! Berhasil: $sukses, Duplikat: $duplikat');
            location.href='index.php?page=produk';
        </script>";
        exit;
    }
}
?>

<div class="container mt-4">
    <h3>Import Produk dari Excel</h3>
    <form method="post" enctype="multipart/form-data">
        <div class="mb-3">
            <label class="form-label">Pilih File Excel (.xls / .xlsx)</label>
            <input type="file" name="file_excel" class="form-control" accept=".xls,.xlsx" required>
        </div>
        <button type="submit" name="import" class="btn btn-success">Import</button>
        <a href="index.php?page=produk" class="btn btn-secondary">Kembali</a>
    </form>

    <hr>
    <p><b>Format Excel yang didukung:</b></p>
    <table class="table table-bordered">
        <thead class="table-light">
            <tr>
                <th>Kode Barang</th>
                <th>Nama Produk</th>
                <th>Stok</th>
                <th>Harga Beli</th>
                <th>Harga Eceran</th>
                <th>Kategori</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>BRG001</td>
                <td>Produk A</td>
                <td>100</td>
                <td>5000</td>
                <td>7000</td>
                <td>Umum</td>
            </tr>
        </tbody>
    </table>
</div>
