<?php

namespace App\Console\Commands;

use App\Mail\MembershipExpiredMail;
use App\Models\Company;
use App\Models\DetailMembershipPayment;
use App\Models\Url;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Mail;

class ReminderMembershipExpiredEvent extends Command
{
    protected $signature = 'membership:expired';

    protected $description = 'Recuerda el pago de su membresia 5 días antes de ser cumplido';

    public function handle()
    {
        # 5 días antes de la expiración
        $dateNow = Carbon::now()->addDays(5)->toDateString();
        $expiratonNow = DetailMembershipPayment::whereDate('payment_date_end', $dateNow)
            ->where('status', 1)->where('status_page', 1)->get();

        if ($expiratonNow->isNotEmpty()) $this->sendNotification($expiratonNow);
    }

    public function sendNotification($data)
    {
        $urlBase =  Url::find(2)->url . Url::find(5)->url;

        foreach ($data as $row) {

            $idcompany = $row->idcompany;

            #Datos para el correo
            $admin = User::where('idcompany', $idcompany)->active()
                ->whereHas('detailUser', function ($q) use ($idcompany) {
                    $q->where('iduser_type', 2)->where('idcompany', $idcompany)->active();
                })->first();

            if ($admin) {
                $company = Company::find($idcompany);

                $rut_company    = base64_encode($company->rut);
                $username       = base64_encode($admin->username);
                $rut            = base64_encode($admin->rut);
                $password       = base64_encode(Crypt::decryptString($admin->encrypted_password));
                $iduser_type    = base64_encode(2);
                $webRenovation  = $urlBase . "/?rut_company=$rut_company&username=$username&rut=$rut&password=$password&iduser_type=$iduser_type";

                #Enviar correo al usuario correspondiente para decirle que su membresía vence hoy
                Mail::to($admin->email)->send(new MembershipExpiredMail(
                    "$admin->username",   # Nombre del administrador
                    $webRenovation,                     # URL de renovación
                ));
            }
        }
    }
}
