<?php

namespace App\Services\SmartCredit;

use App\Utility\HttpRequest\HttpAsForm;
use Exception;
use Illuminate\Validation\Rules\Enum;

class SmartCredit
{
    /*
     * Create smart credit account life cycle
     * call /start api (GET)
     * call /customer/create api (POST)
     * call /customer/update/identity api (POST)
     * call /id-verification api (GET)
     * call /id-verification api (POST)
     * call /validate/credit-card-number (GET)
     * call /customer/update/credit-card (POST)
     * call /complete api (POST)
     * */

    const CLIENT_KEY = "ddeada92-6310-4850-82c4-0b99159b9339";

    private string $api_base_url = '';
    private string $pws_base_url = '';

    private string $client_key;
    public string $customer_token='';
    public string $pws_customer_token='';
    public string $tracking_token='';

    private string $email;
    private string $first_name;
    private string $last_name;
    private string $client_ip;
    private string $street;
    private string $zip;
    private string $phone;
    private string $dob;
    private string $ssn;
    private string $password;
    private string $planType;
    private string $refference;
    private string $card_number;
    private string $cvv;
    private string $expiry;
    private string $credit_card_token;
    private string $partial_ssn;
    private string $sqa_answer;
    private string $sqa_question;
    private string $sponsorCodeString = "YHV3QZWXN5";
    private string $pid = "11885";
    private string $temporaryPassword;

    private array $logData = [];

    public string $status_code = "";
    public string $message = "";
    public $data = [] ;
    private string $log_id;

    private int $updateId=0;

    private string $prefix = "SMART_CREDIT_API_";


    public function __construct($client_key){
        $this->client_key = $client_key;
        $this->api_base_url = (config('app.SMART_CREDIT_BASE_URL') ?? '')."/api/signup";
        $this->pws_base_url = config('app.PWS_SMART_CREDIT_BASE_URL') ?? '';
        $this->log_id = "LOG_".getSecurityKey();
    }

    /**
     * @throws Exception
     */
    private function setException($responseData){
        $this->status_code = config('constant.API_FAILED_CODE');
        if(isset($responseData['errors']) && !empty($responseData['errors'])){
            $responseData['errors'] = current($responseData['errors']);
            $this->message = $responseData['errors']['message'];
        }else{
            $this->message = "Somethings went to wrong.";
        }
        throw new \Exception($this->message);
    }


    public function setData($inputData): SmartCredit
    {
        $this->email = $inputData['email'] ?? "";
        $this->planType = $inputData['planType'] ?? "";
        $this->password = $inputData['password'] ?? "";
        $this->first_name = $inputData['first_name'] ?? "";
        $this->last_name = $inputData['last_name'] ?? "";
        $this->client_ip = $inputData['client_ip'] ?? "";
        $this->zip = $inputData['zip'] ?? "";
        $this->street = $inputData['street'] ?? "";
        $this->phone = $inputData['phone'] ?? "";
        $this->dob = $inputData['dob'] ?? "";
        $this->ssn = $inputData['ssn'] ?? "";
        $this->partial_ssn = $inputData['partial_ssn'] ?? "";
        $this->card_number = $inputData['card_number'] ?? "";
        $this->cvv = $inputData['cvv'] ?? "";
        $this->expiry = $inputData['expiry'] ?? "";
//        $this->sqa_answer = $inputData['sqa_answer'];
//        $this->sqa_question = $inputData['sqa_question'];

        $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]['user_request'] = $inputData;

        if(!empty($this->partial_ssn)){
            $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]['user_request']['partial_ssn'] = "XXXX";
        }

        if(!empty($this->ssn)){
            $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]['user_request']['ssn'] = "XXX-XX-XXXX";
        }

        if(!empty($this->card_number)){
            $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]['user_request']['card_number'] = "XXXXXXXXXXXX";
        }

        if(!empty($this->cvv)){
            $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]['user_request']['cvv'] = "XXX";
        }

        if(!empty($this->expiry)){
            $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]['user_request']['expiry'] = "XXXX";
        }

        if(!empty($this->password)){
            $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]['user_request']['password'] = "XXXXXXXX";
        }


        /*$this->logData['SMART_CREDIT_API_LOG'][$this->log_id]['user_request']['sqa_answer'] = "XXXX";
        $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]['user_request']['sqa_question'] = "XXXX";*/

        return $this;
    }

    /**
     * @throws Exception
     */

    private function start(): void
    {

        $url = $this->api_base_url . "/start";

        $params = [
            'clientKey' => $this->client_key,
            'PID' => $this->pid
        ];

        $responseData = (new HttpAsForm($url))->get($params);

        $this->data = $responseData;

        $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]["START"] = $this->prepareLogData($url,'GET',$params);

        if(!empty($responseData['trackingToken'])){
            $this->tracking_token = $responseData['trackingToken'];
        }else{
            $this->setException($responseData);
        }


        //appLog($this->logData);
    }

    /**
     * @throws Exception
     */

    private function campaign(): void
    {

        $url = $this->api_base_url . "/campaign";

        $params = [
            'clientKey' => $this->client_key,
            'PID' => $this->pid
        ];
        $responseData = (new HttpAsForm($url))->get($params);

        $this->data = $responseData;

        $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]["CAMPAIGN"] = $this->prepareLogData($url,'GET',$params);

        if(isset($responseData['errors']) && !empty($responseData['errors'])){
            $this->setException($responseData);
        }


        //appLog($this->logData);
    }


    /**
     * @throws Exception
     */

    private function validateEmail(): void
    {

        $url = $this->api_base_url ."/validate/email";

        $params = [
            'clientKey' => $this->client_key,
            'email'=>$this->email,
            'trackingToken'=>$this->tracking_token
        ];

        $responseData = (new HttpAsForm($url))->get($params);

        $this->data = $responseData;

        $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]["VALIDATE_EMAIL"] = $this->prepareLogData($url,'GET',$params);

        if(isset($responseData['errors']) && !empty($responseData['errors'])){
            $this->setException($responseData);
        }

    }

    /**
     * @throws Exception
     */

    private function validateSponsorCode(): void
    {

        $url = $this->api_base_url ."/validate/sponsor-code";

        $params = [
            'clientKey' => $this->client_key,
            'sponsorCode '=>$this->sponsorCodeString,
            'trackingToken'=>$this->tracking_token
        ];

        $responseData = (new HttpAsForm($url))->get($params);

        $this->data = $responseData;

        $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]["VALIDATE_SPONSOR_CODE"] = $this->prepareLogData($url,'GET',$params);

        if(isset($responseData['errors']) && !empty($responseData['errors'])){
            $this->setException($responseData);
        }

    }

    /**
     * @throws Exception
     */

    private function validateSsn(): void
    {
        $url = $this->api_base_url . "/validate/ssn";

        $params = [
            'clientKey' => $this->client_key,
            'ssn' => $this->ssn,
            'trackingToken' => $this->tracking_token
        ];

        // optional parameter customer token
        if (!empty($this->customer_token)) {
            $params['customerToken'] = $this->customer_token;
        }

        $responseData = (new HttpAsForm($url))->get($params);

        $this->data = $responseData;

        $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]["VALIDATE_SSN"] = $this->prepareLogData($url, 'GET', $params);

        if (isset($responseData['errors']) && !empty($responseData['errors'])) {
            $this->setException($responseData);
        }

    }

    /**
     * @throws Exception
     */

    private function create(): void
    {

        $url = $this->api_base_url ."/customer/create";

        $params = [
            'clientKey' => $this->client_key,
            'email'=>$this->email,
            'trackingToken'=>$this->tracking_token,
            'password'=>$this->password,
            'planType'=>$this->planType,
            'sponsorCodeString'=>$this->sponsorCodeString
        ];


        $responseData = (new HttpAsForm($url))->post($params);

        $this->data = $responseData;

        $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]["CREATE"] = $this->prepareLogData($url,'POST',$params);

        if(!empty($responseData['customerToken'])){
            $this->customer_token = $responseData['customerToken'];
        }else{
            $this->setException($responseData);
        }

    }

    /**
     * @throws Exception
     */

    private function updateIdentity(): void
    {

        $url = $this->api_base_url . "/customer/update/identity";

        $params = [
            'clientKey' => $this->client_key,
            'trackingToken' => $this->tracking_token,
            'customerToken' => $this->customer_token,
            'firstName' => $this->first_name,
            'lastName' => $this->last_name,
            'homeAddress.street' => $this->street,
            'homeAddress.zip' => $this->zip,
            'homePhone' => $this->phone,
            'identity.birthDate' => $this->dob,
            'identity.ssnPartial' => $this->partial_ssn,
            'identity.ssn' => $this->ssn,
            'isConfirmedTerms' => true,
//            'securityQuestionAnswer.answer' => $this->sqa_answer,
//            'securityQuestionAnswer.securityQuestionId' => $this->sqa_question,
            'confirmTermsBrowserIpAddress' => $this->client_ip
        ];

        $responseData = (new HttpAsForm($url))->post($params);

        $this->data = $responseData;

//        $action=($this->updateId==1)?"UPDATE_IDENTITY_1":"UPDATE_IDENTITY";

        $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]["UPDATE_IDENTITY"] = $this->prepareLogData($url, 'POST', $params);

        if (isset($responseData['errors']) && !empty($responseData['errors'])) {
            $this->setException($responseData);
        }


        //appLog($this->logData);
    }

    /**
     * @throws Exception
     */

    private function getIdVerification(): void
    {
        $url = $this->api_base_url ."/id-verification";

        $params = [
            'clientKey' => $this->client_key,
            'trackingToken'=>$this->tracking_token,
            'customerToken'=>$this->customer_token
        ];

        $this->getIdVerificationApiCall($url,$params,1);

        if($this->status_code == config('constant.API_FAILED_CODE')){
            $this->getIdVerificationApiCall($url,$params,2);
        }

        if($this->status_code == config('constant.API_FAILED_CODE')) {
            $this->setException($this->data);
        }

    }

    private function getIdVerificationApiCall($url,$params,$count){

        $responseData = (new HttpAsForm($url))->get($params);
        //$responseData = $this->identityQuestionAnswer();
        $this->data = $responseData;

        $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]["GET_ID_VERIFICATION"][$count] = $this->prepareLogData($url,'GET',$params);

        if(isset($responseData['errors']) && !empty($responseData['errors'])){
            $this->status_code = config('constant.API_FAILED_CODE');
        }else{
            $this->status_code = config('constant.API_SUCCESS_CODE');
            $this->message = __('Account has been created successfully');
        }

    }

    private function prepareLogData($url,$method,$request_data){

        if(isset($request_data['identity.ssnPartial'])){
            $request_data['identity.ssnPartial'] = "XXXX";
        }

        if(isset($request_data['identity.ssn'])){
            $request_data['identity.ssn'] = "XXX-XX-XXXX";
        }

        if(isset($request_data['ssn'])){
            $request_data['ssn'] = "XXX-XX-XXXX";
        }

        if(isset($request_data['password'])){
            $request_data['password'] = "XXXXXXX";
        }

        if(isset($request_data['j_password']))
        {
            $request_data['j_password'] = "*********";
        }

        return [
            'request' => [
                'url' => $url,
                'method' => $method,
                'body'=> $request_data,
                'Header'=>[
                    'ContentType' => 'application/x-www-form-urlencoded'
                ]
            ],
            'response' => $this->data
        ];
    }

    /**
     * @throws Exception
     */

//    private function postIdVerification(): void
//    {
//
//        $this->logData['action'][] = $this->prefix."POST_ID_VERIFICATION";
//
//        $url = $this->api_base_url ."/id-verification";
//
//        $params = [
//            'clientKey' => $this->client_key,
//            'trackingToken'=>$this->tracking_token,
//            'customerToken'=>$this->customer_token,
//            'idVerificationCriteria.answer1'=>'2003',
//            'idVerificationCriteria.answer2'=>'ConsumerDirect',
//            'idVerificationCriteria.answer3'=>'J. C. R. Licklider',
//            'idVerificationCriteria.answer4'=>'123 Main',
//            'idVerificationCriteria.answer5'=>'$450,000',
//            'idVerificationCriteria.referenceNumber'=>$this->refference
//        ];
//
//        $responseData = (new HttpAsForm($url))->post($params);
//
//        if(isset($responseData['errors']) && !empty($responseData['errors'])){
//            $this->setException($responseData);
//        }
//
//    }

    /**
     * @throws Exception
     */
    private function identityQuestionAnswer()
    {
        $data='{
            "idVerificationCriteria": {
              "referenceNumber": "50fdbbbd-50a0-452a-8a86-9be0af826fdb",
              "question1": {
                "name": "ASSOC_ST_NAME",
                "displayName": "Which of these street names are you associated with?",
                "type": "IDMA",
                "questionId": 2389852099,
                "choiceList": {
                  "choice": [
                    {
                      "key": "10742928663",
                      "display": "138th"
                    },
                    {
                      "key": "10742928665",
                      "display": "Chamblee"
                    },
                    {
                      "key": "10742928667",
                      "display": "Moonlake"
                    },
                    {
                      "key": "10742928669",
                      "display": "Portland"
                    },
                    {
                      "key": "10742928671",
                      "display": "None of the Above"
                    }
                  ]
                }
              },
              "question2": {
                "name": "SSN_ISSUED",
                "displayName": "What state was your social security number issued (this could be the state in which you were born or had your first job)?",
                "type": "IDMA",
                "questionId": 2389852101,
                "choiceList": {
                  "choice": [
                    {
                      "key": "10742928673",
                      "display": "Colorado"
                    },
                    {
                      "key": "10742928675",
                      "display": "Florida"
                    },
                    {
                      "key": "10742928677",
                      "display": "Louisiana"
                    },
                    {
                      "key": "10742928679",
                      "display": "Massachusetts"
                    },
                    {
                      "key": "10742928681",
                      "display": "None of the Above"
                    }
                  ]
                }
              },
              "question3": {
                "name": "AUTO_TERM",
                "displayName": "What is the term (in months) of your most recent auto loan or lease?",
                "type": "IDMA",
                "questionId": 2389852103,
                "choiceList": {
                  "choice": [
                    {
                      "key": "10742928683",
                      "display": "25 -  36"
                    },
                    {
                      "key": "10742928685",
                      "display": "37 -  48"
                    },
                    {
                      "key": "10742928687",
                      "display": "49 -  60"
                    },
                    {
                      "key": "10742928689",
                      "display": "61 -  72"
                    },
                    {
                      "key": "10742928691",
                      "display": "None of the Above"
                    }
                  ]
                }
              },
              "question4": {
                "name": "ST_LOAN_PYMT",
                "displayName": "What is the monthly payment of your student loan?",
                "type": "IDMA",
                "questionId": 2389852105,
                "choiceList": {
                  "choice": [
                    {
                      "key": "10742928693",
                      "display": "$ 1 - $ 50"
                    },
                    {
                      "key": "10742928695",
                      "display": "$ 151 - $ 200"
                    },
                    {
                      "key": "10742928697",
                      "display": "$ 201 - $ 250"
                    },
                    {
                      "key": "10742928699",
                      "display": "$ 51 - $ 100"
                    },
                    {
                      "key": "10742928701",
                      "display": "None of the Above"
                    }
                  ]
                }
              }
            }
          }';
        $returnData['data']=json_decode($data,true);
        $returnData['message']='success';
        $returnData['status_code']='100';
//        $questionAnswerList=(new SmartCredit(config('app.CLIENT_KEY')))->security_questions();
        return $returnData['data'];
    }

    private function validateCardNumber(): void
    {

        $this->logData['action'][] = $this->prefix."VALIDATE_CARD_NUMBER";

        $url = $this->api_base_url ."/validate/credit-card-number";
        $params = [
            'clientKey' => $this->client_key,
            'trackingToken'=>$this->tracking_token,
            'number'=>$this->card_number
        ];

        $responseData = (new HttpAsForm($url))->get($params);

        if(!empty($responseData['creditCardToken'])){
            $this->credit_card_token = $responseData['creditCardToken'];
        }else{
            $this->setException($responseData);
        }

    }


    /**
     * @throws Exception
     */

    private function updateCardNumber(): void
    {

        $this->logData['action'][] = $this->prefix."UPDATE_CARD_NUMBER";

        $url = $this->api_base_url ."/customer/update/credit-card";

        $exploded = explode("/",$this->expiry);
        $expirationMonth = $exploded[0];
        $expirationYear = $exploded[1];

        $params = [
            'clientKey' => $this->client_key,
            'trackingToken'=>$this->tracking_token,
            'customerToken'=>$this->customer_token,
            'confirmTermsBrowserIpAddress'=>$this->client_ip,
            'creditCard.cvv'=>$this->cvv,
            'creditCard.expirationMonth'=>$expirationMonth,
            'creditCard.expirationYear'=>$expirationYear,
            'isConfirmedTerms'=>true,
            'creditCard.token'=>$this->credit_card_token
        ];

        $responseData = (new HttpAsForm($url))->post($params);

        if(!$responseData['isFinancialObligationMet']){
            $this->setException($responseData);
        }

    }

    /**
     * @throws Exception
     */

    private function complete($inputData): void
    {

        $url = $this->api_base_url ."/complete";

        $params = [
            'clientKey' => $this->client_key,
            'trackingToken'=>$inputData['trackingToken'],
            'customerToken'=>$inputData['customerToken']
        ];

        $responseData = (new HttpAsForm($url))->post($params);

        $this->data = $responseData;

        $params['email'] = $inputData['email'];

        $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]['COMPLETE'] = $this->prepareLogData($url,'POST',$params);

        if(isset($responseData['errors']) && !empty($responseData['errors'])){
            $this->setException($responseData);
        }else{
            $this->planType = $responseData['planType'] ?? "";
            $this->temporaryPassword = $responseData['temporaryPassword'] ?? "";
        }

    }

    public function checkIsEmailExistOnSmartCredit(){

        $result['status'] = false;
        $result['message'] = "";

        try {
            $this->start();
            $this->validateEmail();
        }catch (\Exception $ex){
            $this->status_code = config('constant.API_FAILED_CODE');;
            $this->message = $ex->getMessage();
        }

        $this->logData['SMART_CREDIT_EMAIL_VALIDATION_LOG'][$this->log_id]["START"] = $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]["START"];
        $this->logData['SMART_CREDIT_EMAIL_VALIDATION_LOG'][$this->log_id]["VALIDATE_EMAIL"] = $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]["VALIDATE_EMAIL"];

        unset($this->logData['SMART_CREDIT_API_LOG']);

        $this->logData['SMART_CREDIT_EMAIL_VALIDATION_LOG'][$this->log_id]['email'] = $this->email;
        $this->logData['SMART_CREDIT_EMAIL_VALIDATION_LOG'][$this->log_id]['message'] = $this->message;
        $this->logData['SMART_CREDIT_EMAIL_VALIDATION_LOG'][$this->log_id]['status_code'] = $this->status_code;

        if(!empty($this->data['errors'])){
            $errors = collect($this->data['errors'])->firstWhere('code','=','EMAIL_USED');
            if(!empty($errors)){
                $result['status'] = true;
                $result['message'] = "You already have an account with Smartcredit and would not open the questions";
            }
        }

        appLog($this->logData);

        return $result;
    }

    public function checkIsSsnExistOnSmartCredit(){

        $result['status'] = false;
        $result['message'] = "";

        $this->status_code = config('constant.API_SUCCESS_CODE');

        try {

            $this->start();
            $this->validateSsn();

        }catch (\Exception $ex){
            $this->status_code = config('constant.API_FAILED_CODE');
            $this->message = $ex->getMessage();
        }

        $this->logData['SMART_CREDIT_SSN_VALIDATION_LOG'][$this->log_id]["START"] = $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]["START"];
        $this->logData['SMART_CREDIT_SSN_VALIDATION_LOG'][$this->log_id]["VALIDATE_SSN"] = $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]["VALIDATE_SSN"];

        unset($this->logData['SMART_CREDIT_API_LOG']);

        $this->logData['SMART_CREDIT_SSN_VALIDATION_LOG'][$this->log_id]['email'] = $this->email;
        $this->logData['SMART_CREDIT_SSN_VALIDATION_LOG'][$this->log_id]['message'] = $this->message;
        $this->logData['SMART_CREDIT_SSN_VALIDATION_LOG'][$this->log_id]['status_code'] = $this->status_code;

        if(!empty($this->data['errors'])){
            $errors = collect($this->data['errors'])->first();
            if(!empty($errors)){
                $result['status'] = true;
                $result['message'] = $this->message;
            }
        }

        appLog($this->logData);

        return $result;
    }

    public function register(): SmartCredit
    {
        try{
            $this->start();
            $this->campaign();
            $this->validateEmail();
            $this->validateSponsorCode();
            $this->create();
            $this->updateIdentity();
//            $this->updateId=1;
//            $this->updateIdentity();
            $this->getIdVerification();

        }catch (\Exception $ex){
            $this->status_code = config('constant.API_FAILED_CODE');;
            $this->message = $ex->getMessage();

        }

        $this->logData['email'] = $this->email;
        $this->logData['message'] = $this->message;
        $this->logData['status_code'] = $this->status_code;

        appLog($this->logData);

        return $this;
    }

    public function security_question($inputData): SmartCredit{

        try{
            $this->postIdVerification($inputData);
            $this->complete($inputData);
        }
        catch (\Exception $ex){
            $this->status_code = config('constant.API_FAILED_CODE');
            $this->message = $ex->getMessage();
        }

        appLog($this->logData);
        return $this;
    }

    public function security_questions(): SmartCredit{

        try{
            $this->start();
            $this->logData['action'][] = $this->prefix."SECURITY_QUESTIONS";
            $url = $this->api_base_url . "/security-questions";
            $params = [
                'clientKey' => $this->client_key,
                'trackingToken'=>$this->tracking_token
            ];
            $responseData = (new HttpAsForm($url))->get($params);

            if(!empty($responseData['securityQuestions'])){
                $this->status_code = config('constant.API_SUCCESS_CODE');
                $this->message = __('Security Question has been gotten successfully');
                $this->data=$responseData['securityQuestions'];

            }else{
                $this->setException($responseData);
            }

        }catch (\Exception $ex){
            $this->status_code = config('constant.API_FAILED_CODE');
            $this->message = $ex->getMessage();
        }
        appLog($this->logData);
        return $this;
    }

    private function postIdVerification($inputData)
    {

        $url = $this->api_base_url ."/id-verification";

        $params = [
            'clientKey' => $this->client_key,
            'trackingToken'=>$inputData['trackingToken'],
            'customerToken'=>$inputData['customerToken'],
            'idVerificationCriteria.referenceNumber'=>$inputData['referenceNumber']
        ];

        if(!empty($inputData['security_question_answer'])){
            foreach ($inputData['security_question_answer'] as $key => $sqa){
                $params['idVerificationCriteria.'.$key] = $sqa['answer']['id'];
            }
        }

        $responseData = (new HttpAsForm($url))->post($params);

        $this->data = $responseData;

        $params['email'] = $inputData['email'];

        $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]['POST_ID_VERIFICATION'] = $this->prepareLogData($url,'POST',$params);

        if(isset($responseData['errors']) && !empty($responseData['errors'])){
            $this->setException($responseData);
        }

        $this->status_code = config('constant.API_SUCCESS_CODE');
        $this->message = __('Save successfully');


    }

    private function getCustomerTokenByCredential($email,$password){

            $this->api_base_url = (config('app.SMART_CREDIT_BASE_URL') ?? '');
            $url = $this->api_base_url . '/external-login';
            $loginType = config('app.LOGIN_TYPE') ?? 'PARTNER_API';
            $params = [
                'loginType' => $loginType,
                'j_username' => $email,
                'j_password' => $password,
            ];
            $responseData = (new HttpAsForm($url))->post($params);

            $this->data = $responseData;

            $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]['EXTERNAL_LOGIN'] = $this->prepareLogData($url,'POST',$params);

            if ($responseData['success']) {
                $this->pws_customer_token = $responseData['customerToken'];
            }else{
                $this->setPwsException($responseData);
            }

          return $this;
    }
    private function customerAccountStatus($type){

        $url = $this->pws_base_url . '/customer/account/status?'.'customerToken='.$this->pws_customer_token;
        $params = [
            'status' => $type,
        ];

        $responseData = (new HttpAsForm($url))->put($params,HttpAsForm::CONTENT_TYPE_JSON);

        $this->data = $responseData;

        $this->logData['SMART_CREDIT_API_LOG'][$this->log_id]['CUSTOMER_ACCOUNT_STATUS'] = $this->prepareLogData($url,'PUT',$params);

        if (!empty($responseData['accountStatus'])) {
            $this->data = $responseData;
        }else{
            $this->setPwsException($responseData);
        }

        return $this;
    }

    public function customerSubscription($inputData)
    {
        try{
            $this->getCustomerTokenByCredential($inputData['email'],$inputData['password']);
            $this->customerAccountStatus($inputData['type']);
        }catch (\Exception $ex){
            $this->status_code = config('constant.API_FAILED_CODE');
            $this->message = $ex->getMessage();
        }

        $this->logData['email'] = $inputData['email'];
        $this->logData['message'] = $this->message;
        $this->logData['status_code'] = $this->status_code;

        appLog($this->logData);
        return $this;
    }
    private function setPwsException($responseData){
        $this->status_code = config('constant.API_FAILED_CODE');
        if(isset($responseData['errors']) && !empty($responseData['errors'])){
            $responseData['errors'] = current($responseData['errors']);
            $this->message = $responseData['errors']['message'];
        }else{
            $this->message = "Somethings went to wrong.";
        }
        throw new \Exception($this->message);
    }


}
