<?php

namespace App\Jobs;

use App\Models\Investment;
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\Log;
use Illuminate\Support\Facades\Mail;

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

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        Log::info("Sending payment reminders");

        // Define reminder intervals in hours
        $reminderIntervals = [24, 48, 72];

        foreach ($reminderIntervals as $hours) {
            $this->sendRemindersForInterval($hours);
        }

        Log::info("Payment reminders completed");
    }

    /**
     * Send reminders for a specific interval
     */
    protected function sendRemindersForInterval(int $hours): void
    {
        $startTime = now()->subHours($hours)->subMinutes(30);
        $endTime = now()->subHours($hours)->addMinutes(30);

        $pendingInvestments = Investment::where('status', 'pending_payment')
            ->where('payment_status', 'pending')
            ->whereBetween('created_at', [$startTime, $endTime])
            ->get();

        foreach ($pendingInvestments as $investment) {
            Log::info("Sending {$hours}h payment reminder for investment {$investment->reference}");

            // In production, send actual reminder email
            // Mail::to($investment->email)->send(new PaymentReminderMail($investment, $hours));

            // Log the reminder
            $investment->emailLogs()->create([
                'email_type' => 'payment_reminder',
                'recipient' => $investment->email,
                'subject' => "Payment Reminder - Complete Your Investment ({$hours}h)",
                'status' => 'sent',
                'sent_at' => now(),
            ]);
        }

        if ($pendingInvestments->count() > 0) {
            Log::info("Sent {$hours}h reminders", [
                'count' => $pendingInvestments->count(),
            ]);
        }
    }
}
