<?php

namespace App\Http\Controllers\Admin;

use App\APIWrapper\Wrapper;
use App\ConsumerApplication;
use App\ConsumerApplicationFiles;
use App\Http\Controllers\Controller;
use App\Method\KMGP2P\KMGP2PMethods;
use App\Events\V1\EventKMGP2PDocumentUpload;
use App\Slack;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\KMGP2PBorrowerReg;
use App\KMGP2PDocument;
use Carbon\Carbon;

class KMGP2PController extends Controller{

    private $request;

    public function __construct(Request $request){

        $this->request = $request;
    }

    public function checkWorthiness(){
        $kmLoanId = 0;
        $user_id = Auth::check() ? Auth::user()->id : 107;
        $wrapper = new Wrapper();
        $wrapperMethods = $wrapper->register(KMGP2PMethods::class);
        $wrapper->payload->addPayload(new Request(['id' => $this->request->get('id'), 'user_id' => $user_id]));

        $application = ConsumerApplication::where('id',$this->request->get('id'))->first(['id', 'lender_id']);
        if(isset($application->id)){
            $wrapperRes = $wrapperMethods->borrowerRegistration($wrapper);
            if (isset($wrapperRes->errorBag)) {
                return response()->json(['status' => 'FAIL', 'data' => array_filter($wrapperRes->errorBag)]);
            }

            if (isset($wrapperRes->error)) {
                return response()->json(['status' => 'FAIL', 'message' => isset($wrapperRes->error->description) ? $wrapperRes->error->description : 'Something went wrong while saving loan application details'], 400);
            }

            $kmLoanId = $wrapperRes->data->kmLoanId;
        } else {
            return response()->json(['status' => 'FAIL', 'message' => 'Invalid Loan application']);
        }

        if($kmLoanId > 0){
            \request()->merge(['kmLoanId' => $kmLoanId]);
            $wrapper->payload->addPayload(new Request(['id' => $this->request->get('id'), 'user_id' => $user_id, 'kmLoanId' => $kmLoanId]));
            $wrapperRes = $wrapperMethods->saveEMI($wrapper);
            $wrapperMethods->updateLoan($wrapper);
            if (isset($wrapperRes->errorBag)) {
                return response()->json(['status' => 'FAIL', 'data' => array_filter($wrapperRes->errorBag)]);
            }

            if (isset($wrapperRes->error)) {
                return response()->json(['status' => 'FAIL', 'message' => isset($wrapperRes->error->description) ? $wrapperRes->error->description : 'Something went wrong while saving emi calculation details'], 400);
            }
        }

        $application_files = ConsumerApplicationFiles::select(['consumer_application_id','file_type', 'file_path'])->where('consumer_application_id', $this->request->get('id'))->orderBy('created_at','desc')->get();
        //$doc_array = array('POI'=>['pan_card'],'POA'=>array('votar_id_front','votar_id_back','passport_front','passport_back','aadhar_card','aadhar_card_back','driving_license'),'agreement'=>['loan_agreement_esign'],'proforma'=>['pro_forma_invoice'],'nach'=>['nach'],'bank_proof'=>array('bank_statement_1','bank_statement_2','bank_statement_3','bank_statement_6' ,'security_cheques'));
        $doc_array = array('POI'=>['pan_card'],'POA'=>array('votar_id_front','votar_id_back','passport_front','passport_back','aadhar_card','aadhar_card_back','driving_license'),'agreement'=>['loan_agreement_esign'],'proforma'=>['pro_forma_invoice'],'nach'=>['e mandate','nach']);
        foreach($application_files as $val){
            foreach($doc_array as $key => $values){
                if (in_array($val->file_type, array_values($values))){
                    unset($doc_array[$key]);
                }
            }
        }
        if(!empty($doc_array)){
           return response()->json(['status' => 'FAIL','data' => array_keys($doc_array)]);
        }else{
            event(new EventKMGP2PDocumentUpload(['id'=>$this->request->get('id'), 'uid'=>$user_id]));
            return response()->json(['status' => 'OK', 'message' => 'Loan application details along with documents updated to KMG P2P']);
        }
    }

    public function SendDocumentToKMGP2P(){
        $application_id = $this->request->get('id');
        $uid = $this->request->get('uid');
        //$application_files = ConsumerApplicationFiles::select(['id', 'consumer_application_id','file_type', 'file_path'])->where('consumer_application_id', $application_id)->whereNull('deleted_at')->orderBy('created_at','desc')->get();
        $application_files = ConsumerApplicationFiles::select('consumer_application_files.id', 'consumer_application_files.consumer_application_id', 'consumer_application_files.file_type', 'consumer_application_files.file_path')
            ->from('consumer_application_files')
            ->join(DB::raw('(SELECT file_type, MAX(created_at) AS latest_upload_date
                            FROM consumer_application_files
                            WHERE consumer_application_id = '.$application_id.' AND deleted_at IS NULL
                            GROUP BY file_type) latest_files'), function ($join) {
                $join->on('consumer_application_files.file_type', '=', 'latest_files.file_type')
                    ->on('consumer_application_files.created_at', '=', 'latest_files.latest_upload_date');
            })
            ->where('consumer_application_files.consumer_application_id', $application_id)
            ->get();
        
        if(count($application_files) > 0){
            $errorCount = 0;
            $kmgAppln = KMGP2PBorrowerReg::where('application_id', $application_id)->first(['kmg_loan_id']);
            $kmgLoanId = $kmgAppln->kmg_loan_id;
            $wrapper = new Wrapper();
            $wrapperMethods = $wrapper->register(KMGP2PMethods::class);
            foreach($application_files as $key => $val){
                $key = $val->file_type;
                if ($key == 'pan_card'){
                    $param = "PAN";
                }
                if ($key == 'votar_id_front' || $key == 'votar_id_back' || $key == 'votar_id_front_masked' || $key == 'votar_id_back_masked'){
                    $param = "VOTER_ID";
                }
                if ($key == 'passport_front' || $key == 'passport_back' || $key == 'passport_front_masked' || $key == 'passport_back_masked'){
                    $param = "PASSPORT";
                }
                if ($key == 'aadhar_card' || $key == 'aadhar_card_back' || $key == 'aadhar_card_masked' || $key == 'aadhar_card_back_masked'){
                    $param = "AADHAR";
                }
                if ($key == 'driving_license' || $key == 'driving_license_masked'){
                    $param = "DRIVING_LICENSE";
                }
                if ($key == 'loan_agreement_esign'){
                    $param = "LOAN_AGREEMENT";
                }
                if ($key == 'pro_forma_invoice'){
                    $param = "OTHER";
                }
                if ($key == 'nach' || $key == 'e mandate'){
                    $param = "OTHER";
                }
                if (strpos($key, 'bank_statement') !== false){
                    $param = "BANK_STATEMENT";
                }
                if ($key == 'security_cheques'){
                    $param = "CHEQUE";
                }
                if ($key != ''){
                    $param = strtoupper($key);
                }
                
                request()->merge(['id' => $application_id, 'kmg_loan_id' => $kmgLoanId,'file_path' => $val->file_path, 'param' =>$param, 'file_id'=>$val->id, 'user_id'=>$uid]);
                $wrapper->payload->addPayload(new Request(['id' => $application_id, 'kmg_loan_id' => $kmgLoanId,'file_path' => $val->file_path, 'param' =>$param, 'file_id'=>$val->id, 'user_id'=>$uid]));
                $wrapperRes = $wrapperMethods->uploadDocument($wrapper);
                if (isset($wrapperRes->status) && $wrapperRes->status == 'OK') {
                    $fileArray = explode("/", $val->file_path);
                    $file_name = $fileArray[1];
                    $file_tmp_path = storage_path().'/'.$file_name;
                    unlink($file_tmp_path);
                }
                $errMsg = 'Something went wrong while document upload';
                if(isset($wrapperRes->errorBag['Error'])){
                    $errorCount++;
                    $errMsg = isset($wrapperRes->errorBag['Error']) ? $wrapperRes->errorBag['Error'] : 'Something went wrong while document upload';
                    break;
                }
                if (isset($wrapperRes->error)) {
                    $errorCount++;
                    $errMsg = isset($wrapperRes->error->description) ? $wrapperRes->error->description : 'Something went wrong while document upload';
                    break;
                    return response()->json(['status' => 'FAIL', 'message' => isset($wrapperRes->error->description) ? $wrapperRes->error->description : 'Something went wrong while document upload'], 400);
                }
            }
            if($errorCount > 0){
                return response()->json(['status' => 'FAIL', 'message' => $errMsg], 400);
            } else{
                return response()->json(['status' => 'OK', 'message' => 'Loan documents uploaded successfully to KMG P2P']);
            }
        }else{
            return response()->json(['status' => 'FAIL', 'message' => 'Files are missing']);
        }
    }

    public function SingleSendDocumentToKMGP2P(){
        $application_id = $this->request->get('id');
        $file_id = $this->request->get('file_id');
        $uid = Auth::check() ? Auth::user()->id : 107;
        $application_files = ConsumerApplicationFiles::where('id', $file_id)->first(['file_type', 'file_path']);
        $kmgAppln = KMGP2PBorrowerReg::where('application_id', $application_id)->first(['kmg_loan_id']);
        $kmgLoanId = $kmgAppln['kmg_loan_id'];
        $wrapper = new Wrapper();
        $wrapperMethods = $wrapper->register(KMGP2PMethods::class);
        $key = $application_files->file_type;
        if ($key == 'pan_card'){
            $param = "PAN";
        }
        if ($key == 'votar_id_front' || $key == 'votar_id_back' || $key == 'votar_id_front_masked' || $key == 'votar_id_back_masked'){
            $param = "VOTER_ID";
        }
        if ($key == 'passport_front' || $key == 'passport_back' || $key == 'passport_front_masked' || $key == 'passport_back_masked'){
            $param = "PASSPORT";
        }
        if ($key == 'aadhar_card' || $key == 'aadhar_card_back' || $key == 'aadhar_card_masked' || $key == 'aadhar_card_back_masked'){
            $param = "AADHAR";
        }
        if ($key == 'driving_license' || 'driving_license_masked'){
            $param = "DRIVING_LICENSE";
        }
        if ($key == 'loan_agreement_esign'){
            $param = "LOAN_AGREEMENT";
        }
        if ($key == 'pro_forma_invoice'){
            $param = "OTHER";
        }
        if ($key == 'nach' || $key == 'e mandate'){
            $param = "OTHER";
        }
        if (strpos($key, 'bank_statement') !== false){
            $param = "BANK_STATEMENT";
        }
        if ($key == 'security_cheques'){
            $param = "CHEQUE";
        }
        if ($key != ''){
            $param = strtoupper($key);
        }
        request()->merge(['id' => $application_id, 'kmg_loan_id' => $kmgLoanId, 'file_path' => $application_files->file_path, 'param' =>$param, 'file_id'=>$file_id, 'user_id'=>$uid]);
        $wrapper->payload->addPayload(new Request(['id' => $application_id,'kmg_loan_id' => $kmgLoanId,'file_path' => $application_files->file_path, 'param' =>$param, 'file_id'=>$file_id, 'user_id'=>$uid]));
        $wrapperRes = $wrapperMethods->uploadDocument($wrapper);
        if (isset($wrapperRes->status) && $wrapperRes->status == 'OK') {
            $fileArray = explode("/", $application_files->file_path);
            $file_name = end($fileArray);
            $file_tmp_path = storage_path().'/'.$file_name;
            return response()->json(['status' => 'OK', 'message' => 'Loan document uploaded successfully to KMG P2P']);
        }

        if (isset($wrapperRes->error)) {
            return response()->json(['status' => 'FAIL', 'message' => isset($wrapperRes->error->description) ? $wrapperRes->error->description : 'Something went wrong while document upload'], 400);
        }

        return response()->json(['status' => 'FAIL', 'message' => isset($wrapperRes->errorBag['Error']) ? $wrapperRes->errorBag['Error'] : 'Something went wrong while document upload'], 400);
    }

    public function getDocumentMapping(){
        $mappedDocumentExists = [];
        if(!$this->request->has('file_type')) {
            $files = ConsumerApplicationFiles::where('consumer_application_id', $this->request->get('id'))->orderBy('created_at', 'DESC')->get(['id', 'file_type']);
            foreach ($files as $file) {
                $filesExistIds[$file->file_type][] = $file->id;
                $mappedDocumentExists[$file->file_type] = $file->file_type;
            }
        }else{
            $filesExistIds[$this->request->get('file_type')][] = $this->request->get('file_id');
            $mappedDocumentExists[$this->request->get('file_type')] = $this->request->get('file_id');
        }

        $mappedDocumentAvExists = [];
        if (isset($filesExistIds) && $filesExistIds) {
            foreach ($filesExistIds as $mainKey => $filesExistId) {
                $avansePushed = KMGP2PDocument::where('application_id', $this->request->get('id'))->whereIn('file_id', $filesExistId)->first();
                if (isset($avansePushed->id)) {
                    $mappedDocumentAvExists[$mainKey] = $mainKey;
                }
            }
        }

        return [$mappedDocumentExists, $mappedDocumentAvExists];
    }

    public function pushRepayments(){
        $wrapper = new Wrapper();
        $wrapperMethods = $wrapper->register(KMGP2PMethods::class);
        $wrapper->payload->addPayload($this->request);
        $wrapperRes = $wrapperMethods->savePaymentTransactions($wrapper);
        if (isset($wrapperRes->errorBag)) {
            return response()->json(['status' => 'FAIL', 'data' => array_filter($wrapperRes->errorBag)]);
        }
        return response()->json(['status' => 'OK', 'data' => $wrapperRes]);
    }
}

