<?php
require 'vendor/autoload.php'; // composer require phpoffice/phpspreadsheet
use PhpOffice\PhpSpreadsheet\IOFactory;

$conn = new mysqli("localhost", "root", "", "stock_opname");

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

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

    $jumlah_sukses = 0;

    // Lewati baris pertama (judul kolom)
    for ($i = 1; $i < count($rows); $i++) {
        list($part_number, $nama_barang, $satuan, $barcode, $foto, $keterangan) = $rows[$i];

        // Cek apakah barcode sudah ada
        $cek = $conn->query("SELECT id_barang FROM barang WHERE barcode = '$barcode'");
        if ($cek->num_rows > 0) continue;

        $stmt = $conn->prepare("INSERT INTO barang (part_number, nama_barang, satuan, barcode, foto, keterangan) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssss", $part_number, $nama_barang, $satuan, $barcode, $foto, $keterangan);
        if ($stmt->execute()) $jumlah_sukses++;
    }

    echo "$jumlah_sukses barang berhasil diupload dari Excel. <a href='form_barang.php'>Kembali</a>";
} else {
    echo "File tidak ditemukan. <a href='form_barang.php'>Kembali</a>";
}
