<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

class Creditreport extends BaseModel
{
    use HasFactory;

    protected $fillable = ['user_id','file_name','email','password','report_type'];

    public function addOrUpdateCreditReport($inputData){
        $inserted = [];
        if(!empty($inputData['html_content'])) {
            $file_path = config('constant.CREDIT_REPORT_CONTENT_PATH') . DIRECTORY_SEPARATOR . $inputData['user_id'];
            $creditReport = self::where('user_id',$inputData['user_id'])->first();
            if(empty($creditReport)) {
                $creditReport = self::create([
                    'user_id' => $inputData['user_id'],
                    'file_name' => "",
                ]);
            }else{
                deleteFile($file_path.DIRECTORY_SEPARATOR.$creditReport->file_name);
            }

            if ($creditReport->id > 0) {
                $file_name = $creditReport->id . ".html";
                uploadHTML($file_path, $file_name, $inputData['html_content']);
                self::where('id', $creditReport->id)->update([
                    'file_name' => $file_name
                ]);
            }
        }

        return $creditReport;
    }

    public function insertCreditReport($inputData){
        if(isset($inputData['password']) && !empty($inputData['password'])){
            $inputData['password'] = customEncrypt($inputData['password']);
        }
        return self::create($inputData);
    }

    public function getCreditReportInfoByUserId($user_id){
        return self::where('user_id',$user_id)->first();
    }

    public function getCreditReportInfoByUserIdAndType($user_id,$type){
        return self::where(['user_id'=>$user_id,'report_type'=>$type])->first();
    }

    public function updateCreditReport($inputData){
        $response = [];
        $response['status'] = false;
        if(!empty($inputData)) {
            $file_path = config('constant.CREDIT_REPORT_CONTENT_PATH') . DIRECTORY_SEPARATOR . $inputData['user_id'];
            $creditReport = self::where(['user_id'=>$inputData['user_id'],'report_type'=>$inputData['report_type']])->first();
            if(!empty($creditReport)) {
                $file_name = $creditReport->id . ".html";
                uploadHTML($file_path, $file_name, $inputData['credithtml']);
                self::where('id', $creditReport->id)->update([
                    'file_name' => $file_name
                ]);
                $response['status'] = true;
            }

        }

        return $response;
    }

    public function updateCreditReportByUserId($inputData) : array
    {

        $response = [];

        $creditReport = self::where('user_id',$inputData['user_id'])->first();

        if(!empty($creditReport)) {
            $response['data'] = $creditReport->update($inputData);
       }

        return $response;
    }
}
