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

try {
    echo "=== Project Inventory Sync Script ===" . PHP_EOL;
    echo "Starting sync of existing outgoing transactions to project inventory..." . PHP_EOL . PHP_EOL;

    // Get all successful outgoing transactions with items
    $outgoingTransactions = DB::table('outgoing_transactions')
        ->join('outgoing_items', 'outgoing_transactions.id', '=', 'outgoing_items.outgoing_transaction_id')
        ->select(
            'outgoing_transactions.id as transaction_id',
            'outgoing_transactions.project_id',
            'outgoing_transactions.material_request_number',
            'outgoing_transactions.transaction_date',
            'outgoing_items.item_id',
            'outgoing_items.quantity_released',
            'outgoing_items.unit_price'
        )
        ->where('outgoing_transactions.status', 'successful')
        ->where('outgoing_items.quantity_released', '>', 0)
        ->whereNotNull('outgoing_transactions.project_id')
        ->orderBy('outgoing_transactions.project_id')
        ->orderBy('outgoing_items.item_id')
        ->get();

    echo "Found " . $outgoingTransactions->count() . " outgoing items to sync..." . PHP_EOL . PHP_EOL;

    if ($outgoingTransactions->isEmpty()) {
        echo "No outgoing transactions found to sync." . PHP_EOL;
        exit;
    }

    $processedCount = 0;
    $createdRecords = 0;
    $updatedRecords = 0;
    $currentProject = null;
    $currentItem = null;

    foreach ($outgoingTransactions as $transaction) {
        if ($currentProject !== $transaction->project_id) {
            echo PHP_EOL . "--- Processing Project ID: {$transaction->project_id} ---" . PHP_EOL;
            $currentProject = $transaction->project_id;
            $currentItem = null;
        }

        if ($currentItem !== $transaction->item_id) {
            echo "Processing Item ID: {$transaction->item_id}" . PHP_EOL;
            $currentItem = $transaction->item_id;
        }

        // Check if project inventory record exists
        $projectInventory = ProjectInventory::where('project_id', $transaction->project_id)
            ->where('item_id', $transaction->item_id)
            ->first();

        if ($projectInventory) {
            // Update existing record
            $oldQuantity = $projectInventory->quantity_available;
            $projectInventory->updateQuantity($transaction->quantity_released, 'add');
            $newQuantity = $projectInventory->quantity_available;

            echo "  - Updated: Qty {$oldQuantity} + {$transaction->quantity_released} = {$newQuantity}" . PHP_EOL;
            $updatedRecords++;
        } else {
            // Create new record
            $projectInventory = ProjectInventory::create([
                'project_id' => $transaction->project_id,
                'item_id' => $transaction->item_id,
                'quantity_available' => $transaction->quantity_released,
                'allocated_quantity' => 0,
                'unit_price' => $transaction->unit_price ?: 0,
                'total_value' => $transaction->quantity_released * ($transaction->unit_price ?: 0)
            ]);

            echo "  - Created: Qty {$transaction->quantity_released} @ Price " . ($transaction->unit_price ?: 0) . PHP_EOL;
            $createdRecords++;
        }

        $processedCount++;
    }

    echo PHP_EOL . "=== Sync Complete ===" . PHP_EOL;
    echo "Total items processed: {$processedCount}" . PHP_EOL;
    echo "New project inventory records created: {$createdRecords}" . PHP_EOL;
    echo "Existing records updated: {$updatedRecords}" . PHP_EOL;

    // Display summary of project inventory after sync
    echo PHP_EOL . "=== 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;
    }

    echo PHP_EOL . "=== Detailed Project Inventory ===" . PHP_EOL;
    $detailedInventory = ProjectInventory::select(
        'project_id',
        'item_id',
        'quantity_available',
        'unit_price',
        'total_value'
    )
    ->orderBy('project_id')
    ->orderBy('item_id')
    ->get();

    $currentProjectDetail = null;
    foreach ($detailedInventory as $detail) {
        if ($currentProjectDetail !== $detail->project_id) {
            echo PHP_EOL . "Project {$detail->project_id}:" . PHP_EOL;
            $currentProjectDetail = $detail->project_id;
        }
        echo "  Item {$detail->item_id}: Qty {$detail->quantity_available} @ {$detail->unit_price} = {$detail->total_value} AED" . PHP_EOL;
    }

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