<?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\ProjectInventory;

try {
    echo "=== Site Return Project ID Fix Script ===" . PHP_EOL;
    echo "Fixing project_id for existing site returns and updating project inventory..." . PHP_EOL . PHP_EOL;

    // Get all site returns that don't have project_id set
    $siteReturns = IncomingOperation::where('operation_type', 'site_return')
        ->whereNull('project_id')
        ->get();

    echo "Found " . $siteReturns->count() . " site returns without project_id..." . PHP_EOL . PHP_EOL;

    $fixedCount = 0;
    $processedInventory = 0;

    foreach ($siteReturns as $siteReturn) {
        $projectId = null;
        $source = '';

        // Try to get project_id from material_request_id
        if ($siteReturn->material_request_id) {
            $materialRequest = DB::table('outgoing_transactions')
                ->where('id', $siteReturn->material_request_id)
                ->first();

            if ($materialRequest && $materialRequest->project_id) {
                $projectId = $materialRequest->project_id;
                $source = "material_request_{$siteReturn->material_request_id}";
            }
        }

        // Try to get project_id from direct_delivery_id if not found
        if (!$projectId && $siteReturn->direct_delivery_id) {
            $directDelivery = DB::table('direct_deliveries')
                ->where('id', $siteReturn->direct_delivery_id)
                ->first();

            if ($directDelivery && $directDelivery->project_id) {
                $projectId = $directDelivery->project_id;
                $source = "direct_delivery_{$siteReturn->direct_delivery_id}";
            }
        }

        if ($projectId) {
            echo "Site Return {$siteReturn->id}: Setting project_id = {$projectId} (from {$source})" . PHP_EOL;

            // Update the site return with correct project_id
            $siteReturn->project_id = $projectId;
            $siteReturn->save();

            // Now process project inventory if the return was completed
            if ($siteReturn->status === 'completed') {
                echo "  Processing project inventory for completed return..." . PHP_EOL;

                foreach ($siteReturn->items as $item) {
                    if ($item->quantity_accepted > 0) {
                        $projectInventory = ProjectInventory::where('project_id', $projectId)
                            ->where('item_id', $item->item_id)
                            ->first();

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

                            echo "    Item {$item->item_id}: {$oldQuantity} - {$item->quantity_accepted} = {$newQuantity}" . PHP_EOL;
                            $processedInventory++;

                            // Remove record if quantity becomes zero or negative
                            if ($projectInventory->quantity_available <= 0) {
                                $projectInventory->delete();
                                echo "    Removed project inventory record (quantity <= 0)" . PHP_EOL;
                            }
                        } else {
                            echo "    No project inventory found for item {$item->item_id}" . PHP_EOL;
                        }
                    }
                }
            }

            $fixedCount++;
        } else {
            echo "Site Return {$siteReturn->id}: Could not determine project_id" . PHP_EOL;
        }
    }

    echo PHP_EOL . "=== Fix Complete ===" . PHP_EOL;
    echo "Site returns fixed: {$fixedCount}" . PHP_EOL;
    echo "Project inventory items processed: {$processedInventory}" . PHP_EOL;

    echo PHP_EOL . "=== Updated Project Inventory Summary ===" . PHP_EOL;
    $projectInventorySummary = ProjectInventory::select(
        'project_id',
        DB::raw('COUNT(*) as item_count'),
        DB::raw('SUM(quantity_available) as total_quantity'),
        DB::raw('SUM(total_value) as total_value')
    )
    ->groupBy('project_id')
    ->orderBy('project_id')
    ->get();

    foreach ($projectInventorySummary as $summary) {
        echo "Project {$summary->project_id}: {$summary->item_count} items, Total Qty: {$summary->total_quantity}, Total Value: " . number_format($summary->total_value, 2) . " AED" . PHP_EOL;
    }

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