<?php
/**
 * Created by PhpStorm.
 * User: sunil
 * Date: 28/11/18
 * Time: 12:39 PM
 */

namespace App;


use App\Http\Middleware\MongoMiddleware;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use App\Logging\CloudWatchLoggerFactory;
use App\ConsumerApplication;

class EPFUANLookup extends Model
{
    private $endPointDevelopment = '';
    private $karza_key = '';
    private $karza_key2 = '';
    private $curl;
    const PUBLIC = 'public';
    const PRIVATE = 'private';
    private $start_time;
    private $payload;

    protected $table = 'employment_verification';

    public function setup(){
        $this->endPointDevelopment = (_env('KARZAURL', ''));
        $this->karza_key = (_env('KARZAKEY', ''));
        $this->karza_key2 = (_env('KARZA_KEY', ''));
        $this->start_time = time();
    }

    public function getUAN($mobile_number){
        $this->setup();
        $this->endPointDevelopment .= 'uan-lookup';
        if($this->endPointDevelopment && $this->karza_key) {
            $this->payload = json_encode(['mobile' => $mobile_number, 'consent' => 'Y']);

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $this->endPointDevelopment,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $this->payload,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'cache-control: no-cache',
                    'x-karza-key: ' . $this->karza_key
                ),
            ));

            $this->curl = $curl;

            (new Slack(new Request(['title' => 'EPF api - 1', 'fields' => ['request' => $this->payload, 'endpoint' => $this->endPointDevelopment], 'group' => Slack::$STAGE_TESTING])))->send();

            return $this->get();
        }

        return false;
    }

    public function getUANByApplicationV1($id, $isRaw = false){
        $data = $this->whereNull('deleted_at')->where('application_id', $id)->get(['id','application_id', 'data','employerName','employeeName','email','mobile','entity_id','uan_no','applicant_type']);
        if($isRaw){
            return $data;
        }
        $response['epf'] = '';
        $response['epfCoApplicant'] = '';
        foreach ($data as $item){
            if($item->applicant_type == 1 || !$item->applicant_type){
                $response['epf'] = $item;
            }else{
                $response['epfCoApplicant'] = $item;
            }
        }

        return $response;
    }

    public function getUANByApplication($id, $isRaw = false){
        $data = $this->whereNull('deleted_at')->where('application_id', $id)->get(['id','application_id', 'data','employerName','employeeName','email','mobile','entity_id','uan_no','applicant_type']);
        if($isRaw){
            return $data;
        }
        $response['epf'] = '';
        $response['epfCoApplicant'] = '';
        foreach ($data as $item){
            if($item->applicant_type == 1 || !$item->applicant_type){
                $response['epf'] = $item;
            }else{
                $response['epfCoApplicant'] = $item;
            }
        }

        return $response;
    }

    public function verifyUAN($uan){
        $this->setup();
        $this->endPointDevelopment .= 'membership-lookup';
        if($this->endPointDevelopment && $this->karza_key) {
            $this->payload = json_encode(['uan' => $uan, 'consent' => 'Y']);

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $this->endPointDevelopment,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $this->payload,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'cache-control: no-cache',
                    'x-karza-key: ' . $this->karza_key
                ),
            ));

            $this->curl = $curl;

            (new Slack(new Request(['title' => 'EPF api - 2', 'fields' => ['request' => $this->payload, 'endpoint' => $this->endPointDevelopment], 'group' => Slack::$STAGE_TESTING])))->send();

            return $this->get();
        }
        return false;
    }

    public function employmentVerificationAdvanced($employerName, $employeeName, $entityId, $uanNo, $mobile, $emailId){

        $this->setup();
        $this->endPointDevelopment .= 'employment-verification-advanced';
        if($this->endPointDevelopment && $this->karza_key) {
            $data = ['employerName' => $employerName, 'employeeName' => $employeeName, 'entityId' => !is_null($entityId) ? $entityId : '', 'mobile' => $mobile, 'emailId' => !is_null($emailId) ? $emailId : '', 'pdf' => true];
            if($uanNo){
                $data['uans'] = [$uanNo];
            }

            $this->payload = json_encode($data);

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $this->endPointDevelopment,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $this->payload,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'cache-control: no-cache',
                    'x-karza-key: ' . $this->karza_key
                ),
            ));

            $this->curl = $curl;

            //(new Slack(new Request(['title' => 'EPF api - 3', 'fields' => ['request' => $this->payload, 'endpoint' => $this->endPointDevelopment], 'group' => Slack::$STAGE_TESTING])))->send();

            return $this->get();
        }
        return false;
    }

    public function employmentVerificationAdvancedPanFlow($employerName, $employeeName, $entityId, $uanNo, $mobile, $emailId, $application_id, $applicant_type){
        // $data = ['employerName' => $employerName, 'employeeName' => $employeeName, 'entityId' => !is_null($entityId) ? $entityId : '', 'mobile' => $mobile, 'emailId' => !is_null($emailId) ? $emailId : '', 'pdf' => true];
        // if($uanNo){
        //     $data['uans'] = [$uanNo];
        // }
        $this->setup();
        $this->endPointDevelopment .= 'employment-verification-advanced';
        if($this->endPointDevelopment && $this->karza_key) {
            $app_data = ConsumerApplication::whereNull('is_deleted')->where('id', $application_id)->first();

            // if ($app_data->pan_card) {
            //     $pan = $app_data->pan_card;
            // } else {
            //     throw new Exception("PAN not in Database.");
            // }
            // $pan = $app_data->pan_card;
            if($applicant_type == 1){
                if ($app_data->pan_card) {
                    $pan = $app_data->pan_card;
                } else {
                    throw new \Exception("Applicant PAN not in Database.");
                }
            }
            elseif ($applicant_type == 2) {
                if ($app_data->co_applicant_pan_card) {
                    $pan = $app_data->co_applicant_pan_card;
                } else {
                    throw new \Exception("Co-Applicant PAN not in Database.");
                }
            }
            // $data = ['runPanFlow' => true, 'pan'=>$pan, 'pdf' =>true, 'consent'=>'Y'];
            $data = ['runPanFlow' => true, 'pan'=>$pan, 'pdf' =>true, 'consent'=>'Y', 'employerName' => $employerName, 'employeeName' => $employeeName, 'entityId' => !is_null($entityId) ? $entityId : '', 'mobile' => $mobile, 'emailId' => !is_null($emailId) ? $emailId : ''];
            if($uanNo){
                $data['uan_no'] = [$uanNo];
            }

            $this->payload = json_encode($data);

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $this->endPointDevelopment,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $this->payload,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    // 'cache-control: no-cache',
                    'x-karza-key: ' . $this->karza_key
                ),
            ));
            $response = curl_exec($curl);

            $response = json_decode($response);

            $this->curl = $curl;

            $cwFactory = new CloudWatchLoggerFactory();
            $cwFactory->logger(json_encode(['application_id' => $application_id, 'request' => json_encode($data) ?? '', 'response' => $response ?? '', 'error_msg' => curl_error($curl) ?? '']));
            // (new Slack(new Request(['title' => 'EPF api - 3', 'fields' => ['request' => $this->payload, 'endpoint' => $this->endPointDevelopment], 'group' => Slack::$STAGE_TESTING])))->send();


            return $this->get();
        }
        return false;
    }

    public function get(){
        try {
            $response = curl_exec($this->curl);
            if (curl_error($this->curl)) {
                $error = curl_error($this->curl);
            }
            curl_close($this->curl);

            (new Services())->log('Karza', ['status' => true, 'service_count' => 0, 'start_time' => $this->start_time]);
            $cwFactory = new CloudWatchLoggerFactory();
            $data = array('user_id'=> isset(Auth::user()->id) ? Auth::user()->id : '', 'vendor'=> 'Karza', 'api_url' => $this->endPointDevelopment,'Request'=> $this->payload ?? '{}', 'Response'=>isset($response) ? json_decode($response, 1) : '', 'error_msg' => isset($error) ? json_decode($error, 1) : '');
            $cwFactory->logger(json_encode($data));
            if (isset($error)) {
                return false;
            }
            //(new Slack(new Request(['title' => 'EPF api response', 'fields' => ['response' => $response], 'group' => Slack::$STAGE_TESTING])))->send();
            return json_decode($response, 1);

        }catch (\Exception $e){
            (new Slack(new Request(['title' => 'Karza EPF Failed', 'fields' => ['response' => $response], 'group' => Slack::$STAGE_TESTING])))->send();
        }
        return false;
    }
}
