<?php

namespace App\Services;

use App\Models\Creditreport;
use App\Utility\CurlRequest;
use App\Models\IqCallHistory;
use App\Utility\Email;
use function PHPUnit\Framework\isEmpty;

class CreditReportService
{

    const HTML_SCRAPPER_API_DOMAIN = "https://readytogoletters.com:8080";
//    const HTML_SCRAPPER_API_DOMAIN = "https://test.readytogoletters.com:8080";
//    const HTML_SCRAPPER_API_DOMAIN = "http://localhost:5000";

    public $identity_iq_html_url = self::HTML_SCRAPPER_API_DOMAIN."/identity-iq-credit-report-html";
    public $identity_iq_refresh_date_url = self::HTML_SCRAPPER_API_DOMAIN."/identity-iq-report-refresh-date";  // For Import button hit request for getting popup
    public $identity_iq_refresh_button_url =  self::HTML_SCRAPPER_API_DOMAIN."/identity-iq-click-refresh-btn";
    public $smart_credit_refresh_button_url =  self::HTML_SCRAPPER_API_DOMAIN."/smart-credit-credit-click-refresh-btn";
    public $SMART_CREDIT_HTML_URL =  self::HTML_SCRAPPER_API_DOMAIN."/smart-credit-credit-report-3b";
    public $smart_credit_refresh_date_url =  self::HTML_SCRAPPER_API_DOMAIN."/smart-credit-credit-refresh-status";
    public $SMART_CREDIT_JSON_URL =  self::HTML_SCRAPPER_API_DOMAIN."/smart-credit-credit-report-3b-json";
    public $ip = "45.55.43.211:8080";


    public function getIdentityRefreshButtonContent($username, $password,$ssn) {
        $result['status'] = false;
        $result['message'] = 'api problem.';
        $credentials['email'] = $username;
        $credentials['password'] = $password;
        $credentials['ssn'] = $ssn;
        $status = 0;
        $params = json_encode($credentials);
        $URL = $this->identity_iq_refresh_button_url;
        $curlRequest = new CurlRequest();

        $response = $curlRequest->makeCurlRequest($params,'POST',$URL);
        $response = json_decode($response,true);

        if (!empty($response) && $response['status_code'] == 200) {
            $status = 1;
            $result['status'] = true;
            $result['message'] = $response['data'];
        }
        if(isset($response['ip']) && !empty($response["ip"])){
            $this->ip = $response['ip'];
        }
        $ip_explode = explode(":", $this->ip );
        (new IqCallHistory())->insertHistory($ip_explode[0],$ip_explode[1],$response['page'],$response['page_code'],$status);
        return $result;
    }
    public function getIdentityIQHTML($username, $password,$ssn) {
        $logData['action'] = "GET_IDENTITY_IQ_HTML";

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

        $credentials['email'] = $username;
        $credentials['password'] = $password;
        $credentials['ssn'] = $ssn;
        $status = 0;
        try {
                $params = json_encode($credentials);
                $URL = $this->identity_iq_html_url;

                $curlRequest = new CurlRequest();

                $response = $curlRequest->makeCurlRequest($params,'POST', $URL);
                $response = json_decode($response,true);

        //        if ($response['data'] == "ERROR" || $response['data'] == "TIME_OUT" || $response['data'] == "INVALID_LOGIN" || $response['data'] == 'ACCOUNT_LOCKED' ) {
                if (!empty($response) && $response['status_code'] == 200){
                    $status = 1;
                    $result['status'] = true;
                    $result['html'] = $response['data'];
                    $result['message'] = 'User is valid.';
                }else{
                    $result['status_code'] = $response['status_code'];
                    $result['message'] = config('constant.SCRAPPER_RESPONSE'.'.'.$response['data']);
                    $response['page_code'] = $response['page_code']??"403";
                    throw new \Exception(config('constant.SCRAPPER_RESPONSE'.$response['data']));
                }

                /*
                if ($response == "ERROR" || $response == "TIME_OUT" || $response == "INVALID_LOGIN" || $response == "ACCOUNT_LOCKED") {

                    $result['message'] = config('constant.SCRAPPER_RESPONSE'.'.'.$response);
                    throw new \Exception(config('constant.SCRAPPER_RESPONSE'.$response));
                }

                if (!empty($response) ) {
                    $result['status'] = true;
                    $result['html'] = $response['data'];
                    $result['message'] = 'User is valid.';
                }
                */

                $logData['user_info'] = $credentials['email'];
                $logData['status'] =  $result['status'];

         }catch (\Exception $ex){
                $logData['data']['response'] = $response;
                $logData['data']['credentials'] = $credentials['email'];

            }

        if(isset($response['ip']) && !empty($response["ip"])){
            $this->ip = $response['ip'];
        }
        $ip_explode = explode(":", $this->ip );
        (new IqCallHistory())->insertHistory($ip_explode[0],$ip_explode[1],$response['page'],$response['page_code'],$status);
        appLog($logData);

        return $result;
    }
    public function getIdentityIQRefreshDate($username, $password,$ssn) {

        $credentials['email'] = $username;
        $credentials['password'] = $password;
        $credentials['ssn'] = $ssn;
        $status = 0;

        $params = json_encode($credentials);
        $URL = $this->identity_iq_refresh_date_url;
        $curlRequest = new CurlRequest();
        $response = $curlRequest->makeCurlRequest($params,'POST',$URL);
        $response = json_decode($response,true);

//        if ($response['data'] == "ERROR" || $response['data'] == "TIME_OUT" || $response['data'] == "INVALID_LOGIN" || $response['data'] == 'ACCOUNT_LOCKED' ) {

        if(!empty($response) && $response['status_code'] == 200) {
            $status = 1;
        }
        if(isset($response['ip']) && !empty($response["ip"])){
            $this->ip = $response['ip'];
        }
        $ip_explode = explode(":", $this->ip );
        (new IqCallHistory())->insertHistory($ip_explode[0],$ip_explode[1],$response['page'],$response['page_code'],$status);

        if ($response['status_code'] != 200){
            $status = 0;
            $result['refresh_date'] = 'ERROR';
            $result['message'] = config('constant.SCRAPPER_RESPONSE'.'.'.$response['data']) ;
            return  $result;
        }

        return $response;
    }
    public function getSmartCreditRefreshButtonContent($username, $password) {

        $result['status'] = false;
        $result['message'] = 'api problem.';
        $credentials['email'] = $username;
        $credentials['password'] = $password;
        //$credentials['ssn'] = $ssn;

        $params = json_encode($credentials);
        $URL = $this->smart_credit_refresh_button_url;
        $curlRequest = new CurlRequest();
        $response =$curlRequest->makeCurlRequest($params,'POST',$URL);

        if (!empty($response)) {
            $result['status'] = true;
            $result['message'] = $response;
        }
        return $result;
    }
    public function getSmartCreditRefreshDate($username, $password,$ssn) {

        $credentials['email'] = $username;
        $credentials['password'] = $password;
        //$credentials['ssn'] = $ssn;

        $params = json_encode($credentials);
        $URL = $this->smart_credit_refresh_date_url;
        $curlRequest = new CurlRequest();
        $response = $curlRequest->makeCurlRequest($params,'POST',$URL);
        if ($response == "ERROR" || $response == "TIME_OUT" || $response == "INVALID_LOGIN" || $response == 'ACCOUNT_LOCKED' ) {
            $result['refresh_date'] = 'ERROR';
            $result['message'] = config('constant.SCRAPPER_RESPONSE'.'.'.$response) ;
            return  $result;
        }
        return json_decode($response,true);
    }
    public function getSmartCreditHTML($username, $password) {

        $result['status'] = false;
        $result['html'] = "";
        $result['message'] = '';
        $logData['action'] = "GET_SMART_CREDIT_HTML";
        try {
            $credentials['email'] = $username;
            $credentials['password'] = $password;

//        $credentials['email'] = "stevetest@consumerdirect.com";
//        $credentials['password'] = "123456789";
            $params = json_encode($credentials);

            $URL = $this->SMART_CREDIT_HTML_URL;

            if(config('app.SMART_CREDIT_REPORT_BY_JSON') == '1') {

                $URL = $this->SMART_CREDIT_JSON_URL;
            }

            $curlRequest = new CurlRequest();

            $response = $curlRequest->makeCurlRequest($params,'POST', $URL);

            if ($response == "ERROR" || $response == "TIME_OUT" || $response == "INVALID_LOGIN" ) {
                $result['message'] = config('constant.SCRAPPER_RESPONSE'.'.'.$response);
                throw new \Exception('Report not found');
            }

            if (!empty($response)) {
                $result['status'] = true;
                $result['html'] = $response;
                $result['message'] = 'User is valid.';
            }
            $logData['user_info'] = $credentials['email'];
            $logData['status'] =  $result['status'];

        }catch (\Exception $ex){
            $logData['data']['response'] = $response;
            $logData['data']['credentials'] = $credentials['email'];

        }

        appLog($logData);

        return $result;
    }
    public static function getCreditReportContent($user_id,$file_name){
        if(empty($user_id) || empty($file_name)){
            return "";
        }
        $file_path = config('constant.CREDIT_REPORT_CONTENT_PATH').DIRECTORY_SEPARATOR.$user_id.DIRECTORY_SEPARATOR.$file_name ?? "";
        return getFile($file_path);
    }
    public function getUpdatedReport($user_id,$report_type,$ssn){
        $reportContent = [];

        try {
               $creditReportDataObj = (new Creditreport())->getCreditReportInfoByUserIdAndType($user_id, $report_type);
               /*$creditReportDataObj->email = "stevetest@consumerdirect.com";*/

               /*$reportContent = $this->getSmartCreditHTML("stevetest@consumerdirect.com", "123456789");
               $reportContent = $this->getIdentityIQHTML("faust_89@ukr.net", "Faust_4639672",'5150');
               $reportContent['status'] = true;*/
               if (!empty($creditReportDataObj)) {
                   $creditReportDataObj->password = customDecrypt($creditReportDataObj->password);
                   if($report_type == config('constant.reportType.SMART_CREDIT')) {
                       $reportContent = $this->getSmartCreditHTML($creditReportDataObj->email, $creditReportDataObj->password);
//                       $reportContent = $this->getSmartCreditHTML("stevetest@consumerdirect.com", "123456789");
                   }else if($report_type == config('constant.reportType.IDENTITY_IQ')){
                       $reportContent = $this->getIdentityIQHTML($creditReportDataObj->email, $creditReportDataObj->password,$ssn);
//                       $reportContent = $this->getIdentityIQHTML("faust_89@ukr.net", "Faust_4639672",'5150');
                   }
                   $reportContent['credit_report_file_name'] = $creditReportDataObj->file_name ?? "";
                   $reportContent['credit_report_user_obj']=$creditReportDataObj;
               }else{
                   $reportContent['status'] = false;
               }
            }
        catch (\Exception $ex){

            $reportContent['status'] = false;
            $reportContent['message'] = $ex->getMessage();

        }

        return $reportContent;
    }
    public function uploadCreditReport($inputData)
    {
        return (new Creditreport())->updateCreditReport($inputData);
    }
    public function validateUserInCreditReportProvider($inputData){
        $reportContent = [];
        try {
                if($inputData['source_type']  == config('constant.reportType.SMART_CREDIT')) {
                    $reportContent = $this->getSmartCreditHTML($inputData['email'], $inputData['password']);
//                       $reportContent = $this->getSmartCreditHTML("stevetest@consumerdirect.com", "123456789");
                }else if($inputData['source_type']  == config('constant.reportType.IDENTITY_IQ')){
                    $reportContent = $this->getIdentityIQHTML($inputData['email'], $inputData['password'], $inputData['ssn']);
//                       $reportContent = $this->getIdentityIQHTML("faust_89@ukr.net", "Faust_4639672",'5150');
                }

        }
        catch (\Exception $ex){

            $reportContent['status'] = false;
            $reportContent['message'] = $ex->getMessage();

        }

        return $reportContent;
    }

    public function sampledata(){
       $data = [
                "button_type" => 1,
                "ip" => "206.206.124.81:6662",
                "page" => "Dashboard.aspx",
                "page_code" => 403,
                "data" => "ERROR",
                "status_code" => 408
             ];
       return $data;
    }
}
