<?php

namespace App\Http\Controllers;
use App\Models\Content;
use App\Utility\ActionLogCreate;
use Illuminate\Http\Request;

class BasicController extends Controller
{
    public function  termAndService(Request  $request)
    {
       if($request->isMethod('post'))
       {
           $action="TERMS AND SERVICE CREATE";
           $file_path = config('constant.CONTENT_DIR') . DIRECTORY_SEPARATOR ;
           $file_name = "terms_and_service.html";
           $inputData=['id'=>$request['id'],'terms_service'=>$file_path.$file_name];
           uploadHTML($file_path, $file_name, $request['body']);
           $returnData=(new Content())->insert($inputData);
           ActionLogCreate::logDataCreate($action,$request->all(),$returnData['message'],$returnData['data'],'');

           return back()->with('success',$returnData['message']);
       }
       $content=$this->getTermsAndCondition();
       return view('basic.terms_and_service_entry',compact('content'));
    }
    public function termsAndCondition()
    {
        $content=$this->getTermsAndCondition();
        return view('basic.terms_and_condition',compact('content'));
    }

    private function getTermsAndCondition()
    {
        $content=(new Content())->get();
        if(!empty($content)) {
            $content['terms_service'] = getFile($content['terms_service']);
            $content['title'] = 'terms and service';
        }
        return $content;
    }

    private function generateHtml()
    {
        $path = public_path('report/credit_report.json');
//        $path = public_path('report/credit_report2.json');
        $json_data = json_decode(file_get_contents($path),true);

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

        $json_data = $json_data[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);

        $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_set = $this->account_history_data_binding($json_data['TradeLinePartition']);

//        $html = view('partials.credit_report.personal_info', compact('personal_infos'))->render();
//        $html = view('partials.credit_report.summary',compact('summary_info_data_set'))->render();
//        $html = view('partials.credit_report.creditor_contact',compact('creditor_contact_data_set'))->render();
//        $html = view('partials.credit_report.inquiries',compact('inquiries_data_set'))->render();

        $html = view('partials.credit_report.main_report',compact('creditScore','personal_infos','summary_info_data_set','creditor_contact_data_set','inquiries_data_set','account_history_data_set'))->render();
//        dd($html);
        echo $html;exit;
    }

    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',
                'TransUnion'=> array_filter($personal_info_creditScore,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'TUC'){
                        return $item;
                    }
                }),
                'Experian'=>array_filter($personal_info_creditScore,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'EXP'){
                        return $item;
                    }
                }),
                'Equifax'=>array_filter($personal_info_creditScore,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'EQF'){
                        return $item;
                    }
                }),
                'css_class_1'=>'crLightTableBackground',
                'css_class_2'=>'crLightTableBackground'
            ],
            'NAME' =>[
                'title' => 'NAME',
                'TransUnion'=> array_filter($personal_info_borrowerName,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'TUC'){
                        return $item;
                    }
                }),
                'Experian'=>array_filter($personal_info_borrowerName,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'EXP'){
                        return $item;
                    }
                }),
                'Equifax'=>array_filter($personal_info_borrowerName,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'EQF'){
                        return $item;
                    }
                }),
                'css_class_1'=>'crTableHeader',
                'css_class_2'=>'crTableHeader'
            ],
            'ALSO_KNOWN_AS' =>[
                'title' => 'ALSO KNOWN AS',
                'TransUnion'=>[],
                'Experian'=>[],
                'Equifax'=>[],
                'css_class_1'=>'crTradelineHeader',
                'css_class_2'=>'crTableBackground'
            ],
            'DATE_OF_BIRTH'=>[
                'title' => 'DATE OF BIRTH',
                'TransUnion'=> array_filter($personal_info_birth,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'TUC'){
                        return $item;
                    }
                }),
                'Experian'=>array_filter($personal_info_birth,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'EXP'){
                        return $item;
                    }
                }),
                'Equifax'=>array_filter($personal_info_birth,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'EQF'){
                        return $item;
                    }
                }),
                'css_class_1'=>'crTableBackground',
                'css_class_2'=>'crTradelineHeader'

            ],
            'CURRENT_ADDRESS'=>[
                'title' => 'CURRENT ADDRESS',
                'TransUnion'=> array_filter($personal_info_borrowerAddress,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'TUC'){
                        return $item;
                    }
                }),
                'Experian'=>array_filter($personal_info_borrowerAddress,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'EXP'){
                        return $item;
                    }
                }),
                'Equifax'=>array_filter($personal_info_borrowerAddress,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'EQF'){
                        return $item;
                    }
                }),
                'css_class_1'=>'crLightTableBackground',
                'css_class_2'=>'crLightTableBackground'
            ],
            'PREVIOUS_ADDRESS'=>[
                'title' => 'PREVIOUS ADDRESS',
                'TransUnion'=> array_filter($personal_info_previousAddress,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'TUC'){
                        return $item;
                    }
                }),
                'Experian'=>array_filter($personal_info_previousAddress,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'EXP'){
                        return $item;
                    }
                }),
                'Equifax'=>array_filter($personal_info_previousAddress,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'EQF'){
                        return $item;
                    }
                }),
                'css_class_1'=>'crLightTableBackground',
                'css_class_2'=>'crLightTableBackground'


            ],
            'EMPLOYER'=>[
                'title' => 'EMPLOYER',

                'TransUnion'=> array_filter($personal_info_employer,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'TUC'){
                        return $item;
                    }
                }),
                'Experian'=>array_filter($personal_info_employer,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'EXP'){
                        return $item;
                    }
                }),
                'Equifax'=>array_filter($personal_info_employer,function ($item){
                    if($item['Source']['Bureau']['symbol'] == 'EQF'){
                        return $item;
                    }
                }),
                'css_class_1'=>'crTradelineHeader',
                'css_class_2'=>'crTradelineHeader'

            ],
        ];

        return $personal_info_data_set;
    }

    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'=> '$'.$summary_info['TradelineSummary']['TransUnion']['TotalBalances'],
                'Experian'=>'$'. $summary_info['TradelineSummary']['Experian']['TotalBalances'],
                'Equifax'=>'$'. $summary_info['TradelineSummary']['Equifax']['TotalBalances'],
            ],
            'PAYMENTS'=>[
                'title' => 'PAYMENTS',
                'TransUnion'=>'$'. $summary_info['TradelineSummary']['TransUnion']['TotalMonthlyPayments'],
                'Experian'=>'$'. $summary_info['TradelineSummary']['Experian']['TotalMonthlyPayments'],
                'Equifax'=>'$'. $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[$tradelines[0]['creditorName']] = ['key_data'=>$this->sub_account_history_data_bindings(),'data'=> $data];

        }
//         dd($account_history_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',
            ],

            '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;
    }

}
