<?php

namespace App\Modules\Admin\Companies;

use App\Models\Company;
use App\Models\CompanyUser;
use App\Events\Admin\ChangeCompanyStatusEvent;
use App\Events\Admin\NotifyTransactedCompanyOfBlockedCompanyEvent;
use App\Jobs\Admin\ProcessSendEmailForBannedCompanyNotification;
use App\Traits\ValidatorTraits;

class UpdateCompany
{
    use ValidatorTraits;

    public function updateIsBannedStatus($payload, $id)
    {
        $isBanned = $payload->is_banned;

        // validate query param
        $rules = array(
            'is_banned' => 'required|in:true,false',
        );
        $validate = $this->validateRequest($payload, $rules);
        if ($validate) {
            return $validate;
        }

        // preparing company data to be saved on database
        $companyData = array(
            'is_banned' => $isBanned,
        );

        // update company data to companies table
        $companyUpdateTransaction = tap(Company::where('id', $id))->update($companyData)->first();

        event(new ChangeCompanyStatusEvent($id, $isBanned));

        if($isBanned == 'true'){
            $emailAddress = $this->getCompanyOwnerEmail($companyUpdateTransaction->id, $companyUpdateTransaction->email_address);
            $emailData = [
                'companyName' => strtoupper($companyUpdateTransaction->name),
            ];

            ProcessSendEmailForBannedCompanyNotification::dispatch($emailAddress, $emailData)->onConnection('jobs_emails')->onQueue('sendemail');
            event(new NotifyTransactedCompanyOfBlockedCompanyEvent($companyUpdateTransaction->id)); //Event for sending emails on company transacted by the banned company

        }

        return response()->json(['success' => 'Company ' . ($isBanned == 'true' ? 'Banned' : 'Unbanned') . ' successfully.'])->setStatusCode(201);
    }

    public function getCompanyOwnerEmail($companyID, $companyEmailAddress){
        $emailsAddresses = CompanyUser::select(
            'workers.email_address as owner_email'
        )
        ->join('workers', 'workers.id', 'company_users.worker_id')
        ->where('company_users.company_id', $companyID)
        ->where('company_users.role_id' , 1)
        ->first();

        if($companyEmailAddress == $emailsAddresses->owner_email){
            return $emailsAddresses->owner_email;
        }
        
        return array(
            $companyEmailAddress,
            $emailsAddresses->owner_email,
        );
    }
}
