<?php

require_once __DIR__ . '/vendor/autoload.php';

$app = require_once __DIR__ . '/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

use Illuminate\Support\Facades\DB;
use App\Models\Warehouse\IncomingOperation;
use App\Models\Warehouse\OutgoingTransaction;
use App\Models\Warehouse\ProjectInventory;

try {
    echo "=== Fix Material Request Returns - Project Inventory Update ===" . PHP_EOL;
    echo "Processing completed material request returns..." . PHP_EOL . PHP_EOL;

    DB::beginTransaction();

    // Find all completed material request returns
    $materialReturns = IncomingOperation::where('operation_type', 'site_return')
        ->where('status', 'completed')
        ->whereNotNull('material_request_id')
        ->with('items')
        ->get();

    echo "Found " . $materialReturns->count() . " material request returns to process:" . PHP_EOL . PHP_EOL;

    $processedReturns = 0;
    $totalItemsProcessed = 0;

    foreach ($materialReturns as $return) {
        echo "Processing Return ID: {$return->id}" . PHP_EOL;
        echo "  Material Request ID: {$return->material_request_id}" . PHP_EOL;

        // Get the original material request to find the project
        $materialRequest = OutgoingTransaction::find($return->material_request_id);

        if (!$materialRequest) {
            echo "  ERROR: Material request {$return->material_request_id} not found" . PHP_EOL;
            continue;
        }

        $targetProjectId = $materialRequest->project_id;
        echo "  Target Project ID: {$targetProjectId}" . PHP_EOL;

        if (!$targetProjectId) {
            echo "  WARNING: Material request has no project_id - skipping" . PHP_EOL;
            continue;
        }

        foreach ($return->items as $item) {
            echo "  Processing Item ID: {$item->item_id} ({$item->item->item_description})" . PHP_EOL;
            echo "    Quantity to subtract: {$item->quantity_accepted}" . PHP_EOL;

            // Find project inventory for this item
            $projectInventory = ProjectInventory::where('project_id', $targetProjectId)
                ->where('item_id', $item->item_id)
                ->first();

            if ($projectInventory) {
                $oldQuantity = $projectInventory->quantity_available;

                if ($oldQuantity >= $item->quantity_accepted) {
                    $projectInventory->updateQuantity($item->quantity_accepted, 'subtract');
                    $newQuantity = $projectInventory->quantity_available;

                    echo "    Updated: {$oldQuantity} - {$item->quantity_accepted} = {$newQuantity}" . PHP_EOL;

                    if ($projectInventory->quantity_available <= 0) {
                        $projectInventory->delete();
                        echo "    Deleted inventory record (quantity = 0)" . PHP_EOL;
                    }
                } else {
                    echo "    WARNING: Not enough inventory ({$oldQuantity}) to subtract {$item->quantity_accepted}" . PHP_EOL;
                    // Subtract what's available
                    $projectInventory->updateQuantity($oldQuantity, 'subtract');
                    echo "    Subtracted available quantity: {$oldQuantity}" . PHP_EOL;
                    $projectInventory->delete();
                    echo "    Deleted inventory record (quantity = 0)" . PHP_EOL;
                }

                $totalItemsProcessed++;
            } else {
                echo "    WARNING: No project inventory found for item {$item->item_id} in project {$targetProjectId}" . PHP_EOL;
            }
        }

        $processedReturns++;
        echo PHP_EOL;
    }

    DB::commit();

    echo "=== Processing Complete ===" . PHP_EOL;
    echo "Returns processed: {$processedReturns}" . PHP_EOL;
    echo "Items processed: {$totalItemsProcessed}" . PHP_EOL;

    // Show updated project inventory for affected projects
    echo PHP_EOL . "=== Updated Project Inventories ===" . PHP_EOL;

    $affectedProjects = $materialReturns->map(function($return) {
        $mr = OutgoingTransaction::find($return->material_request_id);
        return $mr ? $mr->project_id : null;
    })->filter()->unique();

    foreach ($affectedProjects as $projectId) {
        $projectItems = ProjectInventory::where('project_id', $projectId)
            ->with(['item', 'project'])
            ->get();

        $project = $projectItems->first();
        echo "Project: " . ($project ? $project->project->project_name : "ID {$projectId}") . PHP_EOL;

        if ($projectItems->count() > 0) {
            foreach ($projectItems as $item) {
                echo "  {$item->item->item_description}: {$item->quantity_available} units" . PHP_EOL;
            }
        } else {
            echo "  No items remaining in inventory" . PHP_EOL;
        }
        echo PHP_EOL;
    }

} catch (Exception $e) {
    DB::rollback();
    echo "Error: " . $e->getMessage() . PHP_EOL;
    echo "Trace: " . $e->getTraceAsString() . PHP_EOL;
}