<?php

namespace App\Http\Controllers;



use App\Models\User;
use App\Models\UserWave;
use App\Models\WaveCycle;
use App\Services\SmartCreditJsonToHtml;
use App\Traits\ApiResponseTrait;
use App\Services\CreditReportService;
use App\Utility\ActionLogCreate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;


class CreditReportController extends Controller
{
    use ApiResponseTrait;
    private $message;
    private $code;
    private $data;
    private $credit_report_type;
    private $user_id;
    private $wave;
    private $last_import_date;
    private $type;
    private $ssn;

    public function __construct()
    {
        $this->message = 'Fail';
        $this->code = config('constant.API_FAILED_CODE');
        $this->data=[];
        $this->type='error';
    }
    public function setAuthUser(){
        $auth_user = auth()->user();
        $this->user_id = $auth_user->id;
        $this->credit_report_type = $auth_user->credit_report_company_type;
        $this->wave = $auth_user->wave;
        $this->last_import_date = $auth_user->last_import_date;
        $this->ssn = $auth_user->ssn;
    }
    public function getCreditReport(Request $request)
    {
        $this->setAuthUser();
        $inputData = $request->all();
        $response['status'] = false;
        $action='GET_CREDIT_REPORT';
        $this->message='Can not fetch Credit Report.';
        if($inputData['action'] == "GET_CREDIT_REPORT"){
            $creditReport = (new CreditReportService())->getUpdatedReport($this->user_id,$this->credit_report_type,$this->ssn);
            if($creditReport['status']){
                $response['status'] = true;
                if(config('app.SMART_CREDIT_REPORT_BY_JSON') == '1' && $this->credit_report_type == config('constant.reportType.SMART_CREDIT')) {
                    $creditReport['html'] = $this->generateHtml($creditReport['html']);
                }
                $response['data'] = $creditReport['html'];
                $this->type='success';
                $this->message='Credit Report is fetched successfully.';
            }
        }
        $requestData=[$this->user_id,$this->credit_report_type];
        ActionLogCreate::logDataCreate($action,$requestData,$this->message,$response['status'],$this->code);
        return response()->json($response,200);

    }
    public function uploadCreditReport(Request $request)
    {
            $this->setAuthUser();
            $action = 'UPLOAD_CREDIT_REPORT';
            $this->message = 'Credit Report uploaded Fail.';
            $inputData = $request->all();

            $inputData['user_id'] = $this->user_id;
            $inputData['report_type']=$this->credit_report_type;
            $creditReportResponse['status']=false;

            if(!empty($inputData['credithtml'])) {
                $creditReportResponse = (new CreditReportService())->uploadCreditReport($inputData);
                if($creditReportResponse['status'])
                {
                    if(getSession('video_first_time'))
                    {
                        unSetSession('video_first_time');
                        setSession('view_video_first_time',true);
                    }
                    $this->updateUserWave();

                    $this->type='success';
                    $this->message='Credit Report is uploaded successfully';
                    $this->code=config('constant.API_SUCCESS_CODE');
                }
                $this->data=$creditReportResponse;
            }
            $logRequestData=[$this->user_id,$this->credit_report_type];
            $logResponseData=[$this->code,$this->message];
            ActionLogCreate::logDataCreate($action,$logRequestData,$this->message,$logResponseData,$this->code);
            return back()->with([$this->type => $this->message]);
    }
    private function updateUserWave()
    {
        $this->setAuthUser();
        $days = getDateDifference($this->last_import_date,'day');

        $inputData['user_id'] = $this->user_id;

        if($days >= config('constant.PACKAGE_INTERVAL_DAY')){

            if($this->wave == config('constant.MAX_WAVE'))
            {
                (new WaveCycle())->insertUserWaveCycle($inputData);
            }

            $this->wave = $this->getUserWave();
            $this->last_import_date = getCurrentDateTime();
        }
        $inputData['wave'] = $this->wave;
        $inputData['last_import_date'] = $this->last_import_date;
        Auth::user()->update([
            'is_import' => config('constant.IMPORT_REPORT_STATUS.NOT_ELIGIBLE'),
            'wave' => $inputData['wave'],
            'last_import_date' => $inputData['last_import_date']
        ]);

        $userwave= (new UserWave())->insertUserWave($inputData);

        ActionLogCreate::logDataCreate('USER_WAVE_CREATE',$inputData,$userwave['message'],$userwave['data'],config('constant.API_SUCCESS_CODE'));

        return $userwave;
    }
    private function getUserWave()
    {
        $currentWave = 1;
        if($this->wave < config('constant.MAX_WAVE')){
            $currentWave = $this->wave + 1;
        }

        return $currentWave ;
    }
    private function generateHtml($json_data):string{

        $data_set = (new SmartCreditJsonToHtml())->generateHtml($json_data);
        $html = '';
        if($data_set != null) {
            $creditScore = $data_set['creditScore'];
            $personal_infos = $data_set['personal_infos'];
            $consumer_statement_data_set = $data_set['consumer_statement_data_set'];
            $summary_info_data_set = $data_set['summary_info_data_set'];
            $creditor_contact_data_set = $data_set['creditor_contact_data_set'];
            $inquiries_data_set = $data_set['inquiries_data_set'];
            $account_history_data_set = $data_set['account_history_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();

        }
        return $html;

    }

}
