<?php
require __DIR__ . '/vendor/autoload.php';
$app = require_once __DIR__ . '/bootstrap/app.php';
$kernel = $app->make(\Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
    $request = \Illuminate\Http\Request::capture()
);

use App\Models\Warehouse\OutgoingFulfillment;
use App\Models\Warehouse\OutgoingTransaction;

// Get the inventory transaction that was created
$inventoryTransaction = OutgoingTransaction::where('material_request_number', 'MR-20251204-477-INV')->first();

if ($inventoryTransaction) {
    echo "Found inventory transaction ID: " . $inventoryTransaction->id . "\n";
    echo "Status: " . $inventoryTransaction->status . "\n\n";

    // Create fulfillment records for what was actually dispatched
    // Based on the log, 100 units of item 1 and 50 units of item 2 were dispatched

    // Check if fulfillments already exist
    $existing = OutgoingFulfillment::where('outgoing_transaction_id', 1)->count();

    if ($existing == 0) {
        // Create fulfillment for item 1 (100 units)
        $fulfillment1 = OutgoingFulfillment::create([
            'outgoing_transaction_id' => 1,  // Original transaction
            'item_id' => 1,
            'quantity_fulfilled' => 100,
            'fulfillment_type' => 'inventory',
            'reference_id' => $inventoryTransaction->id,
            'reference_type' => 'OutgoingTransaction',
            'notes' => 'Inventory dispatch - partial fulfillment'
        ]);
        echo "Created fulfillment for item 1: 100 units\n";

        // Create fulfillment for item 2 (50 units)
        $fulfillment2 = OutgoingFulfillment::create([
            'outgoing_transaction_id' => 1,  // Original transaction
            'item_id' => 2,
            'quantity_fulfilled' => 50,
            'fulfillment_type' => 'inventory',
            'reference_id' => $inventoryTransaction->id,
            'reference_type' => 'OutgoingTransaction',
            'notes' => 'Inventory dispatch - partial fulfillment'
        ]);
        echo "Created fulfillment for item 2: 50 units\n";

        echo "\nFulfillments created successfully!\n";
    } else {
        echo "Fulfillments already exist.\n";
    }

    // Show current status
    $transaction = OutgoingTransaction::with(['items.item'])->find(1);
    $fulfillments = OutgoingFulfillment::where('outgoing_transaction_id', 1)->get();

    echo "\nCurrent Status:\n";
    foreach ($transaction->items as $item) {
        $fulfilled = $fulfillments->where('item_id', $item->item_id)->sum('quantity_fulfilled');
        $remaining = $item->quantity_requested - $fulfilled;
        echo "Item " . $item->item->item_code . ": ";
        echo "Requested=" . $item->quantity_requested . ", ";
        echo "Fulfilled=" . $fulfilled . ", ";
        echo "Remaining=" . $remaining . "\n";
    }

} else {
    echo "Inventory transaction not found.\n";
}