<?php

namespace App\Controllers\Client;

use App\Controllers\BaseController;
use App\Core\Service\Logger;
use App\Model\MasterModel;
use App\Model\FxModel;
use App\Service\Dial;
use Exception;

class DialController extends BaseController
{
    private $model;
    private $Fxmodel;
    public function  __construct()
    {
        parent::__construct();
        $this->model = new MasterModel();
        $this->Fxmodel = new FxModel();
    }
    public function dialNumber()
    {
        try {
            if (empty($this->input['master_name']) || empty($this->input['primary_key']) || empty($this->input['which_no']) || empty($this->input['id'])) {
                throw new Exception('Can\'t dial no. Some parameters are missing');
            }
            // CLIENT DB
            $db = $this->model->client_db_prefix . $this->user_data->comp_id;
            // GET REF DATA
            $fetchData = $this->model->getMasterDataByID($db, $this->input['master_name'], $this->input['id'], $this->input['primary_key']);
            if (!$fetchData['status']) {
                throw new Exception($fetchData['error']);
            }
            // GET BRANCH LIST 
            $brchrs = $this->Fxmodel->getBranchMasterForDialer($this->user_data->comp_id);
            if (!$brchrs['status']) {
                throw new \Exception($brchrs['error']);
            }
            if (empty($brchrs['data'])) {
                throw new \Exception("Branch settings data not found");
            }
            // GET USER ASSIGNED BRANCH
            $branch_tbl = "`$db` . `branch_user_rights`";
            $userBranch = $this->model->fetchAllData("SELECT * FROM $branch_tbl WHERE user_id=:user_d", [":user_d" => $this->user_data->id]);
            if (!$userBranch['status']) {
                throw new Exception($userBranch['error']);
            }
            if (empty($userBranch['data']) && $this->user_data->master_type != 1) {
                throw new Exception('You can\'t call ,because you don\'t have any branch permission');
            }
            $branch = NULL;
            // TO GET BRANCH ID FROM MASTER
            $branch_ref_id = 'branch_id';
            if ($this->input['master_name'] == 'leads') {
                $branch_ref_id = 'branch';
            }
            // FILTER BRANCH IF USER IS NOT MASTER
            if (!empty($userBranch['data']) && $this->user_data->master_type != 1) {
                foreach ($userBranch['data'] as $usrB) {
                    if ($usrB['branch_id'] == $fetchData['data'][$branch_ref_id]) {
                        $branch = $usrB;
                        break;
                    }
                }
                if (!$branch) {
                    throw new Exception('You don\'t have branch permission');
                }
            } else if ($this->user_data->master_type == 1) {
                // IF USER IS MASTER
                $branch['branch_id'] = $fetchData['data'][$branch_ref_id];
            }
            // GET SELECTED BRANCH DATA
            foreach ($brchrs['data'] as $val) {
                if ($val['branch_id'] == $branch['branch_id']) {
                    $branchData = $val;
                    break;
                }
            }
            // BACK DATA
            $refData['user_id'] = $this->user_data->id;
            $refData['ref_type'] = $this->input['master_name'];
            $refData['ref_id'] = $this->input['id'];
            $replaceVariableData['customer_mobile_no'] = $fetchData['data'][$this->input['which_no']];
            $replaceVariableData['ext_no'] = $this->user_data->ext_no;
            $replaceVariableData['user_phone'] = $this->user_data->user_phone;

            foreach ($replaceVariableData as $key => $value) {
                $branchData['dial_api_json'] = str_replace('{{' . $key . '}}', $value, $branchData['dial_api_json']);
            }
            $dialService = new Dial();
            if ($branchData['dialer_provider'] == 'san_click_to_call') {
                // CALL IPPBX 
                $dialResp = $dialService->callSANIPPBX(
                    $branchData['dial_api_url'],$branchData['dial_api_method'],
                    json_decode(stripslashes($branchData['click_2_call_header_json']), true),
                    json_decode(stripslashes($branchData['dial_api_json']), true),
                    $refData
                );
            } else if ($branchData['dialer_provider'] == 'san_easy_go_ivr') {
                // CALL EASYGOIVR
                $dialResp = $dialService->callEasyGoIVR($branchData['dial_api_url'],$branchData['dial_api_method'],
                    json_decode(stripslashes($branchData['click_2_call_header_json']), true),json_decode(stripslashes($branchData['dial_api_json']), true),
                    $refData);
            }
            if (!$dialResp['status']) {
                throw new Exception($dialResp['error']);
            }
            $this->sendResponse(array('status' => true,'code' => $dialResp['code'], 'message' => $dialResp['msg'], 'data' => $dialResp['data']));
        } catch (\Exception $e) {
            Logger::error($e->getMessage(), ['File' => $e->getFile(), 'Line' => $e->getLine()]);
            $this->sendResponse(array('code' => 400, 'message' => $e->getMessage(), 'data' => null));
        }
    }
}
