<?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\OutgoingTransaction;
use App\Models\Warehouse\ProjectInventory;

// Get the inventory transaction
$transaction = OutgoingTransaction::with('items')->find(2);

echo "Transaction ID: " . $transaction->id . "\n";
echo "Project ID: " . $transaction->project_id . "\n";
echo "Status: " . $transaction->status . "\n\n";

echo "Project Inventory BEFORE manual update:\n";
$beforeInventory = ProjectInventory::where('project_id', $transaction->project_id)->get();
foreach ($beforeInventory as $inv) {
    echo "Item " . $inv->item_id . ": " . $inv->quantity_available . "\n";
}

echo "\nProcessing items:\n";
foreach ($transaction->items as $item) {
    echo "\nItem ID: " . $item->item_id . "\n";
    echo "Quantity Released: " . $item->quantity_released . "\n";
    echo "Project ID: " . $transaction->project_id . "\n";

    if (!$transaction->project_id || $item->quantity_released <= 0) {
        echo "Skipping - no project_id or zero quantity\n";
        continue;
    }

    $projectInventory = ProjectInventory::where('project_id', $transaction->project_id)
        ->where('item_id', $item->item_id)
        ->first();

    if ($projectInventory) {
        echo "Found existing project inventory: " . $projectInventory->quantity_available . "\n";
        $oldQty = $projectInventory->quantity_available;
        $projectInventory->updateQuantity($item->quantity_released, 'add');
        echo "Updated from " . $oldQty . " to " . $projectInventory->quantity_available . "\n";
    } else {
        echo "Creating new project inventory record\n";
        $newInventory = ProjectInventory::create([
            'project_id' => $transaction->project_id,
            'item_id' => $item->item_id,
            'quantity_available' => $item->quantity_released,
            'allocated_quantity' => 0,
            'unit_price' => $item->unit_price ?: 0,
            'total_value' => $item->quantity_released * ($item->unit_price ?: 0)
        ]);
        echo "Created new record with quantity: " . $newInventory->quantity_available . "\n";
    }
}

echo "\nProject Inventory AFTER manual update:\n";
$afterInventory = ProjectInventory::where('project_id', $transaction->project_id)->get();
foreach ($afterInventory as $inv) {
    echo "Item " . $inv->item_id . ": " . $inv->quantity_available . "\n";
}