<?php

namespace App\Console\Commands;

use App\Mail\ExpirationProofPaymentMail;
use App\Models\AdminCompany;
use App\Models\ProofPayment;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Mail;

class ExpirationProofPaymentForAdminCommand extends Command
{
    protected $signature = 'expiration:proofPaymentForAdmin';

    protected $description = 'Verificar los comprobantes de pago que vencen mañana.';

    public function handle()
    {
        // Buscar todos los comprobantes de pago activos, son al crédito y vences el siguiente día
        $proofPayments = ProofPayment::where('payment_method', 2)
            ->whereDate('expiration', now()->addDays(1)->toDateString())
            ->whereNull('accepted_iduser')
            ->active()->get();

        // Agrupar por idcompany y contar los registros en cada grupo
        $dataProofPayments = $proofPayments->groupBy('idcompany')->map(function ($group) {
            return [
                'idcompany'     => $group->first()->idcompany,
                'countRegister' => $group->count(),
            ];
        })->values()->toArray();

        foreach ($dataProofPayments as $dataProofPayment) {
            // Obtener data del administrador
            $admin = AdminCompany::where('idcompany', $dataProofPayment['idcompany'])
                ->active()->first();
            $user = User::where('rut', $admin->rut)->first();

            // Enviar correo al administrador
            if ($admin && $user) {
                $username = $user->username;
                $rut_company = $admin->company->rut;
                $password = Crypt::decryptString($user->encrypted_password);;
                $iduser_type = 2;

                $urlProofPayment = "https://www.softnet.cl/v1/auth/login?username=$username&rut_company=$rut_company&password=$password&iduser_type=$iduser_type";

                Mail::to($admin->email)->send(
                    new ExpirationProofPaymentMail(
                        $admin->name . ' ' . $admin->surname,
                        Carbon::parse(now()->addDays(1))->isoFormat('D [de] MMMM [de] YYYY'),
                        $dataProofPayment['countRegister'],
                        $urlProofPayment
                    )
                );
            }
        }
    }
}
