<?php
// post/import_receipt.php
require_once '../config/config.php';
require_once '../vendor/autoload.php'; // Pastikan PhpSpreadsheet terinstall

use PhpOffice\PhpSpreadsheet\IOFactory;

if (!isset($_SESSION['user_id'])) {
    header('Location: ../index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file_excel'])) {
    $file = $_FILES['file_excel']['tmp_name'];
    
    try {
        $spreadsheet = IOFactory::load($file);
        $sheet = $spreadsheet->getActiveSheet();
        $rows = $sheet->toArray();
        
        $errors = [];
        $validData = [];
        $rowNumber = 1; // Header
        
        // Loop data mulai baris ke-2 (index 1)
        foreach (array_slice($rows, 1) as $row) {
            $rowNumber++;
            $po_number   = trim($row[0] ?? '');
            $item_code   = trim($row[1] ?? '');
            $item_name   = trim($row[2] ?? '');
            $qty_receive = intval($row[3] ?? 0);
            $price       = floatval($row[4] ?? 0);
            $invoice_no  = trim($row[5] ?? '');

            if (empty($po_number) || empty($item_code)) continue; // Skip baris kosong

            // ==========================================
            // VALIDASI BACKEND (SESUAL PERMINTAAN)
            // ==========================================
            
            // 1. Cek apakah PO ada di database
            $stmt_po = $pdo->prepare("SELECT id, status FROM purchase_orders WHERE po_number = ?");
            $stmt_po->execute([$po_number]);
            $po_data = $stmt_po->fetch(PDO::FETCH_ASSOC);

            if (!$po_data) {
                $errors[] = "Baris $rowNumber: PO Number <b>$po_number</b> tidak ditemukan di database.";
                continue;
            }

            $po_id = $po_data['id'];

            // 2. Cek apakah Item ada di purchase_order_items untuk PO tersebut
            $stmt_item = $pdo->prepare("SELECT id, qty, item_name FROM purchase_order_items WHERE po_id = ? AND item_code = ?");
            $stmt_item->execute([$po_id, $item_code]);
            $item_data = $stmt_item->fetch(PDO::FETCH_ASSOC);

            if (!$item_data) {
                $errors[] = "Baris $rowNumber: Item <b>$item_code</b> tidak ditemukan dalam PO <b>$po_number</b>.";
                continue;
            }

            // 3. Validasi Qty (Jika qty receive > qty order)
            if ($qty_receive > $item_data['qty']) {
                $errors[] = "Baris $rowNumber: Qty Receive ($qty_receive) melebihi Qty Order ({$item_data['qty']}) untuk item $item_code.";
                continue;
            }

            // Jika Lolos Validasi
            $validData[] = [
                'po_id' => $po_id,
                'po_number' => $po_number,
                'item_code' => $item_code,
                'item_name' => $item_name ?: $item_data['item_name'],
                'qty' => $qty_receive,
                'price' => $price,
                'invoice_no' => $invoice_no
            ];
        }

        // Jika ada error validasi, hentikan proses dan tampilkan error
        if (!empty($errors)) {
            $_SESSION['flash'] = [
                'type' => 'error',
                'msg' => '<strong>Gagal Import!</strong><br>' . implode('<br>', $errors)
            ];
            header('Location: ../view/transaksi_penerimaan.php');
            exit;
        }

        // ==========================================
        // PROSES SIMPAN JIKA SEMUA VALID
        // ==========================================
        $pdo->beginTransaction();
        $user_id = $_SESSION['user_id'];

        foreach ($validData as $data) {
            $po_id      = $data['po_id'];
            $po_number  = $data['po_number'];
            $part_number= $data['item_code'];
            $item_name  = $data['item_name'];
            $qty_receive= $data['qty'];
            $price      = $data['price'];

            // Ambil info stok lama
            $stmt_get = $pdo->prepare("SELECT stock, price FROM spareparts WHERE part_number = ?");
            $stmt_get->execute([$part_number]);
            $sparepart = $stmt_get->fetch(PDO::FETCH_ASSOC);

            if ($sparepart) {
                $old_stock = intval($sparepart['stock']);
                $old_price = floatval($sparepart['price']);
                $new_stock = $old_stock + $qty_receive;
                $new_price = $price > 0 ? $price : $old_price;

                // Update Stok Master
                $pdo->prepare("UPDATE spareparts SET stock = ?, price = ? WHERE part_number = ?")->execute([$new_stock, $new_price, $part_number]);

                // Insert History
                $stmt_history = $pdo->prepare("INSERT INTO sparepart_history (part_number, name_barang, old_value, new_value, status, doc, qty, changed_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt_history->execute([$part_number, $item_name, $old_price, $new_price, 'GOOD RECEIVE', $po_number, $qty_receive, $user_id]);
            }

            // Insert Goods Receipt Items
            $stmt_gr = $pdo->prepare("INSERT INTO goods_receipt_items (po_number, part_number, item_name, qty, unit, price) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt_gr->execute([$po_number, $part_number, $item_name, $qty_receive, 'PC', $price]);

            // Update/Delete PO Items (Logika Sebelumnya)
            // Ambil qty order
             $stmt_cek_po = $pdo->prepare("SELECT id, qty FROM purchase_order_items WHERE po_id = ? AND item_code = ?");
             $stmt_cek_po->execute([$po_id, $part_number]);
             $po_item = $stmt_cek_po->fetch();

             if ($po_item) {
                 if ($qty_receive == $po_item['qty']) {
                     $pdo->prepare("DELETE FROM purchase_order_items WHERE id = ?")->execute([$po_item['id']]);
                 } elseif ($qty_receive < $po_item['qty']) {
                     $sisa = $po_item['qty'] - $qty_receive;
                     $pdo->prepare("UPDATE purchase_order_items SET qty = ? WHERE id = ?")->execute([$sisa, $po_item['id']]);
                 }
             }
        }

        $pdo->commit();

        $_SESSION['flash'] = [
            'type' => 'success',
            'msg' => 'Import berhasil! ' . count($validData) . ' data diproses.'
        ];
        header('Location: ../view/transaksi_penerimaan.php');
        exit;

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