<?php

namespace App;

use App\PirimidBankAnalysis;
use Illuminate\Http\Request;
use App\Logging\CloudWatchLoggerFactory;
use Illuminate\Http\Response;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Grade\GradeController;
use App\ConsumerApplication;

class Pirimid {

    public $response;
    public $curlData;

    public function __construct(Request $request){
        $this->request = $request;
        $this->baseURL = env('PIRIMID_URL').'/fiu/api/'.env('PIRIMID_TENANT_ID');
        $this->API_KEY = env('PIRIMID_API_KEY');
        $this->cloudwatchLogger = new CloudWatchLoggerFactory();
    }

    public function uploadBankStatement($requestFile=true) {
        try {
            $this->curlData = $this->postData($requestFile);
            $curl = curl_init();
            $url = $this->baseURL.'/bank-statement/process-work-order';
            if(isset($this->curlData["file"]->mime) && $this->curlData["file"]->mime == 'application/zip'){
                $url = $url.'/zip';
            }
            $headers = [
                "Content-Type: multipart/form-data",
                "Accept: */*",
                "Cookie: AWSALB=i8DzM0l2n6ER4HTDMlKsIqRs/24Dy2+8U3mIe9suO62jx0zuNsHe6AUVFKUXRCmx6sJk9IV23MHoj1kKEol+6X7SXwVrMkwVwLcg++TJghYJ62e7OtOBeQu2PJ6B; AWSALBCORS=i8DzM0l2n6ER4HTDMlKsIqRs/24Dy2+8U3mIe9suO62jx0zuNsHe6AUVFKUXRCmx6sJk9IV23MHoj1kKEol+6X7SXwVrMkwVwLcg++TJghYJ62e7OtOBeQu2PJ6B; JSESSIONID=B93B53DA9070D9A9BA35408B8341BEF1",
                "API_KEY: ".$this->API_KEY
            ];
            curl_setopt_array($curl, [
                CURLOPT_URL => $url,
                CURLOPT_POST => 1,
                CURLOPT_RETURNTRANSFER => 1,
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_FRESH_CONNECT => 1,
                CURLOPT_FORBID_REUSE => 1,
                CURLOPT_TIMEOUT => 100,
                CURLOPT_POSTFIELDS => $this->curlData,
            ]);
            $this->response = curl_exec ($curl);
            curl_close ($curl);
            // $this->response = '{"trackingId":"01957ec1-3799-6626-629c-5a05b1cd495a","status":"PENDING","timestamp":"2025-03-10T06:32:26.794Z","message":"Request Initiated"}';
            $this->saveToDB();
            return json_decode($this->response);
        } catch (\Exception $e) {
            $this->cloudwatchLogger->logger(json_encode(['title' => 'Pirimid Upload Statement', 'message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
        }
    }

    public function fetchAnalytics($trackingId, $type) {
        $curl = curl_init();
        $headers = [
            "Accept: application/octet-stream",
            "Cookie: AWSALB=i8DzM0l2n6ER4HTDMlKsIqRs/24Dy2+8U3mIe9suO62jx0zuNsHe6AUVFKUXRCmx6sJk9IV23MHoj1kKEol+6X7SXwVrMkwVwLcg++TJghYJ62e7OtOBeQu2PJ6B; AWSALBCORS=i8DzM0l2n6ER4HTDMlKsIqRs/24Dy2+8U3mIe9suO62jx0zuNsHe6AUVFKUXRCmx6sJk9IV23MHoj1kKEol+6X7SXwVrMkwVwLcg++TJghYJ62e7OtOBeQu2PJ6B; JSESSIONID=B93B53DA9070D9A9BA35408B8341BEF1",
            "API_KEY: ".$this->API_KEY
        ];
        curl_setopt_array($curl, [
            CURLOPT_URL => $this->baseURL."/analytics/".$type.'/download?trackingId='.$trackingId,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_FRESH_CONNECT => 1,
            CURLOPT_FORBID_REUSE => 1,
            CURLOPT_TIMEOUT => 100
        ]);
        $response = curl_exec ($curl);
        curl_close ($curl);
        return $response;
    }

    public function postData($requestFile) {
        $data = $this->request->all();
        if ($requestFile) {
            $cfile = curl_file_create(
                $data['uploaded_file']->getPathname(),
                $data['uploaded_file']->getMimeType(),
                $data['uploaded_file']->getClientOriginalName()
            );
        } else {
            $cfile = curl_file_create(
                $data['uploaded_file']->getPathname(),
                $data['uploaded_file']->getMimeType(),
                $data['uploaded_file']->getFileName()
            );
        }
        $returnData = ['file' => $cfile];
        if (isset($data['employementType']) && $data['employmentType'] == 'SALARIED') {
            $returnData = array_merge($returnData, ['employmentType' => 'SELF_EMPLOYED']);
        }
        if (isset($data['password']) && $data['password'] != '') {
            if($cfile->mime == 'application/zip'){
                $returnData = array_merge($returnData, ['pdfPasswords' => $data['password']]);
            }else{
                $returnData = array_merge($returnData, ['pdfPasswords' => $data['password']]);
            }
        }
        return $returnData;
    }

    public function processWebhook() {
        try {
            $data = $this->request->all();
            $trackingId = $data['trackingId'];
            $pirimidAnalysis = DB::select("select application_id, applicant_type from pirimid_bank_analysis pba where json_extract(pba.response, '$.trackingId') = '".$trackingId."' order by created_at desc limit 1");
            $id = $pirimidAnalysis[0]->application_id;
            $applicant_type = $pirimidAnalysis[0]->applicant_type;
            if (isset($data['message']) && $data['message']['reportStatus'] == "COMPLETED") {
                $s3 = Storage::disk('s3');
                // Excel file save
                $excelStream = $this->fetchAnalytics($trackingId, 'excel');
                $excelfileName = 'consumer/'.$id.'/pirimid_analysis_excel_'.$trackingId.'.xls';
                $s3->put($excelfileName, $excelStream);
                $this->saveToFile('pirimid_analysis_excel', $excelfileName, $id, $applicant_type, $trackingId);
                // JSON file save
                $jsonData = $this->fetchAnalytics($trackingId, 'json');
                $jsonfileName = 'consumer/'.$id.'/pirimid_analysis_json'.$trackingId.'.json';
                $s3->put($jsonfileName, $jsonData, $id);
                // $this->saveToFile('pirimid_analysis_json', $jsonfileName, $id);
                $pba = PirimidBankAnalysis::where('application_id', $id)->first(['analytics_fetch']);
                if ($pba && $pba->analytics_fetch != 1) {
                    $pba->analytics_fetch = 1;
                    $pba->save();
                    $status = DB::select("select status from status_logs where application_id = ".$id." and status = 'approved'");
                    if ($pirimidAnalysis[0]->applicant_type != 2 && !isset($status[0])) {
                        $grade = new GradeController(new Request);
                        $result = $grade->autoReject(false, $id, 'banking');
                        if ($result) {
                            $consumer_application = ConsumerApplication::find($id);
                            $consumer_application->state = "rejected";
                            $consumer_application->save();
                            $appStatus = 'rejected';
                            StatusLogs::insert([
                                'application_id' => $id,
                                'user_id' => 107,
                                'status' => $appStatus,
                                'created_at' => Carbon::now()->toDateTimeString()
                            ]);
                        }
                        $this->cloudwatchLogger->logger(json_encode(['title' => 'Auto Reject Banking','application_id' => $id, 'auto_reject_result' => $result]));
                    }
                }
            }
            return true;
        } catch (\Exception $e) {
            $this->cloudwatchLogger->logger(json_encode(['tracking_id' => $trackingId, 'message' => $e->getMessage(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()]));
            ConsumerApplicationFiles::where('id',$id)->update(['finbit_analysis_date' => Carbon::now()->toDateTimeString()]);
            return false;
        }
    }

    public function saveToDB() {
        $pirimidBankAnalysis = new PirimidBankAnalysis();
        $pirimidBankAnalysis->application_id = $this->request->get('id');
        $pirimidBankAnalysis->request = json_encode($this->curlData);
        $pirimidBankAnalysis->response = json_encode(json_decode($this->response), true);
        $pirimidBankAnalysis->user_id = Auth::user()->id;
        $pirimidBankAnalysis->created_at = Carbon::now()->toDateTimeString();
        $pirimidBankAnalysis->applicant_type = $this->request->get('applicant_type');
        $pirimidBankAnalysis->save();
    }

    private function saveToFile($fileName, $path, $id, $applicant_type, $trackingId): void{
        $consumer_application_file = new ConsumerApplicationFiles();
        $consumer_application_file->consumer_application_id = $id;
        $consumer_application_file->file_type = $fileName;
        $consumer_application_file->bank_name = '';
        $consumer_application_file->password = '';
        $consumer_application_file->accounttype = '';
        $consumer_application_file->statementtype = '';
        $consumer_application_file->statemenfilettype = '';
        $consumer_application_file->customer_id = '';
        $consumer_application_file->provider = '';
        $consumer_application_file->finbit_analysis_date = '';
        $consumer_application_file->bp_number = '';
        $consumer_application_file->accountUID = '';
        $consumer_application_file->file_path = $path;
        $consumer_application_file->doc_ref_id = $trackingId;
        $consumer_application_file->created_by = Auth::user()->id ?? 107;
        $consumer_application_file->image_score = '';
        $consumer_application_file->m_generated = 0;
        $consumer_application_file->applicant_type = $applicant_type;
        $consumer_application_file->bureau_report_type = '';
        $consumer_application_file->bureau_report_score = '';
        $consumer_application_file->is_masked = 0;
        $consumer_application_file->save();
    }

}