<?php
// post/po_import.php
require_once '../config/config.php';
if (!isset($_SESSION['user_id'])) { header('Location: ../index.php'); exit; }

if(isset($_POST['submit']) || isset($_FILES['file_excel'])) {
    $file = $_FILES['file_excel']['tmp_name'];
    $ext = pathinfo($_FILES['file_excel']['name'], PATHINFO_EXTENSION);

    try {
        // Logika membaca CSV (Tanpa library eksternal)
        if ($ext === 'csv' || $ext === 'xls') { // XLS sering terbaca sebagai teks oleh logic sederhana ini, atau pakai library
            
            // Jika ingin membaca XLS real, gunakan PhpSpreadsheet. 
            // Untuk demo tanpa library, kita asumsikan user upload CSV atau XLS yang formatnya mirip teks tab-delimited.
            // Berikut logika untuk CSV:
            
            $handle = fopen($file, "r");
            $header = fgetcsv($handle, 1000, ","); // Skip header (bisa juga "\t" jika tab delimited)
            
            $pdo->beginTransaction();
            
            while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
                // Jika file hasil download template tadi (pakai tab), gunakan explode("\t", ...)
                // Deteksi delimiter sederhana:
                $data_row = (count($row) == 1 && strpos($row[0], "\t") !== false) ? explode("\t", $row[0]) : $row;

                // Mapping kolom sesuai Template Baru:
                // Index 0: No PO
                // Index 1: Tanggal
                // Index 2: Supplier (BARU)
                // Index 3: Kode Barang
                // Index 4: Nama Barang
                // Index 5: Qty
                // Index 6: Unit
                // Index 7: Harga
                // Index 8: Status
                // Index 9: Komentar
                
                if(count($data_row) < 8) continue; // Skip jika baris tidak lengkap

                $po_number = $data_row[0];
                $date      = date('Y-m-d', strtotime($data_row[1]));
                $supplier  = $data_row[2];           // Ambil Supplier
                $item_code = $data_row[3];
                $item_name = $data_row[4];
                $qty       = (float)$data_row[5];
                $unit      = $data_row[6];
                $price     = (float)$data_row[7];
                $status    = strtolower($data_row[8]) ?: 'pending';
                $comments  = $data_row[9] ?? '';

                // 1. Cek/Insert Header PO
                $stmtPO = $pdo->prepare("SELECT id FROM purchase_orders WHERE po_number = ?");
                $stmtPO->execute([$po_number]);
                $poID = $stmtPO->fetchColumn();

                if(!$poID) {
                    // Insert Header dengan Supplier Name
                    $stmtInsertPO = $pdo->prepare("INSERT INTO purchase_orders (po_number, date, supplier_name, status, comments) VALUES (?, ?, ?, ?, ?)");
                    $stmtInsertPO->execute([$po_number, $date, $supplier, $status, $comments]);
                    $poID = $pdo->lastInsertId();
                }

                // 2. Insert Item
                $stmtItem = $pdo->prepare("INSERT INTO purchase_order_items (po_id, item_code, item_name, qty, unit, price) VALUES (?, ?, ?, ?, ?, ?)");
                $stmtItem->execute([$poID, $item_code, $item_name, $qty, $unit, $price]);
            }
            
            fclose($handle);
            $pdo->commit();
            
            $_SESSION['flash'] = ['type' => 'success', 'msg' => 'Data PO berhasil di-import!'];
            
        } else {
             $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Format file tidak didukung. Gunakan CSV atau XLS.'];
        }

    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Error: ' . $e->getMessage()];
    }
    
    header('Location: ../view/po_list.php');
    exit;
}
?>