<?php

namespace App\Jobs;

use App\Models\LeadFollowup;
use App\Models\User;
use App\Notifications\LeadUpcomingActivityNotification;
use App\Services\LeadActivityService;
use App\Services\Messaging\Fast2SmsService;
use App\Services\Messaging\WhatsAppService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public function handle(
        Fast2SmsService $smsService,
        WhatsAppService $whatsAppService,
        LeadActivityService $activityService
    ): void {
        $dueFollowups = LeadFollowup::with('lead')
            ->where('status', 'pending')
            ->whereNull('reminder_sent_at')
            ->where('followup_at', '<=', now())
            ->limit(100)
            ->get();

        foreach ($dueFollowups as $followup) {
            $lead = $followup->lead;
            if (! $lead) {
                continue;
            }

            $template = (string) config('lead.fast2sms.followup_template');
            $message = str_replace('{{name}}', $lead->contact_person_name, $template);

            if ($smsService->sendMessage($lead->mobile, $message)) {
                $activityService->log($lead, 'followup_sms_sent', 'Follow-up SMS reminder sent', [
                    'followup_id' => $followup->id,
                ]);
            }

            if ($whatsAppService->sendTemplate($lead->mobile, config('lead.whatsapp.template_followup'), [
                'name' => $lead->contact_person_name,
            ])) {
                $activityService->log($lead, 'followup_whatsapp_sent', 'Follow-up WhatsApp reminder sent', [
                    'followup_id' => $followup->id,
                ]);
            }

            $superAdmins = User::where('is_superadmin', true)->get();
            foreach ($superAdmins as $admin) {
                $admin->notify(new LeadUpcomingActivityNotification($lead, $followup));
            }

            $followup->update(['reminder_sent_at' => now()]);
        }
    }
}
