<?php

namespace App\Jobs;

use App\Mail\RequestLoanMail;
use App\Models\Application\RequestLoan;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Carbon\Carbon;
use Exception;
use stdClass;

class RequestMailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected int $minutes = 10;

    public function handle(): void
    {
        $lastRequest = Cache::get('created_at');

        if (!$lastRequest) {
            return;
        }

        $lastRequestTime = Carbon::parse($lastRequest);
        $diffMinutes = now()->diffInMinutes($lastRequestTime);

        if ($diffMinutes >= $this->minutes) {
            $this->send();
            Cache::forget('created_at');
            Cache::forget('job_id');
        } else {
            $remaining = $this->minutes - $diffMinutes;
            dispatch((new self())->delay(now()->addMinutes($remaining)));
        }
    }

    protected function send()
    {
        $data = new stdClass();

        try {
            $today = now()->format('Y-m-d');
            $requests = RequestLoan::with(['client', 'request_client'])
                ->whereDate('created_at', $today)
                ->where('is_active', 1);

            if (!$requests->exists()) {
                return;
            }

            $data->mail = (object)[
                'subject' => 'Requests created',
                'to' => 'adrian.arellano@outlook.com',
            ];

            $data->requestsCount = $requests->count();
            $data->requests = $requests->get();

            Mail::to($data->mail->to)->send(new RequestLoanMail($data));
        } catch (Exception $e) {
            if ($data->mail->to)
                Mail::raw('Error al enviar el correo: ' . $e->getMessage(), function ($mail) use ($data) {
                    $mail->to($data->mail->to)->subject("Failed to send");
                });
        }
    }
}
