<?php

namespace Database\Seeders;

use App\Models\Credit;
use App\Models\Installment;
use Illuminate\Database\Seeder;
use Illuminate\Support\Carbon;

class CreditSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // El listado de créditos con la CUOTA TOTAL (última columna) incluida.
        $creditsData = [
            // company_id, client_id, collector_user_id, created_by_user_id, status, amount, interest_rate, installments_count, periodicity, date, due_day_1, due_day_2, cuota
            [1, 1, 3, 2, 'active', 1000000, 10, 8, 'weekly', '10/2/2025', 4, null, 150000],
            [1, 2, 3, 2, 'active', 600000, 20, 10, 'weekly', '10/2/2025', 4, null, 84000],
            [1, 3, 3, 2, 'active', 400000, 20, 4, 'biweekly', '10/2/2025', 15, 30, 140000],
            [1, 4, 3, 2, 'active', 2000000, 10, 8, 'weekly', '10/2/2025', 4, null, 300000],
            [1, 5, 3, 2, 'active', 800000, 10, 6, 'weekly', '10/3/2025', 1, null, 160000],
            [1, 6, 3, 2, 'active', 1000000, 10, 6, 'biweekly', '10/3/2025', 15, 30, 234000],
            [1, 7, 3, 2, 'active', 500000, 10, 3, 'biweekly', '10/3/2025', 5, 20, 200000],
            [1, 8, 3, 2, 'active', 1000000, 10, 4, 'biweekly', '10/4/2025', 15, 30, 300000],
            [1, 9, 3, 2, 'active', 400000, 20, 1, 'monthly', '10/6/2025', 6, null, 480000],
            [1, 10, 3, 2, 'active', 200000, 20, 1, 'monthly', '10/8/2025', 31, null, 240000],
            [1, 11, 3, 2, 'active', 2000000, 10, 8, 'biweekly', '10/8/2025', 15, null, 350000],
            [1, 12, 3, 2, 'active', 250000, 12, 1, 'biweekly', '10/13/2025', 30, null, 280000],
            [1, 13, 3, 2, 'active', 700000, 20, 6, 'weekly', '10/14/2025', 6, null, 140000],
            [1, 14, 3, 2, 'active', 1000000, 10, 8, 'weekly', '10/14/2025', 4, null, 150000],
            [1, 15, 3, 2, 'active', 600000, 20, 6, 'weekly', '10/15/2025', 5, null, 120000],
            [1, 16, 3, 2, 'active', 1000000, 10, 13, 'weekly', '10/15/2025', 7, null, 100000],
            [1, 17, 3, 2, 'active', 1000000, 10, 6, 'weekly', '10/17/2025', 5, null, 200000],
            [1, 18, 3, 2, 'active', 150000, 20, 4, 'weekly', '10/19/2025', 7, null, 45000],
            [1, 19, 3, 2, 'active', 300000, 20, 3, 'biweekly', '10/19/2025', 15, 30, 130000],
            [1, 20, 3, 2, 'active', 800000, 20, 6, 'weekly', '10/20/2025', 1, null, 160000],
            [1, 21, 3, 2, 'active', 100000, 20, 2, 'biweekly', '10/23/2025', 15, 30, 60000],
            [1, 22, 3, 2, 'active', 500000, 20, 10, 'weekly', '10/23/2025', 4, null, 70000],
            [1, 23, 3, 2, 'active', 1000000, 10, 8, 'weekly', '10/24/2025', 5, null, 150000],
            [1, 24, 3, 2, 'active', 150000, 20, 4, 'biweekly', '10/25/2025', 15, 30, 52500],
            [1, 25, 3, 2, 'active', 800000, 20, 1, 'monthly', '10/27/2025', 27, null, 960000],
        ];

        foreach ($creditsData as $data) {
            [
                $company_id, $client_id, $collector_user_id, $created_by_user_id, $status,
                $amount, $interest_rate, $installments_count, $periodicity, $start_date_str,
                $due_day_1, $due_day_2, $total_installment_amount // <-- Nuevo dato
            ] = $data;

            // Convertir la fecha a objeto Carbon
            // Nota: Asumiendo que la fecha de desembolso (start_date) es 10/2/2025 (MM/DD/YYYY)
            $start_date = Carbon::createFromFormat('m/d/Y', $start_date_str)->startOfDay();

            // 1. CREAR EL CRÉDITO
            $credit = Credit::create([
                'company_id' => $company_id,
                'client_id' => $client_id,
                'collector_user_id' => $collector_user_id,
                'created_by_user_id' => $created_by_user_id,
                'status' => $status,
                'amount' => $amount,
                'interest_rate' => $interest_rate,
                'installments_count' => $installments_count,
                'periodicity' => $periodicity,
                'start_date' => $start_date,
                'due_day_1' => $due_day_1,
                'due_day_2' => $due_day_2,
            ]);

            // 2. CALCULAR MONTOS A DISTRIBUIR
            $totalRepay = $total_installment_amount * $installments_count;
            $totalInterest = $totalRepay - $amount;

            // Distribución por cuota (lineal y exacta)
            $principalPerInstallment = round($amount / $installments_count, 2);
            $interestPerInstallment = round($totalInterest / $installments_count, 2);

            // Re-calculamos el totalPerInstallment después del redondeo para evitar inconsistencias
            $totalPerInstallment = $principalPerInstallment + $interestPerInstallment;

            // Variables de saldo
            $remainingPrincipal = $amount;
            $remainingInterest = $totalInterest;
            $currentDueDate = $start_date->copy();

            // 3. GENERAR CUOTAS
            for ($i = 1; $i <= $installments_count; $i++) {

                // --- Determinar la fecha de vencimiento (due_date) ---
                $dueDate = match ($periodicity) {
                    'daily' => $currentDueDate->addDay(),
                    'weekly' => $currentDueDate->addWeek(),
                    'biweekly' => $currentDueDate->addWeeks(2),
                    'monthly' => $currentDueDate->addMonth(),
                    default => $currentDueDate->addDay(), // Fallback
                };

                // --- Cálculo de la cuota (Ajuste de redondeo en la última cuota) ---
                $currentPrincipal = $principalPerInstallment;
                $currentInterest = $interestPerInstallment;
                $currentTotal = $total_installment_amount;

                // Aplicar ajuste de redondeo a la ÚLTIMA cuota
                if ($i === $installments_count) {
                    // El capital restante (ajusta el redondeo)
                    $currentPrincipal = $remainingPrincipal;
                    // El interés restante
                    $currentInterest = $remainingInterest;
                    // La cuota total es la suma de los valores ajustados
                    $currentTotal = $currentPrincipal + $currentInterest;
                }

                // Asegurar que el total sea el valor de la cuota dada para las cuotas intermedias
                if ($i < $installments_count) {
                    $currentTotal = $total_installment_amount;
                    // Forzamos que la suma de Principal + Interés sea igual a la cuota total
                    // (Esto es menos preciso para la distribución lineal pero más fiel al dato de la tabla)
                    // Si el cliente usa el dato de la cuota para la tabla, este es el enfoque:
                    // Distribuimos el capital y el interés para que sumen el total,
                    // y el ajuste final se hace en la última cuota.
                    $currentPrincipal = round($amount / $installments_count, 2);
                    $currentInterest = $currentTotal - $currentPrincipal;
                }

                // Actualizar saldos pendientes para el próximo cálculo/ajuste final
                $remainingPrincipal -= $currentPrincipal;
                $remainingInterest -= $currentInterest;

                // Crear la cuota
                Installment::create([
                    'credit_id' => $credit->id,
                    'installment_number' => $i,
                    'status' => 'pending',
                    'due_date' => $dueDate,
                    'principal_amount' => $currentPrincipal,
                    'interest_amount' => $currentInterest,
                    'total_amount' => $currentTotal,
                    'principal_balance_after' => round($remainingPrincipal > 0 ? $remainingPrincipal : 0, 2),
                    'amount_paid' => 0.00,
                ]);
            }
        }

        $this->command->info('25 Créditos y sus cuotas (usando el monto de cuota fijo) creados exitosamente.');
    }
}
