<?php

namespace App\Jobs;

use App\Model\Dialer;
use App\Model\SmsTemplete;
use App\Model\Cron;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public $requestData;
    public $campaignId;
    public $clientId;
    public $hopperMode;
    public $extension;
    public $asteriskServer;

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

    public function __construct(
        array $requestData,
        int $campaignId,
        int $clientId,
        string $hopperMode,
        string $extension,
        string $asteriskServer
    ) {
        $this->requestData     = $requestData;
        $this->campaignId      = $campaignId;
        $this->clientId        = $clientId;
        $this->hopperMode      = $hopperMode;
        $this->extension       = $extension;
        $this->asteriskServer  = $asteriskServer;
    }

    public function handle()
    {
        $dialer   = new Dialer();
        $cron     = new Cron();
        $template = new SmsTemplete();

        $addResponse = $dialer->addLeadToExtensionLiveOutboundAI(
            $this->campaignId,
            $this->hopperMode,
            $this->extension,
            $this->asteriskServer,
            $this->clientId
        );

        if (!empty($addResponse['code']) && $addResponse['code'] === 'NO_LEADS') {
            $cron->addLeadTemp($this->clientId, $this->campaignId);
            return;
        }

        $this->requestData['lead_id'] = $addResponse['lead_id'];
        $this->requestData['list_id'] = $addResponse['list_id'];

        // Dial call
        $dialer->outboundAIDialAsterisk($this->requestData);
    }
}
