<?php

namespace App\Console\Commands;

use App\Models\Customer;
use App\Models\Sale;
use App\Models\Purchase;
use App\Models\MonyImport;
use App\Models\MonyExport;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;

class UpdateCustomerInitialBalance extends Command
{
    protected $signature = 'customers:update-initial-balance {--date= : End date for balance calculation (Y-m-d)}';
    protected $description = 'Update customer initial balance (first_mony) based on their final balance';

    public function handle(): int
    {
        $toDate = $this->option('date') ? Carbon::createFromFormat('Y-m-d', $this->option('date')) : now();
        
        $this->info("📊 جاري تحديث الأرصدة الأولية للعملاء حتى: {$toDate->format('Y-m-d')}");
        $this->newLine();

        $customers = Customer::all();
        $progressBar = $this->output->createProgressBar(count($customers));
        $progressBar->start();

        foreach ($customers as $customer) {
            $balance = $customer->first_mony ?? 0;

            // Calculate all transactions until the specified date
            $salesTotal = Sale::where('customer_id', $customer->id)
                ->where('date', '<=', $toDate)
                ->with('products')
                ->get()
                ->reduce(fn($carry, $sale) => $carry + $sale->products->sum('pivot.total'), 0);

            $purchasesTotal = Purchase::where('customer_id', $customer->id)
                ->where('date', '<=', $toDate)
                ->with('products')
                ->get()
                ->reduce(fn($carry, $purchase) => $carry + $purchase->products->sum('pivot.total'), 0);

            $monyImportsTotal = MonyImport::where('customer_id', $customer->id)
                ->where('date', '<=', $toDate)
                ->sum('value');

            $monyExportsTotal = MonyExport::where('customer_id', $customer->id)
                ->where('date', '<=', $toDate)
                ->sum('value');

            // Calculate final balance
            $finalBalance = $balance + $salesTotal - $purchasesTotal + $monyImportsTotal - $monyExportsTotal;

            // Update first_mony with the final balance
            $customer->update(['first_mony' => $finalBalance]);

            $progressBar->advance();
        }

        $progressBar->finish();
        $this->newLine();
        $this->info("✅ تم تحديث أرصدة جميع العملاء بنجاح!");
        
        return self::SUCCESS;
    }
}
