<?php

namespace App\Http\Controllers\Api;



use App\Http\Controllers\Controller;
use App\Http\Controllers\Util\UtilMethods;
use App\Models\KycThirdParty;
use App\Models\UserAdmin;
use App\Models\User;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class KycThirdpartyController extends Controller
{
    //

    private $successStatusCode = 200;
    private $createStatusCode = 201;
    private $errorStatusCode = 422;

    public function __construct() {
        $this->middleware('auth:api');
    }

    public function registerExpressionInterest(Request $request) {

        $user = Auth::user();
        if($user->user_type == 'third_party') {

            $validator = Validator::make($request->all(), [
                'companyname' => 'required|string',
                'nearestbustop' => 'required|string',
                'lga' => 'required|string',
                'employeecount' => 'required|integer',
                'officeaddress' => 'required|string',
                'companyprofile' => 'nullable|string',
                'companytype' => 'required|string|in:existing company,new company',
                'technicalcompetence' => 'nullable|string',
                'technicalpartner' => 'nullable|string',
                'cacfile' => 'nullable|string',
                'apconfile' => 'nullable|string',
                'outdoorfile' => 'nullable|string',
                'auditfile' => 'nullable|string',
                'listpastproject' => 'nullable|string',
                'taxcertificate' => 'nullable|string',
                'evidenceoffinance' => 'nullable|string',
                'businessplan' => 'nullable|string',
                'director_bank_statement' => 'nullable|string',
                'preliminarydesign' => 'nullable|string',
                'bankreference' => 'nullable|string',
                'technicalreference' => 'nullable|string'
            ]);

            if ($validator->fails()) {
                return response()->json(['errors' => $validator->errors()->all()], $this->errorStatusCode);
            }

            $expressionInput = $request->all();

            $userId = $user->id;
            $userObj = User::find($userId);
            $kycExist = KycThirdParty::where('user_id', $userId)->exists();
            
            $rmRole = [2,3];
                $getAssignedOfficer  = UserAdmin::where('department', 'Registry')->whereIn('admin_role_id', $rmRole)->pluck('id')->toArray();
                // var_dump($getAssignedOfficer); die();

                foreach ($getAssignedOfficer as $officer) {
                    $counter = KycThirdParty::where('assigned_officer', (string) $officer)->count();
                    $officerCounter[$officer] = $counter;
                }

                $leastOfficer = array_search(min($officerCounter), $officerCounter);
                $getLeastOfficer = UserAdmin::where('id', (string) $leastOfficer)->first();

            if(!$kycExist) {

                $kycThirdParty = new KycThirdParty();
                $kycThirdParty->company_name = $expressionInput['companyname'];
                $kycThirdParty->nearest_bustop = $expressionInput['nearestbustop'];
                $kycThirdParty->lga = $expressionInput['lga'];
                $kycThirdParty->employee_count = $expressionInput['employeecount'];
                $kycThirdParty->office_address = $expressionInput['officeaddress'];
                //$getCompanyType = strtolower($expressionInput['companytype']);
                $kycThirdParty->company_type = $expressionInput['companytype'];
                $kycThirdParty->assigned_officer = (string)$getLeastOfficer->id;
                $kycThirdParty->company_profile = UtilMethods::convertBase64toPdf($expressionInput['companyprofile']);
                if ($expressionInput['technicalcompetence'] != null) {
                    $kycThirdParty->technical_competence = UtilMethods::convertBase64toPdf($expressionInput['technicalcompetence']);
                }
                if ($expressionInput['technicalpartner'] != null) {
                    $kycThirdParty->technical_partner = UtilMethods::convertBase64toPdf($expressionInput['technicalpartner']);
                }
                if ($expressionInput['cacfile'] != null) {
                    $kycThirdParty->cac_document = UtilMethods::convertBase64toPdf($expressionInput['cacfile']);
                }
                if ($expressionInput['apconfile'] != null) {
                    $kycThirdParty->apcon_document = UtilMethods::convertBase64toPdf($expressionInput['apconfile']);
                }
                if ($expressionInput['outdoorfile'] != null) {
                    $kycThirdParty->outdoor_association = UtilMethods::convertBase64toPdf($expressionInput['outdoorfile']);
                }
                if ($expressionInput['auditfile'] != null) {
                    $kycThirdParty->audit_report = UtilMethods::convertBase64toPdf($expressionInput['auditfile']);
                }
                if ($expressionInput['listpastproject'] != null) {
                    $kycThirdParty->list_past_project = UtilMethods::convertBase64toPdf($expressionInput['listpastproject']);
                }
                if ($expressionInput['taxcertificate'] != null) {
                    $kycThirdParty->tax_clearance = UtilMethods::convertBase64toPdf($expressionInput['taxcertificate']);
                }
                if ($expressionInput['evidenceoffinance'] != null) {
                    $kycThirdParty->evidence_finance = UtilMethods::convertBase64toPdf($expressionInput['evidenceoffinance']);
                }
                if ($expressionInput['businessplan'] != null) {
                    $kycThirdParty->business_plan = UtilMethods::convertBase64toPdf($expressionInput['businessplan']);
                }
                if ($expressionInput['director_bank_statement'] != null) {
                    $kycThirdParty->director_bank_statement = UtilMethods::convertBase64toPdf($expressionInput['director_bank_statement']);
                }
                if ($expressionInput['preliminarydesign'] != null) {
                    $kycThirdParty->preliminary_technical_design = UtilMethods::convertBase64toPdf($expressionInput['preliminarydesign']);
                }
                if ($expressionInput['bankreference'] != null) {
                    $kycThirdParty->bank_or_corporate_reference = UtilMethods::convertBase64toPdf($expressionInput['bankreference']);
                }
                if ($expressionInput['technicalreference'] != null) {
                    $kycThirdParty->technical_reference = UtilMethods::convertBase64toPdf($expressionInput['technicalreference']);
                }
                $response = $userObj->kycThirdParty()->save($kycThirdParty);
            } else {
                return response()->json(['success' => false, 'data' => 'can not register kyc twice'], $this->errorStatusCode);
            }
            return response()->json(['success' => true, 'data' => $response], $this->createStatusCode);
        } else {
            return response()->json(['success' => false, 'data' => 'Can not view this resource'], $this->errorStatusCode);
        }
    }

    public function getThirdPartyExpression($kycThirdPartyId) {

        //$getKycDetails = KycThirdParty::where('id', $kycThirdPartyId)->with(['kycThirdPartyScore'])->get();
        $getKycDetails = KycThirdParty::where('id', $kycThirdPartyId)->get();

        if(count($getKycDetails) == 0 ) {
            return response()->json(['success' => false, 'data' => 'There is no kyc details with the kyc id'], $this->errorStatusCode);
        } else {
            return response()->json(['success' => true, 'data' => $getKycDetails], $this->successStatusCode);
        }
    }

    public function editKycApplication(Request $request, $kycThirdPartyId, $status) {

        $user = Auth::user();
        if($user->user_type == 'third_party') {
            $getKeyObj = KycThirdParty::find($kycThirdPartyId);
            $userId = $user->id;
            if ($getKeyObj->user_id == (string)$userId) {
                if ($getKeyObj->operation_status == 'pending' || $getKeyObj->operation_status == 'disapproved' ||
                    $getKeyObj->legal_status == 'disapproved' || $getKeyObj->account_status == 'disapproved'
                    || $getKeyObj->registry_status == 'disapproved') {

                    $validator = Validator::make($request->all(), [
                        'companyname' => 'nullable|string',
                        'nearestbustop' => 'nullable|string',
                        'lga' => 'nullable|string',
                        'employeecount' => 'nullable|integer',
                        'officeaddress' => 'nullable|string',
                        'companyprofile' => 'nullable|string',
                        'companytype' => 'nullable|string|in:existing company,new company',
                        'technicalcompetence' => 'nullable|string',
                        'technicalpartner' => 'nullable|string',
                        'cacfile' => 'nullable|string',
                        'apconfile' => 'nullable|string',
                        'outdoorfile' => 'nullable|string',
                        'auditfile' => 'nullable|string',
                        'listpastproject' => 'nullable|string',
                        'taxcertificate' => 'nullable|string',
                        'evidenceoffinance' => 'nullable|string',
                        'businessplan' => 'nullable|string',
                        'director_bank_statement' => 'nullable|string',
                        'preliminarydesign' => 'nullable|string',
                        'bankreference' => 'nullable|string',
                        'technicalreference' => 'nullable|string'
                    ]);

                    if ($validator->fails()) {
                        return response()->json(['errors' => $validator->errors()->all()], $this->errorStatusCode);
                    }
                    $expressionInput = $request->all();
                    //$companyType = strtolower($expressionInput['companytype']);
                    $updateData = [];

                    if(!empty($expressionInput['companyname'])) {
                        $updateData['company_name'] = $expressionInput['companyname'];
                    }
                    if (!empty($expressionInput['nearestbustop'])) {
                        $updateData['nearest_bustop'] = $expressionInput['nearestbustop'];
                    }
                    if(!empty($expressionInput['lga'])) {
                        $updateData['lga'] = $expressionInput['lga'];
                    }
                    if (!empty($expressionInput['employeecount'])) {
                        $updateData['employee_count'] = $expressionInput['employeecount'];
                    }
                    if(!empty($expressionInput['officeaddress'])) {
                        $updateData['office_address'] = $expressionInput['officeaddress'];
                    }
                    if (!empty($expressionInput['companyprofile'])) {
                        $updateData['company_profile'] = UtilMethods::convertBase64toPdf($expressionInput['companyprofile']);
                    }
                    if (!empty($expressionInput['companytype'])) {
                        $updateData['company_type'] = $expressionInput['companytype'];
                    }
                    if(!empty($expressionInput['technicalcompetence'])) {
                        $updateData['technical_competence'] = UtilMethods::convertBase64toPdf($expressionInput['technicalcompetence']);
                    }
                    if(!empty($expressionInput['technicalpartner'])) {
                        $updateData['technical_partner'] = UtilMethods::convertBase64toPdf($expressionInput['technicalpartner']);
                    }
                    if(!empty($expressionInput['cacfile'])) {
                        $updateData['cac_document'] = UtilMethods::convertBase64toPdf($expressionInput['cacfile']);
                    }
                    if(!empty($expressionInput['apconfile'])) {
                        $updateData['apcon_document'] = UtilMethods::convertBase64toPdf($expressionInput['apconfile']);
                    }
                    if(!empty($expressionInput['outdoorfile'])) {
                        $updateData['outdoor_association'] = UtilMethods::convertBase64toPdf($expressionInput['outdoorfile']);
                    }
                    if(!empty($expressionInput['auditfile'])) {
                        $updateData['audit_report'] = UtilMethods::convertBase64toPdf($expressionInput['auditfile']);
                    }
                    if(!empty($expressionInput['listpastproject'])) {
                        $updateData['list_past_project'] = UtilMethods::convertBase64toPdf($expressionInput['listpastproject']);
                    }
                    if(!empty($expressionInput['taxcertificate'])) {
                        $updateData['tax_clearance'] = UtilMethods::convertBase64toPdf($expressionInput['taxcertificate']);
                    }
                    if(!empty($expressionInput['evidenceoffinance'])) {
                        $updateData['evidence_finance'] = UtilMethods::convertBase64toPdf($expressionInput['evidenceoffinance']);
                    }
                    if(!empty($expressionInput['businessplan'])) {
                        $updateData['business_plan'] = UtilMethods::convertBase64toPdf($expressionInput['businessplan']);
                    }
                    if(!empty($expressionInput['director_bank_statement'])) {
                        $updateData['director_bank_statement'] = UtilMethods::convertBase64toPdf($expressionInput['director_bank_statement']);
                    }
                    if (!empty($expressionInput['preliminarydesign'])) {
                        $updateData['preliminary_technical_design'] = UtilMethods::convertBase64toPdf($expressionInput['preliminarydesign']);
                    }
                    if(!empty($expressionInput['bankreference'])) {
                        $updateData['bank_or_corporate_reference'] = UtilMethods::convertBase64toPdf($expressionInput['bankreference']);
                    }
                    if(!empty($expressionInput['technicalreference'])) {
                        $updateData['technical_reference'] = UtilMethods::convertBase64toPdf($expressionInput['technicalreference']);
                    }
                    if (!empty($updateData)) {
                        KycThirdParty::where('id', $getKeyObj->id)->update($updateData);
                        if($status == 'all') {
                            KycThirdParty::where('id', $getKeyObj->id)->update(['operation_status' => 'pending', 'legal_status' => 'pending',
                                'account_status' => 'pending', 'registry_status' => 'pending' ]);
                        } else if ($status == 'account') {
                            KycThirdParty::where('id', $getKeyObj->id)->update(['account_status' => 'pending']);
                        } else if ($status == 'legal') {
                            KycThirdParty::where('id', $getKeyObj->id)->update(['legal_status' => 'pending']);
                        } else if ($status == 'registry') {
                            KycThirdParty::where('id', $getKeyObj->id)->update(['registry_status' => 'pending']);
                        }
                    }
                    $getResponse = KycThirdParty::where('id', $getKeyObj->id)->get();
                    return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
                } else {
                    return response()->json(['success' => false, 'data' => 'Unable to edit this application'], $this->errorStatusCode);
                }
            }  else {
                return response()->json(['success' => false, 'data' => 'Can not edit someone application'], $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'Wrong user type error'], $this->errorStatusCode);
        }
    }

    public function getMyThirdPartyCertificate($kycThirdPartyId) {

        $getKycObj = KycThirdParty::find($kycThirdPartyId);
        $user = Auth::user();

        if($getKycObj->user_id  ==  (string)$user->id && $user->user_type == 'third_party') {
            if ($getKycObj->md_status == 'approved') {
                $lastDayOfYear = Carbon::parse($getKycObj->updated_at)->endOfYear()->format('d-m-Y');
                $data = [
                    'date' => Carbon::parse($getKycObj->updated_at)->format('d-m-Y'),
                    'refno' => $getKycObj->ref_no,
                    'companyName' => $getKycObj->company_name,
                    'endDate' => $lastDayOfYear
                ];
                $pdf = Pdf::loadView('certificate', compact('data'));
                return $pdf->download('certificate.pdf');
            } else {
                return response()->json(['success' => false, 'data' => 'you can not generate certificate yet.'], $this->errorStatusCode);
            }
        } else {
            return  response()->json(['success' => false, 'data' => 'you are unable to view resource'], $this->errorStatusCode);
        }
    }

}

