<?php

namespace App\Console\Commands;

use App\Models\Order;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class FixDonorPortfolioAllocatedAmounts extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fix:donor-portfolio-amounts {--from-id=1 : Starting order ID to process from}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix allocated amounts in donor portfolio orders by setting them to the offer price from order finance';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $fromId = $this->option('from-id');

        $this->info("Starting to fix donor portfolio allocated amounts for orders from ID: {$fromId}");

        try {
            // Get orders that have donor portfolios linked and order finances
            $orders = Order::where('id', '>=', $fromId)
                // ->whereHas('donorFinancialPortfolios')
                // ->whereHas('finance')
                // ->with(['donorFinancialPortfolios', 'finance'])
                ->get();

            if ($orders->isEmpty()) {
                $this->info('No orders found with donor portfolios and order finance from the specified ID.');

                return Command::SUCCESS;
            }

            $this->info("Found {$orders->count()} orders to process");

            $updated = 0;
            $skipped = 0;
            $errors = 0;

            foreach ($orders as $order) {
                try {
                    // Get the order finance record (singular relationship)
                    $orderFinance = $order->finance;

                    if (! $orderFinance || ! $orderFinance->offer_price) {
                        $this->warn("Order ID {$order->id}: No order finance with offer price found - skipping");
                        $skipped++;

                        continue;
                    }
                    $offerPrice = $orderFinance->offer_price;

                    // Update all donor portfolio relationships for this order
                    foreach ($order->donorFinancialPortfolios as $portfolio) {
                        $currentAmount = $portfolio->pivot->allocated_amount;

                        if ($currentAmount == 0) {
                            // Update the pivot table
                            DB::table('donor_portfolio_order')
                                ->where('order_id', $order->id)
                                ->where('donor_financial_portfolio_id', $portfolio->id)
                                ->update([
                                    'allocated_amount' => $offerPrice,
                                    'updated_at' => now(),
                                ]);

                            $this->info("Order ID {$order->id}: Updated portfolio '{$portfolio->name}' allocated amount from {$currentAmount} to {$offerPrice}");
                            $updated++;
                        } else {
                            $this->comment("Order ID {$order->id}: Portfolio '{$portfolio->name}' already has allocated amount {$currentAmount} - skipping");
                            $skipped++;
                        }
                    }
                } catch (\Exception $e) {
                    $this->error("Order ID {$order->id}: Error - {$e->getMessage()}");
                    $errors++;
                }
            }

            $this->info("\nUpdate completed!");
            $this->info("Updated: {$updated} portfolio allocations");
            $this->info("Skipped: {$skipped} (already had amounts or no offer price)");

            if ($errors > 0) {
                $this->warn("Errors: {$errors}");
            }

            return Command::SUCCESS;
        } catch (\Exception $e) {
            $this->error('Failed to process orders: '.$e->getMessage());

            return Command::FAILURE;
        }
    }
}
