<?php
// post/transaksi_action.php
require_once '../config/config.php';

header('Content-Type: application/json');
ini_set('display_errors', 0);

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'msg' => 'Akses ditolak.']);
    exit;
}

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

try {
    if ($action === 'save_receipt') {
        $po_id      = intval($_POST['po_id'] ?? 0);
        $invoice_no = $_POST['invoice_no'] ?? '';
        $user_id    = $_SESSION['user_id'];

        // Handle Input Items
        $items_input = $_POST['items'] ?? [];
        if (is_string($items_input)) {
            $items = json_decode($items_input, true);
        } else {
            $items = $items_input;
        }

        if (!is_array($items)) throw new Exception("Data items tidak valid.");
        if ($po_id === 0) throw new Exception("ID PO tidak valid.");
        if (empty($items)) throw new Exception("Tidak ada item untuk disimpan.");

        $pdo->beginTransaction();

        // Ambil Data PO
        $stmt_po = $pdo->prepare("SELECT po_number FROM purchase_orders WHERE id = ?");
        $stmt_po->execute([$po_id]);
        $po_data = $stmt_po->fetch(PDO::FETCH_ASSOC);
        if (!$po_data) throw new Exception("Purchase Order tidak ditemukan.");
        $po_number = $po_data['po_number'];

        foreach ($items as $item) {
            $part_number = $item['code'] ?? '';
            $item_name   = $item['name'] ?? '';
            $qty_receive = intval($item['qty'] ?? 0);
            $unit        = $item['unit'] ?? '';
            $price_input = floatval($item['price'] ?? 0);

            if (empty($part_number) || $qty_receive <= 0) continue;

            // ==========================================
            // VALIDASI BACKEND: Cek Qty PO
            // ==========================================
            $stmt_check_po = $pdo->prepare("SELECT id, qty FROM purchase_order_items WHERE po_id = ? AND item_code = ?");
            $stmt_check_po->execute([$po_id, $part_number]);
            $po_item = $stmt_check_po->fetch(PDO::FETCH_ASSOC);

            if ($po_item) {
                $qty_po_ordered = intval($po_item['qty']);
                
                // Jika Qty Receive > Qty PO -> Tolak (Throw Exception)
                if ($qty_receive > $qty_po_ordered) {
                    throw new Exception("Error: Qty untuk item '{$part_number}' ({$qty_receive}) melebihi pesanan ({$qty_po_ordered}).");
                }

                $po_item_id = $po_item['id'];

                // Logika Hapus/Update
                if ($qty_receive == $qty_po_ordered) {
                    $stmt_del_po = $pdo->prepare("DELETE FROM purchase_order_items WHERE id = ?");
                    $stmt_del_po->execute([$po_item_id]);
                } else {
                    $sisa_qty = $qty_po_ordered - $qty_receive;
                    $stmt_upd_po = $pdo->prepare("UPDATE purchase_order_items SET qty = ? WHERE id = ?");
                    $stmt_upd_po->execute([$sisa_qty, $po_item_id]);
                }
            }

            // Update Stok & Harga Master
            $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_input;

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

                $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, $unit, $price_input
            ]);
        }

        // Update Status PO
        $stmt_count = $pdo->prepare("SELECT COUNT(*) FROM purchase_order_items WHERE po_id = ?");
        $stmt_count->execute([$po_id]);
        $remaining_items = $stmt_count->fetchColumn();

        if ($remaining_items == 0) {
            $stmt_update_po = $pdo->prepare("UPDATE purchase_orders SET status = 'completed' WHERE id = ?");
        } else {
            $stmt_update_po = $pdo->prepare("UPDATE purchase_orders SET status = 'partial' WHERE id = ?");
        }
        $stmt_update_po->execute([$po_id]);

        $pdo->commit();

        echo json_encode(['status' => 'success', 'msg' => 'Transaksi berhasil!']);

    } else {
        throw new Exception("Aksi tidak dikenal.");
    }

} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode(['status' => 'error', 'msg' => $e->getMessage()]);
}
?>