<?php
require '../koneksi.php';
require '../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;

if (isset($_FILES['file_excel']['tmp_name'])) {
    $file = $_FILES['file_excel']['tmp_name'];

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

    // Lewati baris header (baris pertama)
    unset($rows[0]);

    $stmt = $conn->prepare("INSERT INTO barang (barcode, nama_barang, part_number, satuan, keterangan)
                            VALUES (?, ?, ?, ?, ?)
                            ON DUPLICATE KEY UPDATE
                            nama_barang=VALUES(nama_barang),
                            part_number=VALUES(part_number),
                            satuan=VALUES(satuan),
                            keterangan=VALUES(keterangan)");

    $success = 0;
    foreach ($rows as $row) {
        $barcode      = trim($row[0]);
        $nama_barang  = trim($row[1]);
        $part_number  = trim($row[2]);
        $satuan       = trim($row[3]);
        $keterangan   = trim($row[4]);

        if ($barcode != '') {
            $stmt->execute([$barcode, $nama_barang, $part_number, $satuan, $keterangan]);
            $success++;
        }
    }

    echo "$success data berhasil diimport.";
} else {
    echo "File tidak ditemukan.";
}
