<?php

namespace Database\Seeders;

use App\Models\Application;
use Illuminate\Database\Seeder;

class ApplicationSeeder extends Seeder
{
    public function run(): void
    {
        $names = ['María Fernanda Rojas','Carlos Andrés Muñoz','Paula Andrea González','Jorge Luis Araya','Camila Paz Soto','Rodrigo Esteban Díaz','Valentina Ignacia Tapia','Felipe Alejandro Contreras','Daniela Alejandra Silva','Cristóbal Antonio Pérez','Francisca Belén López','Sebastián Ignacio Morales','Andrea Carolina Núñez','Matías Eduardo Castillo','Alejandra del Carmen Vega','Nicolás Javier Fuentes','Carolina Isabel Ramírez','Diego Andrés Herrera'];
        $statuses = ['pending','review','approved','rejected'];

        foreach ($names as $index => $name) {
            $type = $index % 3 === 0 ? 'radomiro' : 'particular';
            $rut = $this->rut(12_345_670 + ($index * 137));
            $date = now()->subDays($index * 2 + 1);
            $data = [
                'application_date' => $date->format('Y-m-d'),
                'full_name' => $name,
                'rut' => $rut,
                'birth_date' => now()->subYears(28 + ($index % 24))->subDays($index * 17)->format('Y-m-d'),
                'email' => 'socio'.($index + 1).'@ejemplo.cl',
                'address' => 'Avenida Granaderos '.(1200 + $index * 23).', Calama',
                'phone' => '+56 9 '.str_pad((string) (61000000 + $index * 7311), 8, '0', STR_PAD_LEFT),
                'delivery_address' => 'Casilla C.C.R. '.($index + 10).', Calama',
                'profession' => ['Ingeniero/a','Técnico/a','Administrativo/a','Operador/a'][$index % 4],
                'work_area' => ['Operaciones','Mantenimiento','Administración','Seguridad'][$index % 4],
                'superintendency' => 'Superintendencia '.chr(65 + ($index % 4)),
                'work_phone' => '+56 55 234 '.str_pad((string) (1000 + $index), 4, '0', STR_PAD_LEFT),
                'management' => ['Operaciones Mina','Recursos Humanos','Servicios','Procesos'][$index % 4],
                'work_email' => 'trabajador'.($index + 1).'@empresa.cl',
                'payment_amount' => $type === 'particular' ? '$ '.number_format(25000 + $index * 1000, 0, ',', '.') : '',
                'receipt_number' => $type === 'particular' ? 'COMP-'.str_pad((string) ($index + 1), 5, '0', STR_PAD_LEFT) : '',
                'first_payment_date' => $type === 'particular' ? $date->copy()->addDays(2)->format('Y-m-d') : '',
                'dependents' => [[
                    'id' => 'seed-dependent-'.$index,
                    'full_name' => 'Carga Familiar '.($index + 1),
                    'rut' => $this->rut(18_100_000 + $index * 53),
                    'birth_date' => now()->subYears(8 + ($index % 10))->format('Y-m-d'),
                    'relationship' => $index % 2 ? 'Hijo/a' : 'Cónyuge',
                ]],
                'recommender_name' => 'Socio Recomendante C.C.R.',
                'recommender_rut' => '10.239.124-3',
                'board_members' => [['id' => 'seed-board-'.$index, 'name' => 'Consejero de turno', 'rut' => '9.876.543-3', 'signature' => '']],
                'signature_date' => $date->copy()->addDays(3)->format('Y-m-d'),
            ];

            Application::updateOrCreate(['folio' => 'CCR-DEMO-'.str_pad((string) ($index + 1), 4, '0', STR_PAD_LEFT)], [
                'type' => $type,
                'status' => $statuses[$index % count($statuses)],
                'full_name' => $name,
                'rut' => $rut,
                'email' => $data['email'],
                'phone' => $data['phone'],
                'application_date' => $date,
                'data' => $data,
                'attachments' => [],
                'admin_notes' => $index % 4 === 1 ? 'Antecedentes revisados. Pendiente de validación final.' : null,
                'created_at' => $date,
                'updated_at' => $date,
            ]);
        }
    }

    private function rut(int $number): string
    {
        $sum = 0; $multiplier = 2;
        foreach (array_reverse(str_split((string) $number)) as $digit) {
            $sum += ((int) $digit) * $multiplier;
            $multiplier = $multiplier === 7 ? 2 : $multiplier + 1;
        }
        $result = 11 - ($sum % 11);
        $dv = $result === 11 ? '0' : ($result === 10 ? 'K' : (string) $result);
        return number_format($number, 0, ',', '.').'-'.$dv;
    }
}
