<?php

namespace App\Services;

class SmartCreditJsonToHtml
{
    // convert to html start

    public  function generateHtml($json_data)
    {
        $json_data = json_decode($json_data,true);

        if(!empty($json_data['BundleComponents']['BundleComponent'][6]['TrueLinkCreditReportType'])) {

            $json_data = $json_data['BundleComponents']['BundleComponent'][6]['TrueLinkCreditReportType'];

            $borrower_info = $json_data['Borrower'];

            $credit_scores = $borrower_info['CreditScore'];

            $creditScore = [
                'title' => 'Vantage Score® 3.0 credit score',
                'TransUnion' => $credit_scores[0]['riskScore'],
                'Experian' => $credit_scores[1]['riskScore'],
                'Equifax' => $credit_scores[2]['riskScore'],
            ];

            $personal_infos = $this->personal_information_data_binding($borrower_info);

            $consumer_statement_data_set = $this->consumer_statement_data_binding($borrower_info);

            $summary_info_data_set = $this->summary_info_data_binding($json_data);

            $creditor_contact_data_set = $this->creditor_contacts_data_binding($json_data);

            $inquiries_data_set = $this->inquiries_data_binding($json_data);

            $account_history_data = $this->account_history_data_binding($json_data['TradeLinePartition']);

            $account_history_data_set = $this->account_history_filter_by_account_type($account_history_data);

            $data_set = ['creditScore'=>$creditScore,'personal_infos'=>$personal_infos,'consumer_statement_data_set'=>$consumer_statement_data_set,'summary_info_data_set'=>$summary_info_data_set,'creditor_contact_data_set'=>$creditor_contact_data_set,'inquiries_data_set'=>$inquiries_data_set,'account_history_data_set'=>$account_history_data_set];

            return $data_set;
//            $html = view('partials.credit_report.main_report', compact('creditScore', 'personal_infos','consumer_statement_data_set','summary_info_data_set', 'creditor_contact_data_set', 'inquiries_data_set', 'account_history_data_set'))->render();
//        dd($html);
        }
        return null;
    }
    private function personal_information_data_binding($borrower_info)
    {
        $personal_info_employer = [];
        $personal_info_birth = [];
        $personal_info_borrowerName = [];
        $personal_info_borrowerAddress = [];
        $personal_info_previousAddress = [];
        $personal_info_creditScore = [];

        if(isset($borrower_info['Employer']))
        {
            $personal_info_employer = $borrower_info['Employer'];
        }
        if(isset($borrower_info['Birth']))
        {
            $personal_info_birth = $borrower_info['Birth'];
        }
        if(isset($borrower_info['BorrowerName']))
        {
            $personal_info_borrowerName = $borrower_info['BorrowerName'];
        }
        if(isset($borrower_info['BorrowerAddress']))
        {
            $personal_info_borrowerAddress = $borrower_info['BorrowerAddress'];
        }
        if(isset($borrower_info['PreviousAddress']))
        {
            $personal_info_previousAddress = $borrower_info['PreviousAddress'];
        }
        if(isset($borrower_info['CreditScore']))
        {
            $personal_info_creditScore = $borrower_info['CreditScore'];
        }

        $personal_info_data_set = [
            'CREDIT_REPORT_DATE' =>[
                'title' => 'CREDIT REPORT DATE',
                'data' => $this->common_data_binding($personal_info_creditScore)
            ],
            'NAME' =>[
                'title' => 'NAME',
                'data' => $this->data_binding_for_name($personal_info_borrowerName)
            ],
            'ALSO_KNOWN_AS' =>[
                'title' => 'ALSO KNOWN AS',
                'data' => $this->data_binding_for_also_known_name($personal_info_borrowerName)
            ],
            'DATE_OF_BIRTH'=>[
                'title' => 'DATE OF BIRTH',
                'data' => $this->common_data_binding($personal_info_birth)

            ],
            'CURRENT_ADDRESS'=>[
                'title' => 'CURRENT ADDRESS',
                'data' => $this->common_data_binding($personal_info_borrowerAddress)

            ],
            'PREVIOUS_ADDRESS'=>[
                'title' => 'PREVIOUS ADDRESS',
                'data' => $this->common_data_binding($personal_info_previousAddress)
            ],
            'EMPLOYER'=>[
                'title' => 'EMPLOYER',
                'data' => $this->common_data_binding($personal_info_employer)
            ],
        ];

        return $personal_info_data_set;
    }

    private function consumer_statement_data_binding($borrower_info):array
    {
        $personal_info_consumer_statement = [];

        if(isset($borrower_info['CreditStatement']))
        {
            $personal_info_consumer_statement = $borrower_info['CreditStatement'];
        }

        return $this->common_data_binding($personal_info_consumer_statement);
    }

    private function inquiries_data_binding($inquiryPartition)
    {

        $inquiries_info = [];

        if(isset($inquiryPartition['InquiryPartition']))
        {
            $inquiries_info = $inquiryPartition['InquiryPartition'];
            if(count($inquiries_info)== 1) {
                $inquiries_info['Inquiry'] = $inquiryPartition['InquiryPartition'];
            }
        }
        return $inquiries_info;
    }

    private function creditor_contacts_data_binding($creditor_contact)
    {

        $creditor_contacts_info = [];

        if(isset($creditor_contact['Subscriber']))
        {
            $creditor_contacts_info = $creditor_contact['Subscriber'];
        }
        return $creditor_contacts_info;
    }

    private function summary_info_data_binding($summary)
    {

        $summary_info = [];

        if(isset($summary['Summary']))
        {
            $summary_info = $summary['Summary'];
        }

        $summary_info_data = [
            'TOTAL_ACCOUNTS' => [
                'title' => 'TOTAL ACCOUNTS',
                'TransUnion'=> $summary_info['TradelineSummary']['TransUnion']['TotalAccounts'],
                'Experian'=> $summary_info['TradelineSummary']['Experian']['TotalAccounts'],
                'Equifax'=> $summary_info['TradelineSummary']['Equifax']['TotalAccounts'],
            ],
            'OPEN_ACCOUNTS' => [
                'title' => 'OPEN ACCOUNTS',
                'TransUnion'=> $summary_info['TradelineSummary']['TransUnion']['OpenAccounts'],
                'Experian'=> $summary_info['TradelineSummary']['Experian']['OpenAccounts'],
                'Equifax'=> $summary_info['TradelineSummary']['Equifax']['OpenAccounts'],
            ],
            'CLOSED_ACCOUNTS' =>[
                'title' => 'CLOSED ACCOUNTS',
                'TransUnion'=> $summary_info['TradelineSummary']['TransUnion']['CloseAccounts'],
                'Experian'=> $summary_info['TradelineSummary']['Experian']['CloseAccounts'],
                'Equifax'=> $summary_info['TradelineSummary']['Equifax']['CloseAccounts'],
            ],
            'DELINQUENT'=>[
                'title' => 'DELINQUENT',
                'TransUnion'=> $summary_info['TradelineSummary']['TransUnion']['DelinquentAccounts'],
                'Experian'=> $summary_info['TradelineSummary']['Experian']['DelinquentAccounts'],
                'Equifax'=> $summary_info['TradelineSummary']['Equifax']['DelinquentAccounts'],
            ],
            'DEROGATORY'=>[
                'title' => 'DEROGATORY',
                'TransUnion'=> $summary_info['TradelineSummary']['TransUnion']['DerogatoryAccounts'],
                'Experian'=> $summary_info['TradelineSummary']['Experian']['DerogatoryAccounts'],
                'Equifax'=> '--',
            ],
            'BALANCES'=>[
                'title' => 'BALANCES',
                'TransUnion'=> amountFormatter($summary_info['TradelineSummary']['TransUnion']['TotalBalances']),
                'Experian'=>amountFormatter($summary_info['TradelineSummary']['Experian']['TotalBalances']),
                'Equifax'=>amountFormatter($summary_info['TradelineSummary']['Equifax']['TotalBalances']),
            ],
            'PAYMENTS'=>[
                'title' => 'PAYMENTS',
                'TransUnion'=>amountFormatter($summary_info['TradelineSummary']['TransUnion']['TotalMonthlyPayments']),
                'Experian'=>amountFormatter($summary_info['TradelineSummary']['Experian']['TotalMonthlyPayments']),
                'Equifax'=>amountFormatter($summary_info['TradelineSummary']['Equifax']['TotalMonthlyPayments']),
            ],
            'PUBLIC_RECORDS'=>[
                'title' => 'PUBLIC RECORDS',
                'TransUnion'=> $summary_info['PublicRecordSummary']['TransUnion']['NumberOfRecords'],
                'Experian'=> $summary_info['PublicRecordSummary']['Experian']['NumberOfRecords'],
                'Equifax'=> $summary_info['PublicRecordSummary']['Equifax']['NumberOfRecords'],
            ],
            'INQUIRIES'=>[
                'title' => 'INQUIRIES (2 years)',
                'TransUnion'=> $summary_info['InquirySummary']['TransUnion']['NumberInLast2Years'],
                'Experian'=> $summary_info['InquirySummary']['Experian']['NumberInLast2Years'],
                'Equifax'=> $summary_info['InquirySummary']['Equifax']['NumberInLast2Years'],
            ]
        ];

        return $summary_info_data;
    }

    private function account_history_data_binding($account_historys)
    {
        $account_history_data = [];

        foreach ($account_historys as $account_history )
        {
            $tradelines = $account_history['Tradeline'];

            if(isset($tradelines['subscriberCode']) && isset($tradelines['accountNumber'])
                && isset($tradelines['creditorName'])){

                $tradelines = [ $tradelines ];
            }

            $data = $this->common_data_binding($tradelines);

            $account_history_data[] = [
                'title'=> $tradelines[0]['creditorName'],
                'key_data'=>$this->sub_account_history_data_bindings(),
                "accountTypeDescription" => $account_history['accountTypeDescription'],
                "accountTypeSymbol" => $account_history['accountTypeSymbol'],
                "accountTypeAbbreviation" => $account_history['accountTypeAbbreviation'],
                'data'=> $data];
        }

        return $account_history_data;
    }

    private function sub_account_history_data_bindings()
    {
        $return_data = [

            'ACCOUNT'=> [
                'title' => 'Account #',

            ],
            'HIGH_BALANCE' => [
                'title' => 'High Balance',
            ],
            'LAST_VERIFIED' =>[
                'title' => 'Last Verified',
            ],

            'DATE_OF_LAST_ACTIVITY' =>[
                'title' => 'Date of Last Activity',
            ],
            'DATE_REPORTED'=>[
                'title' => 'Date Reported',
            ],
            'DATE_OPENED'=>[
                'title' => 'Date Opened',
            ],

            'BALANCE_OWED'=>[
                'title' => 'Balance Owed',
            ],
            'CLOSED_DATE'=>[
                'title' => 'Closed Date',
            ],
            'ACCOUNT_RATING'=>[
                'title' => 'Account Rating',
            ],

            'ACCOUNT_DESCRIPTION'=>[
                'title' => 'Account Description',
            ],

            'DISPUTE_STATUS'=>[
                'title' => 'Dispute Status',
            ],
            'CREDITOR_TYPE'=> [
                'title' => 'Creditor Type',
            ],

            'ACCOUNT_STATUS'=>[
                'title' => 'Account Status',
            ],
            'PAYMENT_STATUS'=> [
                'title' => 'Payment Status',
            ],
            'CREDITOR_REMARKS'=>[
                'title' => 'Creditor Remarks',
            ],
            'ORIGINAL_CREDITOR'=>[
                'title' => 'Original Creditor',
            ],
            'PAYMENT_AMOUNT'=> [
                'title' => 'Payment Amount',
            ],
            'LAST_PAYMENT'=>[
                'title' => 'Last Payment',
            ],
            'TERM_LENGTH'=>[
                'title' => 'Term Length',
            ],
            'PAST_DUE_AMOUNT'=>[
                'title' => 'Past Due Amount',
            ],
            'ACCOUNT_TYPE'=>[
                'title' => 'Account Type',
            ],
            'PAYMENT_FREQUENCY'=>[
                'title' => 'Payment Frequency',
            ],
            'CREDIT_LIMIT'=>[
                'title' => 'Credit Limit',
            ],
        ];

        return $return_data;
    }

    private function common_data_binding($data)
    {
        $data_set =  [
            'TransUnion'=> array_filter($data,function ($item){
                if($item['Source']['Bureau']['symbol'] == 'TUC'){
                    return $item;
                }
            }),
            'Experian'=>array_filter($data,function ($item){
                if($item['Source']['Bureau']['symbol'] == 'EXP'){
                    return $item;
                }
            }),
            'Equifax'=>array_filter($data,function ($item){
                if($item['Source']['Bureau']['symbol'] == 'EQF'){
                    return $item;
                }
            }),
        ];

        return $data_set;
    }
    private function data_binding_for_name($data)
    {
        $data_set =  [
            'TransUnion'=> array_filter($data,function ($item){
                if($item['Source']['Bureau']['symbol'] == 'TUC' && $item['NameType']['symbol'] == '1'){
                    return $item;
                }
            }),
            'Experian'=>array_filter($data,function ($item){
                if($item['Source']['Bureau']['symbol'] == 'EXP' && $item['NameType']['symbol'] == '1'){
                    return $item;
                }
            }),
            'Equifax'=>array_filter($data,function ($item){
                if($item['Source']['Bureau']['symbol'] == 'EQF' && $item['NameType']['symbol'] == '1'){
                    return $item;
                }
            }),
        ];

        return $data_set;
    }
    private function data_binding_for_also_known_name($data)
    {
        $data_set =  [
            'TransUnion'=> array_filter($data,function ($item){
                if($item['Source']['Bureau']['symbol'] == 'TUC' && $item['NameType']['symbol'] == 'A'){
                    return $item;
                }
            }),
            'Experian'=>array_filter($data,function ($item){
                if($item['Source']['Bureau']['symbol'] == 'EXP' && $item['NameType']['symbol'] == 'A'){
                    return $item;
                }
            }),
            'Equifax'=>array_filter($data,function ($item){
                if($item['Source']['Bureau']['symbol'] == 'EQF' && $item['NameType']['symbol'] == 'A'){
                    return $item;
                }
            }),
        ];

        return $data_set;
    }
    private function account_history_filter_by_account_type($data){

        $data_set =  [
            'Revolving'=> array_filter($data,function ($item){
                if($item['accountTypeSymbol'] == 'R'){
                    return $item;
                }
            }),
            'Installment' => array_filter($data,function ($item){
                if($item['accountTypeSymbol'] == 'I'){
                    return $item;
                }
            }),
            'Line_of_credit' => array_filter($data,function ($item){
                if($item['accountTypeSymbol'] == 'C'){
                    return $item;
                }
            }),
            'Collection' => array_filter($data,function ($item){
                if($item['accountTypeSymbol'] == 'Y'){
                    return $item;
                }
            }),
            'Other' => array_filter($data,function ($item){
                if($item['accountTypeSymbol'] == 'O'){
                    return $item;
                }
            }),

        ];

        return $data_set;

    }

}
