<?php

namespace App\Jobs;

use App\Mailer\DynamicMailConfig;
use Carbon\Carbon;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class SendMail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $data;
    private $email;
    private $view;
    private $table;
    private $field;
    private $subject;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data, $view, $email, $table = null, $field = null, $subject = 'Pendaftaran KONASPI UNESA 2024')
    {
        $this->data = $data;
        $this->view = $view;
        $this->email = $email;
        $this->table = $table;
        $this->field = $field;
        $this->subject = $subject;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try{
            DynamicMailConfig::setConfig();
            $email = $this->email;
            // $email = 'iskandarjava@gmail.com';
            Mail::send($this->view, $this->data, function ($message) use ($email){
                    $message->from('konaspi2024@unesa.ac.id', 'Universitas Negeri Surabaya');
                    $message->sender('konaspi2024@unesa.ac.id', 'Universitas Negeri Surabaya');
                    $message->subject($this->subject);
                    $message->to($email, $email);
                }
            );

            if($this->table && isset($this->data[$this->table])){
                $field = $this->field;
                $this->data[$this->table]->$field = Carbon::now();
                $this->data[$this->table]->save();
            }
        }
        catch(Exception $ex){
            Log::debug($ex);
        }
    }
}
