<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\BureauLog;
use App\Slack;

class Equifax{

    private $request;
    private $application_id;
    private $applicant_type;
    public $response = [];
    public $error = "";
    private $filePath = null;
    public $panVendor = "";

    public function __construct(Request $request){
        $this->request = $request;
    }

    public function parseResponse($isParse = true){

        $this->application_id = $this->request->get('application_id');
        $this->applicant_type = $this->request->get('applicant_type');
        $request_type = $this->request->get('request_type');
        $applicant_type = ((int)$this->applicant_type == 1 || $this->applicant_type == '1') ? '' : '_'.$this->applicant_type;

        try {
            //(new Slack(new Request(['title' => 'parseResponse inter', 'fields' => ['parseResponse' => 1, 'e1' => $isParse], 'group' => Slack::$STAGE_TESTING])))->send();
            //$this->filePath = $filePath = "/var/www/html/equifax/".$this->application_id."_response".$applicant_type.".json";
            $this->filePath = $filePath = $this->application_id."/".$this->application_id."_response".$applicant_type.".json";
            (new Slack(new Request(['title' => 'parseResponse inter', 'fields' => ['parseResponse' => 1, 'e1' => $filePath], 'group' => Slack::$STAGE_TESTING])))->send();
            try{
                $file = $this->getData($filePath);
            }catch (\Exception $e) {
                (new Slack(new Request(['title' => 'exception in getting bureau', 'fields' => ['error' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()], 'group' => Slack::$STAGE_TESTING])))->send();
            }
//            (new Slack(new Request(['title' => 'parseResponse inter', 'fields' => ['parseResponse' => 1, 'e1' => $file], 'group' => Slack::$STAGE_TESTING])))->send();
            if($file instanceof Equifax){
                $this->error = 'Can\'t generate equifax at this time';
                return $this->error;
            }

            if($this->request->has('error_check'))
                return $this->getError($file);
            if (!$isParse)
                return $this->getParsedData($file);
            if ($file){
                (new Slack(new Request(['title' => 'equifax file', 'fields' => ['start' => 1, 'e1' => $file], 'group' => Slack::$STAGE_TESTING])))->send();
                return $this->start($file);
            }
        }catch (\Exception $e) {
            $this->error = 'Exception occured';
            if (!$isParse)
                return ['e' => $e->getTraceAsString(), 'm' => $e->getMessage(), 'l' => $e->getLine()];
            return $this;
        }
    }

    public function getError($data){

        $_error = false;
        if (isset($data['soapenv:Envelope']['soapenv:Body']) && $body = $data['soapenv:Envelope']['soapenv:Body']){
            $body = $body['sch:InquiryResponse'];
            if (isset($body["sch:ReportData"])) {
                $ReportData = $body["sch:ReportData"];
                if (isset($ReportData["sch:Error"])) {
                    $_error = "Something Went wrong";
                    $ErrorMessage = $ReportData["sch:Error"];
                    if (isset($ErrorMessage["sch:ErrorMsg"])) {
                        $_error = $ErrorMessage["sch:ErrorMsg"];
                    }
                }

                if(!$_error){
                    if (isset($ReportData['sch:VerifyIDResponse'])){
                        $VerifyIDResponse = $ReportData['sch:VerifyIDResponse'];
                        if(isset($VerifyIDResponse['sch:vidNsdlResponses'])) {
                            $vidNsdlResponses = $VerifyIDResponse['sch:vidNsdlResponses'];
                            if (isset($vidNsdlResponses['sch:nsdlResponse'])) {
                                $nsdlResponse = $vidNsdlResponses['sch:nsdlResponse'];
                                if (isset($nsdlResponse['sch:returnCodeDesc']) && $nsdlResponse['sch:returnCodeDesc']) {
                                    $_error = $nsdlResponse["sch:returnCodeDesc"];
                                }
                            }
                        }
                    }
                }
            }
        }else if (isset($data['Body']['ProcessResponse']['Out']['INProfileResponse']['UserMessage']['UserMessageText']) && $data['Body']['ProcessResponse']['Out']['INProfileResponse']['UserMessage']['UserMessageText']){
            $_error = $data['Body']['ProcessResponse']['Out']['INProfileResponse']['UserMessage']['UserMessageText'];
        }

        return $_error;
    }

    public function getData($file_path){

        if(false !== $data = self::readFile($file_path)) {
//            (new Slack(new Request(['title' => 'readFile', 'fields' => ['parseResponse' => $data,'file_path' => $file_path], 'group' => Slack::$STAGE_TESTING])))->send();
            return json_decode($data, 1);
        } else {
//            (new Slack(new Request(['title' => 'readFile fail', 'fields' => ['parseResponse' => $data,'file_path' => $file_path], 'group' => Slack::$STAGE_TESTING])))->send();
            $this->error = "Unable to open file";
            return $this;
        }
        /*$mFile = fopen($file_path, "r") or die("Unable to open file!");
        if($mFile) {
            $file = fread($mFile, filesize($file_path));
            fclose($mFile);
            return json_decode($file, true);
        }else{
            $this->error = "Unable to open file";
            return $this;
        }*/
    }

    public static function readFile($file_path) {
        try {
            $file_path = strpos($file_path, '_.') ? str_replace('_.', '.', $file_path) : $file_path;
            $s3 = Storage::disk('s3');
//            (new Slack(new Request(['title' => 'readFile checking', 'fields' => ['file_path' => $file_path], 'group' => Slack::$STAGE_TESTING])))->send();
            if ($s3->exists($file_path)) {
//                (new Slack(new Request(['title' => 'equifax readFile exists', 'fields' => ['exists' => 1,'file_path' => $file_path], 'group' => Slack::$STAGE_TESTING])))->send();
                return $s3->get($file_path);
            }else{
//                (new Slack(new Request(['title' => 'experian readFile checking', 'fields' => ['check' => 1, 'file_path' => $file_path], 'group' => Slack::$STAGE_TESTING])))->send();
                $file_path = str_replace('.json', '_experian.json', $file_path);
                if ($s3->exists($file_path)) {
//                    (new Slack(new Request(['title' => 'experian readFile exists', 'fields' => ['exists' => 1, 'file_path' => $file_path], 'group' => Slack::$STAGE_TESTING])))->send();
                    return $s3->get($file_path);
                }
            }
            return false;
        } catch (\Exception $e) {
            //@todo: report if file do not exist on S3
            return false;
        }
    }

    public static function isFileExist($file_path) {
        try {
            $s3 = Storage::disk('s3');
            if ($s3->exists($file_path)) {
                return true;
            }else{
                $file_path = str_replace('.json', '_experian.json', $file_path);
                if ($s3->exists($file_path)) {
                    return true;
                }
            }
            return false;
        } catch (\Exception $e) {
            //@todo: report if file do not exist on S3
            return false;
        }
    }

    public static function moveFile($old_path, $new_path) {
        try {
            $s3 = Storage::disk('s3');
            if ($s3->exists($old_path)) {
                return $s3->move($old_path, $new_path);
            }else{
                $old_path = str_replace('.json', '_experian.json', $old_path);
                $new_path = str_replace('.json', '_experian.json', $new_path);
                if ($s3->exists($old_path)) {
                    return $s3->move($old_path, $new_path);
                }
            }
            return false;
        } catch (\Exception $e) {
            //@todo: report if file do not exist on S3
            return false;
        }
    }

    public function start($data){
        if (isset($data['soapenv:Envelope']['soapenv:Body']) && $body = $data['soapenv:Envelope']['soapenv:Body']){
            return $response = $this->getAccountInfo($body);
        }
    }

    public function getPanValidationData($panData = array())
    {

        if (!$this->application_id) {
            $this->application_id = $this->request->get('application_id');
        }
        if (!$this->applicant_type) {
            $this->applicant_type = $this->request->get('applicant_type');
        }

        $applicant_type = (empty($this->applicant_type) || $this->applicant_type == 1) ? '' : '_'.$this->applicant_type;

        $filePath = $this->application_id.'/'.$this->application_id."_response_pan_valid".$applicant_type.".json";

        if (self::isFileExist($filePath)) {
            $file = $this->getData($filePath);
            if (isset($file['soapenv:Envelope']['soapenv:Body']) && isset($file['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse']) && $body = $file['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse']) {
                if (isset($body["sch:ReportData"])) {
                    if (isset($body["sch:ReportData"]["sch:VerifyIDResponse"])) {
                        if (isset($body["sch:ReportData"]["sch:VerifyIDResponse"]["sch:vidNsdlResponses"])) {
                            if (isset($body["sch:ReportData"]["sch:VerifyIDResponse"]["sch:vidNsdlResponses"]["sch:nsdlResponse"])) {
                                return $body["sch:ReportData"]["sch:VerifyIDResponse"]["sch:vidNsdlResponses"]["sch:nsdlResponse"];
                            }
                        }
                    }
                }
            }
        }else if(isset($panData['response'])){
            $s3 = Storage::disk('s3');
            $s3->put($filePath, $panData['response']);
            $file = json_decode($panData['response'], 1);
            if (isset($file['soapenv:Envelope']['soapenv:Body']) && isset($file['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse']) && $body = $file['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse']) {
                if (isset($body["sch:ReportData"])) {
                    if (isset($body["sch:ReportData"]["sch:VerifyIDResponse"])) {
                        if (isset($body["sch:ReportData"]["sch:VerifyIDResponse"]["sch:vidNsdlResponses"])) {
                            if (isset($body["sch:ReportData"]["sch:VerifyIDResponse"]["sch:vidNsdlResponses"]["sch:nsdlResponse"])) {
                                return $body["sch:ReportData"]["sch:VerifyIDResponse"]["sch:vidNsdlResponses"]["sch:nsdlResponse"];
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    public function getAccountData($accounts){
        $activeCreditCardLimit = 0;
        $sanctionAmount = 0;
        $historyType = [];
        $timestamp = Carbon::now()->toDateTimeString();

        if(isset($accounts["sch:History48Months"]["sch:Month"]["sch:PaymentStatus"])) {
            $historyType = $accounts["sch:History48Months"]["sch:Month"]["sch:PaymentStatus"];
        }else {
            foreach($accounts["sch:History48Months"]["sch:Month"] as $history) {
                $historyType[] = $history["sch:PaymentStatus"];
            }
        }

        if (isset($accounts["sch:AccountType"]) and $accounts["sch:AccountType"] == "Credit Card" and isset($accounts["sch:CreditLimit"]) and $accounts["sch:Open"] == "Yes") {
            $activeCreditCardLimit = (double) $accounts["sch:CreditLimit"];
        }

        if (isset($accounts["sch:Open"]) and $accounts["sch:Open"] == "Yes" and isset($accounts["sch:SanctionAmount"])) {
            $sanctionAmount = (double)$accounts["sch:SanctionAmount"];
        }elseif(isset($accounts["sch:Open"]) and $accounts["sch:Open"] == "Yes" and isset($accounts["sch:AccountType"]) and $accounts["sch:AccountType"] == "Credit Card"){
            if(isset($accounts["sch:CreditLimit"])) {
                $sanctionAmount = (double) $accounts["sch:CreditLimit"];
            }elseif(isset($accounts["sch:HighCredit"])){
                $sanctionAmount = (double) $accounts["sch:HighCredit"];
            }
        }

        $ApprovedAmount = 0;


        $AccountDetails = $this->accountDetails($accounts);
        $cc_loan = 0;
        $Balance = $AccountDetails["Balance"];
        $ReportedDate = $AccountDetails["ReportedDate"];
        $InterestRate = $AccountDetails["InterestRate"];
        $DateOpened = $AccountDetails["DateOpened"];
        $DateClosed = $AccountDetails["DateClosed"];
        $OwnershipType = $AccountDetails["OwnershipType"];
        $Institution = $AccountDetails["Institution"];
        $RepaymentTenure = $AccountDetails["RepaymentTenure"];
        $InstallmentAmount = $AccountDetails["InstallmentAmount"];
        $isOpened = $AccountDetails["isOpened"];
        $LastPayment = $AccountDetails["LastPayment"];
        $PastDueAmount = $AccountDetails["PastDueAmount"];
        $LastPaymentDate = $AccountDetails["LastPaymentDate"];

        $dpd = is_array($historyType) ? array_count_values($historyType) : [];

        if(isset($accounts["sch:AccountType"]) and $accounts["sch:AccountType"] != "Credit Card") {
            $cc_loan = 1;
            if (isset($accounts["sch:SanctionAmount"])) {
                $ApprovedAmount = $accounts["sch:SanctionAmount"];
                if (!$ApprovedAmount)
                    $ApprovedAmount = 0;
            }

        }elseif(isset($accounts["sch:AccountType"]) and $accounts["sch:AccountType"] == "Credit Card"){
            $cc_loan = 0;
            if(isset($accounts["sch:CreditLimit"])) {
                $ApprovedAmount = $accounts["sch:CreditLimit"];
                if (!$ApprovedAmount)
                    $ApprovedAmount = isset($accounts["sch:HighCredit"]) ? $accounts["sch:HighCredit"] : 0;
            }

            if(!$InstallmentAmount) {
                if ($ApprovedAmount)
                    $InstallmentAmount = $ApprovedAmount;
            }
        }

        $foir = [
            'application_id' => $this->application_id,
            'AccountType' => $accounts["sch:AccountType"],
            'ApprovedAmount' => (double)$ApprovedAmount,
            'Balance' => (double)$Balance,
            'ReportedDate' => $ReportedDate,
            'InterestRate' => $InterestRate,
            'RepaymentTenure' => (int)$RepaymentTenure,
            'InstallmentAmount' => (double)$InstallmentAmount,
            'cc_loan' => $cc_loan,
            'DateOpened' => $DateOpened,
            'DateClosed' => $DateClosed,
            'OwnershipType' => $OwnershipType,
            'Institution' => $Institution,
            'isOpened' => $isOpened,
            'LastPayment' => $LastPayment,
            'PastDueAmount' => $PastDueAmount,
            'applicant_type' => empty($this->applicant_type) ? 1 : $this->applicant_type,
            'dpd' => json_encode($dpd),
            'LastPaymentDate' => $LastPaymentDate,
            'created_at' => $timestamp];

        return [$activeCreditCardLimit, $sanctionAmount, $foir];
    }

    public function accountDetails($accounts){

        $Balance = isset($accounts["sch:Balance"]) && $accounts["sch:Balance"] ? $accounts["sch:Balance"] : 0;
        $ReportedDate = isset($accounts["sch:DateReported"]) && $accounts["sch:DateReported"] ? $accounts["sch:DateReported"] : null;
        $InterestRate = isset($accounts["sch:InterestRate"]) && $accounts["sch:InterestRate"] ? $accounts["sch:InterestRate"] : 0;
        $DateOpened = isset($accounts["sch:DateOpened"]) && $accounts["sch:DateOpened"] ? $accounts["sch:DateOpened"].' 00:00:00' : null;
        $OwnershipType = isset($accounts["sch:OwnershipType"]) && $accounts["sch:OwnershipType"] ? $accounts["sch:OwnershipType"] : '';
        $DateClosed = isset($accounts["sch:DateClosed"]) && $accounts["sch:DateClosed"] ? $accounts["sch:DateClosed"] : null;
        $Institution = isset($accounts["sch:Institution"]) && $accounts["sch:Institution"] ? $accounts["sch:Institution"] : 0;
        $PastDueAmount = isset($accounts["sch:PastDueAmount"]) && $accounts["sch:PastDueAmount"] ? $accounts["sch:PastDueAmount"] : 0;
        $LastPayment = isset($accounts["sch:LastPayment"]) && $accounts["sch:LastPayment"] ? $accounts["sch:LastPayment"] : 0;
        $LastPaymentDate = isset($accounts["sch:LastPaymentDate"]) && $accounts["sch:LastPaymentDate"] ? $accounts["sch:LastPaymentDate"] : null;
        $RepaymentTenure = isset($accounts["sch:RepaymentTenure"]) && $accounts["sch:RepaymentTenure"] ? $accounts["sch:RepaymentTenure"] : 0;

        $InstallmentAmount = isset($accounts["sch:InstallmentAmount"]) && $accounts["sch:InstallmentAmount"] ? $accounts["sch:InstallmentAmount"] : 0;
        $isOpened = isset($accounts["sch:Open"]) && $accounts["sch:Open"] == 'Yes' ? 1 : 0;

        return [
            'Balance' => $Balance,
            'ReportedDate' => $ReportedDate,
            'InterestRate' => $InterestRate,
            'DateOpened' => $DateOpened,
            'OwnershipType' => $OwnershipType,
            'Institution' => $Institution,
            'RepaymentTenure' => $RepaymentTenure,
            'InstallmentAmount' => $InstallmentAmount,
            'isOpened' => $isOpened,
            'PastDueAmount' => $PastDueAmount,
            'DateClosed' => $DateClosed,
            'LastPayment' => $LastPayment,
            'LastPaymentDate' => $LastPaymentDate
        ];
    }

    public function getAccountInfo($body)
    {
        $body = $body['sch:InquiryResponse'];

        $panData = $this->getPanValidationData();

        $activeCreditCardLimit = 0;
        $sanctionAmount = 0;
        $VoterIDList = [];
        $historyType = [];
        $contactInfoList = [];
        $PANIdsList = [];
        $AddressInfoList = [];
        $NationalIdsList = [];
        $NoOfActiveAccounts = 0;
        $TotalPastDue = 0;
        $Score = 0;
        $errorMessage = '';
        $Past12Months = 0;
        $Past24Months = 0;
        $TotalEnquiry = 0;
        $DateOfBirth = null;
        $zeroBalanceAccount = 0;
        $pastDueAccount = 0;
        $foir = [];


        $ReportData = isset($body['sch:ReportData']) ? $body['sch:ReportData'] : '';
        $ScoreData = isset($ReportData['sch:Score']) ? $ReportData['sch:Score'] : '';
        $AccountSummary = isset($ReportData['sch:AccountSummary']) ? $ReportData['sch:AccountSummary'] : '';

        $NoOfActiveAccounts = isset($AccountSummary["sch:NoOfActiveAccounts"]) ? $AccountSummary["sch:NoOfActiveAccounts"] : 0;
        $TotalPastDue = isset($AccountSummary["sch:TotalPastDue"]) ? $AccountSummary["sch:TotalPastDue"] : 0;
        /*$NoOfAccounts = $AccountSummary["sch:NoOfAccounts"];
        $NoOfWriteOffs = $AccountSummary["sch:NoOfWriteOffs"];
        $MostSevereStatusWithIn24Months = $AccountSummary["sch:MostSevereStatusWithIn24Months"];
        $SingleHighestCredit = $AccountSummary["sch:SingleHighestCredit"];
        $SingleHighestSanctionAmount = $AccountSummary["sch:SingleHighestSanctionAmount"];
        $TotalHighCredit = $AccountSummary["sch:TotalHighCredit"];
        $AverageOpenBalance = $AccountSummary["sch:AverageOpenBalance"];
        $SingleHighestBalance = $AccountSummary["sch:SingleHighestBalance"];
        $NoOfPastDueAccounts = $AccountSummary["sch:NoOfPastDueAccounts"];
        $NoOfZeroBalanceAccounts = $AccountSummary["sch:NoOfZeroBalanceAccounts"];
        $RecentAccount = $AccountSummary["sch:RecentAccount"];
        $OldestAccount = $AccountSummary["sch:OldestAccount"];
        $TotalBalanceAmount = $AccountSummary["sch:TotalBalanceAmount"];
        $TotalSanctionAmount = $AccountSummary["sch:TotalSanctionAmount"];
        $TotalCreditLimit = $AccountSummary["sch:TotalCreditLimit"];
        $TotalMonthlyPaymentAmount = $AccountSummary["sch:TotalMonthlyPaymentAmount"];*/


        if (isset($body["sch:ReportData"])) {
            $ReportData = $body["sch:ReportData"];
            if (isset($ReportData["sch:Error"])) {
                $this->error = "Something Went wrong";
                $ErrorMessage = $ReportData["sch:Error"];
                if (isset($ErrorMessage["sch:ErrorMsg"])) {
                    $this->error = $ErrorMessage["sch:ErrorMsg"];
                }
            }

            if ($this->error == 'Consumer record not found'){
                $this->error = '';
            }

            if(!$this->error) {
                if (isset($ReportData["sch:AccountSummary"])) {
                    $AccountDetails = $ReportData["sch:AccountDetails"];
                    if ($ReportData["sch:IDAndContactInfo"]) {
                        $IDAndContactInfo = $ReportData["sch:IDAndContactInfo"];
                        if (isset($IDAndContactInfo["sch:PhoneInfo"])) {
                            if (isset($IDAndContactInfo["sch:PhoneInfo"]["sch:Number"])) {
                                $contactInfoList[] = $IDAndContactInfo["sch:PhoneInfo"]["sch:Number"];
                            } else {
                                foreach ($IDAndContactInfo["sch:PhoneInfo"] as $contactInfo) {
                                    $contactInfoList[] = $contactInfo["sch:Number"];
                                }
                            }
                        }
                        if (isset($IDAndContactInfo["sch:PersonalInfo"])) {
                            if (isset($IDAndContactInfo["sch:PersonalInfo"]["sch:DateOfBirth"]))
                                $DateOfBirth = $IDAndContactInfo["sch:PersonalInfo"]["sch:DateOfBirth"];
                        }

                        if (isset($IDAndContactInfo["sch:IdentityInfo"])) {
                            if (isset($IDAndContactInfo["sch:IdentityInfo"]["sch:VoterID"])) {
                                if (isset($IDAndContactInfo["sch:IdentityInfo"]["sch:VoterID"]["sch:IdNumber"])) {
                                    $VoterIDList = $IDAndContactInfo["sch:IdentityInfo"]["sch:VoterID"]["sch:IdNumber"];
                                } else {
                                    foreach ($IDAndContactInfo["sch:IdentityInfo"]["sch:VoterID"] as $VoterIDs) {
                                        $VoterIDList[] = $VoterIDs["sch:IdNumber"];
                                    }
                                }
                            }
                            if (isset($IDAndContactInfo["sch:IdentityInfo"]["sch:PANId"])) {
                                if (isset($IDAndContactInfo["sch:IdentityInfo"]["sch:PANId"]["sch:IdNumber"])) {
                                    $PANIdsList[] = $IDAndContactInfo["sch:IdentityInfo"]["sch:PANId"]["sch:IdNumber"];
                                } else {
                                    foreach ($IDAndContactInfo["sch:IdentityInfo"]["sch:PANId"] as $PANIds) {
                                        $PANIdsList[] = $PANIds["sch:IdNumber"];
                                    }
                                }
                            }

                            if (isset($IDAndContactInfo["sch:IdentityInfo"]["sch:NationalIDCard"])) {
                                if (isset($IDAndContactInfo["sch:IdentityInfo"]["sch:NationalIDCard"]["sch:IdNumber"])) {
                                    $NationalIdsList[] = $IDAndContactInfo["sch:IdentityInfo"]["sch:NationalIDCard"]["sch:IdNumber"];
                                } else {
                                    foreach ($IDAndContactInfo["sch:IdentityInfo"]["sch:NationalIDCard"] as $PANIds) {
                                        $NationalIdsList[] = $PANIds["sch:IdNumber"];
                                    }
                                }
                            }
                        }

                        if (isset($IDAndContactInfo["sch:AddressInfo"])) {

                            if (isset($IDAndContactInfo["sch:AddressInfo"]["@seq"])) {
                                $Postal = isset($IDAndContactInfo["sch:AddressInfo"]["sch:Postal"]) ? $IDAndContactInfo["sch:AddressInfo"]["sch:Postal"] : '';
                                $Address = isset($IDAndContactInfo["sch:AddressInfo"]["sch:Address"]) ? $IDAndContactInfo["sch:AddressInfo"]["sch:Address"] : '';
                                $Type = isset($IDAndContactInfo["sch:AddressInfo"]["sch:Type"]) ? $IDAndContactInfo["sch:AddressInfo"]["sch:Type"] : '';
                                $State = isset($IDAndContactInfo["sch:AddressInfo"]["sch:State"]) ? $IDAndContactInfo["sch:AddressInfo"]["sch:State"] : '';

                                $AddressInfoList[] = ['Postal' => $Postal, 'Address' => $Address, 'Type' => $Type, 'State' => $State];
                            } else {
                                foreach ($IDAndContactInfo["sch:AddressInfo"] as $AddressInfo) {
                                    $Postal = isset($AddressInfo["sch:Postal"]) ? $AddressInfo["sch:Postal"] : '';
                                    $Address = isset($AddressInfo["sch:Address"]) ? $AddressInfo["sch:Address"] : '';
                                    $Type = isset($AddressInfo["sch:Type"]) ? $AddressInfo["sch:Type"] : '';
                                    $State = isset($AddressInfo["sch:State"]) ? $AddressInfo["sch:State"] : '';

                                    $AddressInfoList[] = ['Postal' => $Postal, 'Address' => $Address, 'Type' => $Type, 'State' => $State];
                                }
                            }

                        }

                        if (isset($AccountDetails["sch:Account"]["@seq"])) {
                            $detailsView = $this->getAccountData($AccountDetails["sch:Account"]);
                            $activeCreditCardLimit += $detailsView[0];
                            $sanctionAmount += $detailsView[1];
                            $foir[] = $detailsView[2];
                        } else {
                            foreach ($AccountDetails["sch:Account"] as $accounts) {
                                $detailsView = $this->getAccountData($accounts);
                                $activeCreditCardLimit += $detailsView[0];
                                $sanctionAmount += $detailsView[1];
                                $foir[] = $detailsView[2];
                            }
                        }
                    }
                }
                $this->response = [
                    'application_id' => $this->application_id,
                    'Score' => isset($ScoreData['sch:Value']) ? $ScoreData['sch:Value'] : '',
                    'NoOfActiveAccounts' => $NoOfActiveAccounts,
                    'activeCreditCardLimit' => $activeCreditCardLimit,
                    'sanctionAmount' => $sanctionAmount,
                    'TotalPastDue' => $TotalPastDue,
                    'Past12Months' => $Past12Months,
                    'Past24Months' => $Past24Months,
                    'TotalEnquiry' => $TotalEnquiry,
                    'zeroBalanceAccount' => $zeroBalanceAccount,
                    'pastDueAccount' => $pastDueAccount,
                    'applicant_type' => empty($this->applicant_type) ? 1 : $this->applicant_type,
                    'VoterID' => json_encode($VoterIDList),
                    'contactInfoList' => json_encode($contactInfoList),
                    'PANIdsList' => json_encode($PANIdsList),
                    'AddressInfoList' => json_encode($AddressInfoList),
                    'NationalIdsList' => json_encode($NationalIdsList),
                    'DateOfBirth' => $DateOfBirth,
                    'panValidation' => json_encode($panData),
                    'created_at' => Carbon::now()->toDateTimeString(),
                    'foir' => $foir
                ];
            }
        }

        return $this;
    }

    public function setRecord(){
        if(!$this->error) {
            $foirs = "";
            $this->response['panVendor'] = $this->panVendor;
            $creditReport = CreditReport::where('application_id', $this->application_id)->where('applicant_type', $this->applicant_type)->first(['id']);
            if (!isset($creditReport->id)) {
                if (isset($this->response['foir'])) {
                    $foirs = $this->response['foir'];
                    unset($this->response['foir']);
                }
                if (count($this->response) > 0) {
                    $creditID = CreditReport::insertGetId($this->response);
                }

                if ($foirs) {
                    foreach ($foirs as $key => $foir) {
                        $foirs[$key]['credit_id'] = $creditID;
                    }
                    FOIR::insert($foirs);
                }
            }
        }
        $this->saveEquifaxData();
        return $this;
    }

    public function getParsedData($data){
        $reportData = $data['soapenv:Envelope']['soapenv:Body']['sch:InquiryResponse']['sch:ReportData'];
        $response['IDAndContactInfo'] = isset($reportData['sch:IDAndContactInfo']) ? $reportData['sch:IDAndContactInfo'] : '';
        $response['Score'] = isset($reportData['sch:Score']) ? $reportData['sch:Score'] : '';
        $response['AccountSummary'] = isset($reportData['sch:AccountSummary']) ? $reportData['sch:AccountSummary'] : '';
        $response['Accounts'] = isset($reportData['sch:AccountDetails']['sch:Account']) ? $reportData['sch:AccountDetails']['sch:Account'] : '';
        $response['EnquirySummary'] = isset($reportData['sch:EnquirySummary']) ? $reportData['sch:EnquirySummary'] : '';
        return $response;
    }

    public function saveEquifaxData(){

        try {
            if(self::isFileExist($this->filePath)) {
                $id = $this->application_id;
                $id_type = $this->request->get('request_type') == 'customer' ? 'application_id' : 'merchant_id';
                $applicant_type = $this->applicant_type;
                $data = self::readFile($this->filePath);
                $data = json_decode(str_replace('sch:', '', str_replace('soapenv:', '', $data)), 1);

                $reportData = $data['Envelope']['Body']['InquiryResponse']['ReportData'];
                $unique_id = $data['Envelope']['Body']['InquiryResponse']['InquiryResponseHeader']['ReportOrderNO'];
                $IDAndContactInfo = $reportData['IDAndContactInfo'];
                $PersonalInfo = $IDAndContactInfo['PersonalInfo'];
                $IdentityInfo = $IDAndContactInfo['IdentityInfo'];
                $AddressInfo = $IDAndContactInfo['AddressInfo'];
                $PhoneInfo = $IDAndContactInfo['PhoneInfo'];
                $EmailAddressInfo = $IDAndContactInfo['EmailAddressInfo'];


                $ScoreData = $reportData['Score'];
                $AccountSummary = $reportData['AccountSummary'];
                $RecentActivities = $reportData['RecentActivities'];
                $OtherKeyInd = $reportData['OtherKeyInd'];
                $EnquirySummary = $reportData['EnquirySummary'];
                $AccountDetails = $reportData['AccountDetails'];

                $date = Carbon::now()->toDateTimeString();

                $equifax_report_id = EquifaxReport::insertGetId([
                    '_id' => $id,
                    'id_type' => $id_type,
                    'applicant_type' => $applicant_type,
                    'score' => isset($ScoreData['Value']) ? $ScoreData['Value'] : '',
                    'NoOfAccounts' => isset($AccountSummary['NoOfAccounts']) ? $AccountSummary['NoOfAccounts'] : '',
                    'NoOfActiveAccounts' => isset($AccountSummary['NoOfActiveAccounts']) ? $AccountSummary['NoOfActiveAccounts'] : '',
                    'NoOfWriteOffs' => isset($AccountSummary['NoOfWriteOffs']) ? $AccountSummary['NoOfWriteOffs'] : '',
                    'TotalPastDue' => isset($AccountSummary['TotalPastDue']) ? $AccountSummary['TotalPastDue'] : '',
                    'MostSevereStatusWithIn24Months' => isset($ScoreData['MostSevereStatusWithIn24Months']) ? $AccountSummary['MostSevereStatusWithIn24Months'] : '',
                    'SingleHighestCredit' => isset($AccountSummary['SingleHighestCredit']) ? $AccountSummary['SingleHighestCredit'] : '',
                    'SingleHighestSanctionAmount' => isset($AccountSummary['SingleHighestSanctionAmount']) ? $AccountSummary['SingleHighestSanctionAmount'] : '',
                    'TotalHighCredit' => isset($AccountSummary['TotalHighCredit']) ? $AccountSummary['TotalHighCredit'] : '',
                    'AverageOpenBalance' => isset($AccountSummary['AverageOpenBalance']) ? $AccountSummary['AverageOpenBalance'] : '',
                    'SingleHighestBalance' => isset($AccountSummary['SingleHighestBalance']) ? $AccountSummary['SingleHighestBalance'] : '',
                    'NoOfPastDueAccounts' => isset($AccountSummary['NoOfPastDueAccounts']) ? $AccountSummary['NoOfPastDueAccounts'] : '',
                    'NoOfZeroBalanceAccounts' => isset($AccountSummary['NoOfZeroBalanceAccounts']) ? $AccountSummary['NoOfZeroBalanceAccounts'] : '',
                    'RecentAccount' => isset($AccountSummary['RecentAccount']) ? $AccountSummary['RecentAccount'] : '',
                    'OldestAccount' => isset($AccountSummary['OldestAccount']) ? $AccountSummary['OldestAccount'] : '',
                    'TotalBalanceAmount' => isset($AccountSummary['TotalBalanceAmount']) ? $AccountSummary['TotalBalanceAmount'] : '',
                    'TotalSanctionAmount' => isset($AccountSummary['TotalSanctionAmount']) ? $AccountSummary['TotalSanctionAmount'] : '',
                    'TotalCreditLimit' => isset($AccountSummary['TotalCreditLimit']) ? $AccountSummary['TotalCreditLimit'] : '',
                    'TotalMonthlyPaymentAmount' => isset($AccountSummary['TotalMonthlyPaymentAmount']) ? $AccountSummary['TotalMonthlyPaymentAmount'] : '',
                    'AccountsDeliquent' => isset($RecentActivities['AccountsDeliquent']) ? $RecentActivities['AccountsDeliquent'] : '',
                    'AccountsOpened' => isset($RecentActivities['AccountsOpened']) ? $RecentActivities['AccountsOpened'] : '',
                    'TotalInquiries' => isset($RecentActivities['TotalInquiries']) ? $RecentActivities['TotalInquiries'] : '',
                    'AccountsUpdated' => isset($RecentActivities['AccountsUpdated']) ? $RecentActivities['AccountsUpdated'] : '',
                    'AgeOfOldestTrade' => isset($OtherKeyInd['AgeOfOldestTrade']) ? $OtherKeyInd['AgeOfOldestTrade'] : '',
                    'NumberOfOpenTrades' => isset($OtherKeyInd['NumberOfOpenTrades']) ? $OtherKeyInd['NumberOfOpenTrades'] : '',
                    'AllLinesEVERWritten' => isset($OtherKeyInd['AllLinesEVERWritten']) ? $OtherKeyInd['AllLinesEVERWritten'] : '',
                    'AllLinesEVERWrittenIn9Months' => isset($OtherKeyInd['AllLinesEVERWrittenIn9Months']) ? $OtherKeyInd['AllLinesEVERWrittenIn9Months'] : '',
                    'AllLinesEVERWrittenIn6Months' => isset($OtherKeyInd['AllLinesEVERWrittenIn6Months']) ? $OtherKeyInd['AllLinesEVERWrittenIn6Months'] : '',
                    'EnquiryPurpose' => isset($EnquirySummary['Purpose']) ? $EnquirySummary['Purpose'] : '',
                    'EnquiryTotal' => isset($EnquirySummary['Total']) ? $EnquirySummary['Total'] : '',
                    'EnquiryPast30Days' => isset($EnquirySummary['Past30Days']) ? $EnquirySummary['Past30Days'] : '',
                    'EnquiryPast12Months' => isset($EnquirySummary['Past12Months']) ? $EnquirySummary['Past12Months'] : '',
                    'EnquiryPast24Months' => isset($EnquirySummary['Past24Months']) ? $EnquirySummary['Past24Months'] : '',
                    'EnquiryRecent' => isset($EnquirySummary['Recent']) ? $EnquirySummary['Recent'] : '',
                    'created_at' => $date
                ]);


                if (isset($AccountDetails['Account'])) {
                    foreach ($AccountDetails['Account'] as $item) {
                        if($item) {
                            $accounts = [
                                'equifax_report_id' => $equifax_report_id,
                                'ReportedDate' => isset($item['@ReportedDate']) ? $item['@ReportedDate'] : '',
                                'AccountNumber' => isset($item['AccountNumber']) ? $item['AccountNumber'] : '',
                                'Institution' => isset($item['Institution']) ? $item['Institution'] : '',
                                'AccountType' => isset($item['AccountType']) ? $item['AccountType'] : '',
                                'OwnershipType' => isset($item['OwnershipType']) ? $item['OwnershipType'] : '',
                                'Balance' => isset($item['Balance']) ? $item['Balance'] : '',
                                'Open' => isset($item['Open']) ? $item['Open'] : '',
                                'SanctionAmount' => isset($item['SanctionAmount']) ? $item['SanctionAmount'] : '',
                                'DateReported' => isset($item['DateReported']) ? $item['DateReported'] : '',
                                'DateOpened' => isset($item['DateOpened']) ? $item['DateOpened'] : '',
                                'Reason' => isset($item['Reason']) ? $item['Reason'] : '',
                                'InterestRate' => isset($item['InterestRate']) ? $item['InterestRate'] : '',
                                'RepaymentTenure' => isset($item['RepaymentTenure']) ? $item['RepaymentTenure'] : '',
                                'DisputeCode' => isset($item['DisputeCode']) ? $item['DisputeCode'] : '',
                                'InstallmentAmount' => isset($item['InstallmentAmount']) ? $item['InstallmentAmount'] : '',
                                'TermFrequency' => isset($item['TermFrequency']) ? $item['TermFrequency'] : '',
                                'CollateralValue' => isset($item['CollateralValue']) ? $item['CollateralValue'] : '',
                                'CollateralType' => isset($item['CollateralType']) ? $item['CollateralType'] : '',
                                'AccountStatus' => isset($item['AccountStatus']) ? $item['AccountStatus'] : '',
                                'AssetClassification' => isset($item['AssetClassification']) ? $item['AssetClassification'] : '',
                                'SuitFiledStatus' => isset($item['SuitFiledStatus']) ? $item['SuitFiledStatus'] : '',
                                'created_at' => $date
                            ];

                            $equifax_account_id = EquifaxAccounts::insertGetId($accounts);


                            $history = [];
                            if (isset($item['History48Months']['Month'])) {
                                foreach ($item['History48Months']['Month'] as $historyItem) {
                                    $history[] = [
                                        'equifax_account_id' => $equifax_account_id,
                                        'PaymentStatus' => $historyItem['PaymentStatus'],
                                        'SuitFiledStatus' => $historyItem['SuitFiledStatus'],
                                        'AssetClassificationStatus' => $historyItem['AssetClassificationStatus'],
                                        'created_at' => $date
                                    ];
                                }

                                if (isset($history) && $history) {
                                    EquifaxAccountHistory::insert($history);
                                }
                            }
                        }
                    }
                }


                EquifaxReportContactInfo::insert([
                    'equifax_report_id' => $equifax_report_id,
                    'PersonalInfo' => json_encode($PersonalInfo),
                    'IdentityInfo' => json_encode($IdentityInfo),
                    'AddressInfo' => json_encode($AddressInfo),
                    'PhoneInfo' => json_encode($PhoneInfo),
                    'EmailAddressInfo' => json_encode($EmailAddressInfo),
                    'created_at' => $date
                ]);
                $rawData = self::readFile($this->filePath);
                BureauLog::insert([
                    'unique_id' => $unique_id,
                    'application_id' => $id,
                    'bureau_name' => 'equifax',
                    'raw_bureau_data' => $rawData,
                    'converted_bureau_data' => json_encode($data, true),
                    'applicant_type' =>$applicant_type,
                    'created_at' => $date,
                    'updated_at' => $date
                ]);
            }
        }catch (\Exception $e){

        }
    }
}
