<?php

namespace App\Controllers;

use App\Models\AdminModel;
use App\Models\LeadModel;

class Api extends BaseController
{
    public function initController(
        \CodeIgniter\HTTP\RequestInterface $request,
        \CodeIgniter\HTTP\ResponseInterface $response,
        \Psr\Log\LoggerInterface $logger
    ) {
        parent::initController($request, $response, $logger);

        $this->AdminModel = new AdminModel();
        $this->LeadModel  = new LeadModel();
    }

    public function add_lead()
    {
        header('Access-Control-Allow-Origin: *');
        $generate_key = hash('sha256', ('blackboard-education' . 'vleads'));
        $api_key = trim($this->request->getPost('key'));
        $data = [];

        if ($generate_key == $api_key) {
            $config = [
                ['field' => 'name',        'label' => 'Full Name',   'rules' => 'required'],
                ['field' => 'mobile',      'label' => 'Mobile No',   'rules' => 'required|min_length[10]|max_length[10]'],
                ['field' => 'email',       'label' => 'Email ID',    'rules' => 'trim|required|valid_email'],
                ['field' => 'enquiry_for', 'label' => 'Enquiry For', 'rules' => 'required'],
            ];

            if (!$this->validate(array_column($config, 'rules', 'field'))) {
                $errors = $this->validator->getErrors();
                $data['status']      = 0;
                $data['name']        = strip_tags($errors['name'] ?? '');
                $data['mobile']      = strip_tags($errors['mobile'] ?? '');
                $data['email']       = strip_tags($errors['email'] ?? '');
                $data['enquiry_for'] = strip_tags($errors['enquiry_for'] ?? '');
            } else {
                $full_name    = $this->request->getPost('name');
                $enquiry_for  = $this->request->getPost('enquiry_for');
                $email        = $this->request->getPost('email');
                $mobile       = $this->request->getPost('mobile');
                $state        = $this->request->getPost('state');
                $city         = $this->request->getPost('city');
                $user_list    = $this->AdminModel->get_user_list();
                $leadStr      = '';
                $leadarr      = [];

                foreach ($user_list as $val) {
                    $leadarr[$val['uid']] = '0';
                    $leadStr .= $val['uid'] . ',';
                }
                $leadStr = rtrim($leadStr, ',');

                $check_todays_leads = $this->LeadModel->check_today_assigned_lead($leadStr);
                foreach ($leadarr as $key => $arr) {
                    foreach ($check_todays_leads as $leads) {
                        if ($key == $leads['user_id']) {
                            $leadarr[$key] = $leads['total_lead'];
                        }
                    }
                }

                $user_id_change = array_search(min($leadarr), $leadarr);
                $inserted_id    = $this->LeadModel->assign_lead($user_id_change);

                if ($inserted_id > '1') {
                    $data['status']  = 'success';
                    $data['message'] = 'Thanku for submission';
                } elseif ($inserted_id == '2') {
                    $data['status']  = 'success';
                    $data['message'] = 'Thanku for submission';
                } else {
                    $data['status'] = null;
                }
            }
        } else {
            $data['status']  = 0;
            $data['message'] = "Invalid Api key.";
        }

        echo json_encode($data);
    }

    public function mobile_validate($mobile)
    {
        $mobile_number = trim($mobile);
        if (strlen($mobile_number) != 10) {
            $this->validator->setError('mobile', 'Please Enter a valid  mobile no of 10 digits.');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    public function alpha_dash_space($fullname)
    {
        if ($fullname != "") {
            if (!preg_match('/^[a-zA-Z\s]+$/', $fullname)) {
                $this->validator->setError('fullname', 'The {field} field may only contain alpha characters & White spaces');
                return FALSE;
            } else {
                return TRUE;
            }
        } else {
            return TRUE;
        }
    }

    public function startcall()
    {
        if (!is_numeric(session()->get('user_type'))) {
            return redirect()->to(base_url('login/index'));
        }

        $counselor_number = session()->get('mobile');
        $customer_number  = $this->request->getPost('mobile');
        $lead_id          = $this->request->getPost('lead_id');
        $url = 'https://vleads.in/portal/api/makecallc2c?key=bb36c34eb6644ab9694315af7d68e629&customer_number=' . $customer_number . '&agent_number=' . $counselor_number . '&lead_id=' . $lead_id . '';

        $curl_handle = curl_init();
        curl_setopt($curl_handle, CURLOPT_URL, $url);
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
        $buffer = curl_exec($curl_handle);
        curl_close($curl_handle);
        print_r($buffer);
        exit;

        if (empty($buffer)) {
            error_log("No response");
        } else {
            print $buffer;
        }
    }

    public function get_call_logs()
    {
        $generate_key = hash('sha256', ('blackboard-education' . 'vleads'));
        $api_key = trim($this->request->getPost('key'));
        $data = [];

        if ($generate_key == $api_key) {
            $config = [
                ['field' => 'caller',        'label' => 'Caller',       'rules' => 'required|min_length[10]|max_length[10]'],
                ['field' => 'agent_number',  'label' => 'Agent Number', 'rules' => 'required'],
            ];

            if (!$this->validate(array_column($config, 'rules', 'field'))) {
                $errors = $this->validator->getErrors();
                $data['status']       = 0;
                $data['caller']       = $errors['caller'] ?? '';
                $data['agent_number'] = $errors['agent_number'] ?? '';
            } else {
                $result = $this->AdminModel->insert_call_log();
                if ($result > 0) {
                    $data['status']  = 1;
                    $data['message'] = "Data success fully inserted";
                } else {
                    $data['status']  = 0;
                    $data['message'] = "System error please try after some time.";
                }
            }
        } else {
            $data['status']  = 0;
            $data['message'] = "Invalid Api key.";
        }

        echo json_encode($data);
    }

    public function call_histroy()
    {
        $mobile = $this->request->getGet('mobile');
        $result = $this->AdminModel->call_histroy($mobile);

        if (empty($result) === FALSE) {
            foreach ($result as $key => $val) {
                $startdate     = $val->call_startdate;
                $call_duration = $val->total_duration;
                $recording_url = $val->recording_url;
                $html = '<div style="float:left;margin:0 10px;">Call Duration ' . $call_duration . '
			  <br><a href="' . $recording_url . '">Recording Link</a><br> (' . $startdate . ')
			</div>
			<i style="float:left;position:relative;top:14px;" class="fa fa-arrow-right" aria-hidden="true">
			</i>';
            }
        } else {
            $html = '<div style="float:left;margin:0 10px;">No Record Found.</div>
	';
        }

        echo $html;
    }
}