<?php

namespace App\Jobs;

use Carbon\Carbon;
use App\Models\MailLog;
use App\Mail\InvoiceSend;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;

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

    /**
     * Create a new job instance.
     *
     * @return void
     */

    public $data;
    public $client;
    public function __construct($data, $client)
    {
        $this->data = $data;
        $this->client = $client;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        $setting = json_decode(emailSetting()->where('tamplate_name', 'bill_generate_eamil')->first()->email_body);
        $bill = $this->data['bill'];

        $message = str_replace(
            [
                '{c_id}',
                '{c_username}',
                '{c_name}',
                '{c_deadline}',
                '{TotalDue}',
                '{company_name}',
                '{company_cell}',
                '{MonthBillAmount}',
                '{bill_type}',
                '{ThisMonth}',
                '{billing_deadline}',
                '{bill_generate_month}'

            ],
            [
                $this->client->id,
                $this->client->userid,
                $this->client->clientsinfo->clients_name,
                $this->client->expire_date,
                $this->client->customerAccount->dueAmount ?? 0,
                siteinfo()->name,
                siteinfo()->mobile,
                $bill->package_rate,
                $bill->billing_type,
                today()->format('M-Y'),
                $bill->due_date,
                Carbon::parse($bill->created_at)->format('M-Y')
            ],
            $setting->email_body
        );


        DB::beginTransaction();

        try {

            $emails = explode(',', $this->client->clientsinfo->email);

            foreach ($emails as $email) {
                $status = Mail::to($email)
                    ->send(new InvoiceSend($this->data, $message, $this->client));

                MailLog::create([
                    'clients_id' => $this->client->id,
                    'subject'   => 'Invoice Send',
                    'message'   => $message,
                    'status'    => 'success',
                    'error'     => '',
                    'to'        => $email,
                ]);
            }

            DB::commit();
        } catch (\Swift_TransportException $th) {

            DB::rollback();
            MailLog::create([
                'clients_id' => $this->client->id,
                'subject'    => 'Invoice Send',
                'message'    => $message,
                'status'     => 'faild',
                'error'      => $th,
                'to'         => $this->client->clientsinfo->email,
            ]);
        }
    }
}
