<?php

namespace App\Jobs;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use App\Models\Message;
use App\Mail\SendMultiMails;
use App\Models\DataExcel;

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

    public $tries = 3;
    public $timeout = 60;

    public function __construct(
        public string $senderName,
        public string $sendermail,
        public string $recievermail,
        public string $content,
        public string $subject,
        public Message $message
    ) {}

    public function handle(): void
    {
        $sender = \App\Models\Sender::where('email', $this->sendermail)->first();

        if (!$sender) {
            $this->markFailed("Sender not found");
            return;
        }

        // ✅ dynamic SMTP
        $this->setMailConfig($sender);

        try {
            $clickUrl = route('track.click', [
                'id' => $this->message->id,
                'url' => 'https://aitech.net.au/AiTech-Profile.pdf'
            ]);

            $openUrl = route('track.open', ['id' => $this->message->id]);

            Mail::to($this->recievermail)->send(
                new SendMultiMails(
                    $sender->name,
                    $sender->email,
                    $this->recievermail,
                    $this->content,
                    $this->subject,
                    $this->message,
                    $this->message->file,
                    $clickUrl,
                    $openUrl
                )
            );

            DataExcel::where('email', $this->recievermail)
                ->where('message_id', $this->message->id)
                ->update(['status' => 'sent']);

        } catch (\Throwable $e) {
            Log::error("Send failed: {$this->recievermail} → " . $e->getMessage());

            DataExcel::where('email', $this->recievermail)
                ->where('message_id', $this->message->id)
                ->update(['status' => 'failed']);

            throw $e; // علشان retry
        }
    }

private function setMailConfig($sender)
{
    config([
        'mail.mailers.smtp.host'       => 'smtp.gmail.com',
        'mail.mailers.smtp.port'       => 587,
        'mail.mailers.smtp.username'   => $sender->email,
        'mail.mailers.smtp.password'   => $sender->password,
        'mail.mailers.smtp.encryption' => $sender->smtp_encryption ?? 'tls', 
        'mail.from.address'            => $sender->email,
        'mail.from.name'               => $sender->name,
    ]);

    app()->forgetInstance('mailer');
}


    private function markFailed(string $reason)
    {
        Log::error($reason);

        DataExcel::where('email', $this->recievermail)
            ->where('message_id', $this->message->id)
            ->update(['status' => 'failed']);
    }
}












