<?php

namespace App\Jobs\Command;

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

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

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $dateToday = date('Y-m-d');
        $notificationTypeId = 1; //Newly registered company notification settings ID

        $companies = Company::select(
            'companies.name as company_name',
            'companies.type',
            'companies.created_at as date_created',
            'companies.company_tel as phone_number',
        )
        ->whereDate('companies.created_at', 'LIKE' , $dateToday .'%')
        ->limit(20)
        ->get();

        if(!$companies->isEmpty()) {
            // Get all admin who enabled the notigication type 1 == newly registered company
            $conxSuperAdmins = AdminUser::select(
                'conx_users.email_address',
            )
            ->leftJoin('conx_users_notification_settings', 'conx_users_notification_settings.admin_id', 'conx_users.id')
            ->leftJoin('notification_types', 'notification_types.id', 'conx_users_notification_settings.notification_type_id')
            ->where('notification_types.id', $notificationTypeId)
            ->get();

            $user_data = [
                'date_created' => date("F j, Y"),
            ];

            if(!$conxSuperAdmins->isEmpty()){
                foreach($conxSuperAdmins as $admin){
                    $rules = array(
                        'email_address' => 'required|email:rfc,dns',
                    );
                    $dataTobeValidated = [
                        'email_address' => $admin->email_address
                    ];
                    $error = Validator::make($dataTobeValidated, $rules);
                    
                    // if email is legit, send email
                    if (!$error->fails()) {
                        Mail::to($admin->email_address)->send(new \App\Mail\Command\AdmiNotificationForNewlyCreatedCompany($user_data, $companies));
                    }
                }
            }
        }else{
            echo('No company created today!');
        }
    }
}
