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

 $action = $_POST['action'] ?? '';

try {
    $pdo->beginTransaction();

    if ($action === 'add') {
        
        $po_number = $_POST['po_number'];
        
        // ==========================================
        // LOGIKA BARU: CEK DUPLICATE & HANDLE HEADER
        // ==========================================
        
        // 1. Cek apakah PO Number sudah ada di database
        $stmt_cek = $pdo->prepare("SELECT id FROM purchase_orders WHERE po_number = ?");
        $stmt_cek->execute([$po_number]);
        $existing_po = $stmt_cek->fetch(PDO::FETCH_ASSOC);

        if ($existing_po) {
            // Jika PO sudah ada (Satu PO beberapa barang)
            $po_id = $existing_po['id'];
            
            // Opsional: Update tanggal/supplier/komentar jika perlu (misal input terbaru lebih update)
            // Di sini kita biarkan header pertama tetap utuh, atau bisa di-update:
            $stmt_upd = $pdo->prepare("UPDATE purchase_orders SET date = ?, supplier_name = ? WHERE id = ?");
            $stmt_upd->execute([$_POST['date'], $_POST['supplier_name'] ?? '', $po_id]);
            
        } else {
            // Jika PO belum ada (PO Baru)
            $stmt = $pdo->prepare("INSERT INTO purchase_orders (po_number, date, supplier_name, status, comments) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([
                $po_number,
                $_POST['date'],
                $_POST['supplier_name'] ?? '',
                $_POST['status'] ?? 'pending',
                $_POST['comments'] ?? ''
            ]);
            $po_id = $pdo->lastInsertId();
        }

        // ==========================================
        // 2. INSERT DETAIL (Normalisasi Array/Single)
        // ==========================================
        
        $codes = $_POST['item_code'] ?? [];
        $names = $_POST['item_name'] ?? [];
        $qtys  = $_POST['qty'] ?? [];
        $units = $_POST['unit'] ?? [];
        $prices= $_POST['price'] ?? [];

        // Jika bukan array, ubah jadi array (handle input tunggal)
        if (!is_array($codes)) $codes = [$codes];
        if (!is_array($names)) $names = [$names];
        if (!is_array($qtys))  $qtys  = [$qtys];
        if (!is_array($units)) $units = [$units];
        if (!is_array($prices))$prices= [$prices];

        $stmt_item = $pdo->prepare("INSERT INTO purchase_order_items (po_id, item_code, item_name, qty, unit, price) VALUES (?, ?, ?, ?, ?, ?)");
        
        foreach ($codes as $key => $item_code) {
            $item_name = $names[$key] ?? '';
            $qty       = $qtys[$key] ?? 0;
            $unit      = $units[$key] ?? '';
            $price     = $prices[$key] ?? 0;

            if (empty($item_code)) continue;

            $stmt_item->execute([$po_id, $item_code, $item_name, $qty, $unit, $price]);
        }

        $_SESSION['flash'] = [
            'type' => 'success',
            'msg'  => 'Item berhasil ditambahkan ke PO ' . htmlspecialchars($po_number)
        ];
    }
    elseif ($action === 'edit') {
        // ==========================================
        // 1. UPDATE HEADER
        // ==========================================
        $id = $_POST['id'];
        
        $stmt = $pdo->prepare("UPDATE purchase_orders SET po_number=?, date=?, supplier_name=?, status=?, comments=? WHERE id=?");
        $stmt->execute([
            $_POST['po_number'],
            $_POST['date'],
            $_POST['supplier_name'] ?? '',
            $_POST['status'],
            $_POST['comments'] ?? '',
            $id
        ]);

        // ==========================================
        // 2. DELETE OLD ITEMS
        // ==========================================
        $del = $pdo->prepare("DELETE FROM purchase_order_items WHERE po_id = ?");
        $del->execute([$id]);

        // ==========================================
        // 3. INSERT NEW ITEMS
        // ==========================================
        $codes = $_POST['item_code'] ?? [];
        $names = $_POST['item_name'] ?? [];
        $qtys  = $_POST['qty'] ?? [];
        $units = $_POST['unit'] ?? [];
        $prices= $_POST['price'] ?? [];

        if (!is_array($codes)) $codes = [$codes];
        if (!is_array($names)) $names = [$names];
        if (!is_array($qtys))  $qtys  = [$qtys];
        if (!is_array($units)) $units = [$units];
        if (!is_array($prices))$prices= [$prices];

        $stmt_item = $pdo->prepare("INSERT INTO purchase_order_items (po_id, item_code, item_name, qty, unit, price) VALUES (?, ?, ?, ?, ?, ?)");
        
        foreach ($codes as $key => $item_code) {
            $item_name = $names[$key] ?? '';
            $qty       = $qtys[$key] ?? 0;
            $unit      = $units[$key] ?? '';
            $price     = $prices[$key] ?? 0;

            if (empty($item_code)) continue;

            $stmt_item->execute([$id, $item_code, $item_name, $qty, $unit, $price]);
        }

        $_SESSION['flash'] = [
            'type' => 'success',
            'msg'  => $lang[$current_lang]['msg_success_edit'] ?? 'PO berhasil diperbarui'
        ];
    }
    elseif ($action === 'delete') {
        $id = $_POST['id'];
        
        $pdo->prepare("DELETE FROM purchase_order_items WHERE po_id = ?")->execute([$id]);
        
        $stmt = $pdo->prepare("DELETE FROM purchase_orders WHERE id = ?");
        $stmt->execute([$id]);

        $_SESSION['flash'] = [
            'type' => 'success',
            'msg'  => $lang[$current_lang]['msg_success_delete'] ?? 'PO berhasil dihapus'
        ];
    }

    $pdo->commit();
    
    header('Location: ../view/po_list.php');
    exit;

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