<?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\IncomingOperationItem;
use App\Models\DirectDelivery;
use App\Models\DirectDeliveryItem;

try {
    echo "=== Fix DD-202511-0006 Return Linkage Script ===" . PHP_EOL;
    echo "Linking laptop returns to direct delivery DD-202511-0006..." . PHP_EOL . PHP_EOL;

    // Get the direct delivery
    $directDelivery = DirectDelivery::where('delivery_number', 'DD-202511-0006')->first();
    if (!$directDelivery) {
        echo "ERROR: Direct delivery DD-202511-0006 not found!" . PHP_EOL;
        exit;
    }

    echo "Found Direct Delivery: {$directDelivery->delivery_number} (ID: {$directDelivery->id})" . PHP_EOL;
    echo "Project ID: {$directDelivery->project_id}" . PHP_EOL . PHP_EOL;

    // Get the laptop item from the direct delivery
    $laptopDeliveryItem = $directDelivery->items()->where('item_id', 1)->first();
    if (!$laptopDeliveryItem) {
        echo "ERROR: Laptop item not found in direct delivery!" . PHP_EOL;
        exit;
    }

    echo "Found Laptop Delivery Item (ID: {$laptopDeliveryItem->id})" . PHP_EOL;
    echo "Delivered Quantity: {$laptopDeliveryItem->delivered_quantity}" . PHP_EOL;
    echo "Current Returned Quantity: {$laptopDeliveryItem->returned_quantity}" . PHP_EOL . PHP_EOL;

    // Find site returns with laptop items that have NULL project_id and NULL direct_delivery_id
    $orphanedReturns = IncomingOperation::where('operation_type', 'site_return')
        ->where('status', 'completed')
        ->whereNull('project_id')
        ->whereNull('direct_delivery_id')
        ->whereHas('items', function($query) {
            $query->where('item_id', 1) // laptop item
                  ->where('quantity_accepted', '>', 0);
        })
        ->with('items')
        ->get();

    echo "Found {$orphanedReturns->count()} orphaned laptop returns to fix:" . PHP_EOL;

    $totalReturnedQuantity = 0;
    $fixedReturns = 0;

    DB::beginTransaction();

    foreach ($orphanedReturns as $return) {
        echo "Return ID: {$return->id}, Date: {$return->operation_date}" . PHP_EOL;

        // Update the return operation to link to the direct delivery
        $return->update([
            'project_id' => $directDelivery->project_id,
            'direct_delivery_id' => $directDelivery->id
        ]);

        foreach ($return->items as $item) {
            if ($item->item_id == 1) { // laptop item
                echo "  Item - Quantity Accepted: {$item->quantity_accepted}" . PHP_EOL;

                // Update the item to link to the direct delivery item
                $item->update([
                    'direct_delivery_item_id' => $laptopDeliveryItem->id
                ]);

                $totalReturnedQuantity += $item->quantity_accepted;
            }
        }

        $fixedReturns++;
        echo "  ✓ Fixed return linkage" . PHP_EOL . PHP_EOL;
    }

    // Now update the direct delivery item's returned_quantity
    echo "Updating direct delivery item returned quantity..." . PHP_EOL;
    echo "Total returned quantity from orphaned returns: {$totalReturnedQuantity}" . PHP_EOL;
    echo "Delivered quantity: {$laptopDeliveryItem->delivered_quantity}" . PHP_EOL;

    if ($totalReturnedQuantity > $laptopDeliveryItem->delivered_quantity) {
        echo "WARNING: Total returned quantity exceeds delivered quantity!" . PHP_EOL;
        echo "This suggests duplicate or invalid returns. Only updating up to delivered quantity." . PHP_EOL;

        // Set returned_quantity to the maximum delivered quantity
        $maxReturnQuantity = $laptopDeliveryItem->delivered_quantity;
        $laptopDeliveryItem->update([
            'returned_quantity' => $maxReturnQuantity,
            'can_be_returned' => false
        ]);

        echo "  Set returned_quantity to {$maxReturnQuantity} (max possible)" . PHP_EOL;
    } else {
        // Use the recordReturn method for each quantity
        foreach ($orphanedReturns as $return) {
            foreach ($return->items as $item) {
                if ($item->item_id == 1) {
                    try {
                        $laptopDeliveryItem->recordReturn($item->quantity_accepted);
                        echo "  Recorded return of {$item->quantity_accepted} units" . PHP_EOL;
                    } catch (Exception $e) {
                        echo "  WARNING: Could not record return of {$item->quantity_accepted} units: " . $e->getMessage() . PHP_EOL;
                        break 2; // Break out of both loops
                    }
                }
            }
        }
    }

    DB::commit();

    echo PHP_EOL . "=== Fix Complete ===" . PHP_EOL;
    echo "Returns fixed: {$fixedReturns}" . PHP_EOL;
    echo "Total returned quantity: {$totalReturnedQuantity}" . PHP_EOL;

    // Show final status
    $laptopDeliveryItem->refresh();
    echo PHP_EOL . "=== Final Status ===" . PHP_EOL;
    echo "Laptop Delivery Item (DD-202511-0006):" . PHP_EOL;
    echo "  Delivered Quantity: {$laptopDeliveryItem->delivered_quantity}" . PHP_EOL;
    echo "  Returned Quantity: {$laptopDeliveryItem->returned_quantity}" . PHP_EOL;
    echo "  Available for Return: {$laptopDeliveryItem->getAvailableForReturnQuantity()}" . PHP_EOL;
    echo "  Can be returned: " . ($laptopDeliveryItem->can_be_returned ? 'Yes' : 'No') . PHP_EOL;

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