<?php

namespace App\Http\Controllers;

use App\BankStatement;
use App\BusinessRegistrationDocuments;
use App\BusinessType;
use App\CashCollateral;
use App\CreditFacilityDetails;
use App\CreditFacilityOtherDetails;
use App\FacilityRequest;
use App\HistoricalFinancial;
use App\IdCardFile;
use App\Application_criteria_log;
use App\KeyManagementPersonnel;
use App\Mail\ApplicationCompletedMail;
use App\Mail\FYEIApplicationAssignment;
use App\Mail\FYEIApplicationAssignments;
use App\Mail\RejectedApplicationMail;
use App\MajorProductLine;
use App\AdminModel;
use App\ManagementAccountFile;
use App\NewFinancialPerformance;
use App\NonCashCollateral;
use App\OwnershipApplicant;
use App\Permits;
use App\RejectedAppMove;
use App\UserDetails;
use App\Users;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Log;
use App\Notifications\SendEmailNotification;

class CompanyDetailsController extends Controller
{

    public function submitform(Request $request)
    {
        $data = $request->all();

        $user = UserDetails::query()->where('id', Session::get('userid'))->first();


        if ($user == null || Session::get('userid') == null) {
            Session::flash('error', 'Your session has expired. Kindly log in again!');
            return $this->successJsonMsg('redirect', route('apply'));
            // return redirect()->route('apply')->with('error','Session Has Expired. Please Login/Restore Progress');
        }


        $data['user_id'] = $user->id ?? Session::get('userid');


        Log::info('user with id:' . $data['user_id'] . ' - ' . $user->name . ' submitted the follwing: ' . json_encode($request->all()));


        $save_type = $data['saveType'];

        if ($save_type === 'saveforlater') {

            $data['application_stage'] = 'Stage 1';

            $data['is_stage_complete'] = false;

            $data['is_application_complete'] = false;

            $data['application_status'] = 'Save For Later';

            $this->logActivity('Applicant', 'Client', 'Saved Application For Later', $user->name . ' saved application for later', $user->id);

            $this->runQueryFunctions($data);

            session()->flush();

            Session::flash('success', 'Your session has been saved for later. Kindly log in again to continue your application');
            // return 'yes';
            return $this->successJsonMsg('redirect', route('apply'));
        }

        $validate = Validator::make($data, $this->runValidations(), $this->runValidationMsg());

        if ($validate->fails()) {
            return $this->failJsonMsg($validate->errors()->first());
        }

        $credit_facility_details =  json_decode($data['credit_facility_details'], false);
        if ($data['credit_facilities'] == 'Yes' && empty($credit_facility_details)) {
            return $this->failJsonMsg('Please provide details of your outstanding credit facilities');
        }

        $credit_facility_others_details =  json_decode($data['credit_facility_others_details'], false);
        if ($data['credit_facilities_others'] == 'Yes' && empty($credit_facility_others_details)) {
            return $this->failJsonMsg('Please provide details of your outstanding credit facilities with other banks');
        }

        // $is_age_qualified = $this->calculateDOB($user,$data['application_funds']);
        $is_qualified_sector = $this->checkBusinessSector($data['business_type']);

        $is_registered = $this->checkBusinessRegistration($data['business_structure']);

        $is_year_qualified = Carbon::parse($data['business_established_date'])->age >= 1;

        $is_audited_financials = $data['audited_financials'] === 'Yes';

        $is_credit_facilities = $data['required_licenses'] === 'Yes';

        $has_bank_account = $data['has_bank_account'] === 'Yes';

        Application_criteria_log::updateOrCreate(['user_id' => $user->id], [
            'name' => $user->name,
            // 'age_qualified'=>$is_age_qualified == true ? "Qualified" : "Does Not Qualify",
            'check_bus_sec' => $is_qualified_sector == true ? "Qualified" : "Does Not Qualify",
            'check_bus_reg' => $is_registered == true ? "Qualified" : "Does Not Qualify",
            'business_established_date' => $is_year_qualified,
            'audited_financials' => $data['audited_financials'] === 'Yes' ? "Yes" : 'No: does not qualify',
            'required_licenses' => $data['required_licenses'] === 'Yes' ? "Yes" : 'No: does not qualify',
            'has_bank_account' => $data['has_bank_account'] === 'Yes' ? "Yes" : 'No: does not qualify',
        ]);

        if ($is_qualified_sector && $is_registered && $is_year_qualified && $is_audited_financials && $is_credit_facilities && $has_bank_account) {


            $checksectiontwo = DB::table('new_financial_performances')->where('user_id', $user->id)->first();

            if ($checksectiontwo == null) {
                $data['application_stage'] = 'Stage 2';

                $data['is_stage_complete'] = true;

                $data['is_application_complete'] = false;

                $data['is_disqualified'] = false;

                $this->runQueryFunctions($data);

                Session::flash('success', 'Your Section 1 Application has been submitted and approved. Please enter your financial details and upload relevant documents to proceed to the next stage of the application');

                return $this->successJsonMsg('redirect', route('section2.view'));
            } else {
                // Log::info('i am here and failing');

                $data['application_stage'] = 'Stage 2';

                $data['is_stage_complete'] = true;

                $data['is_application_complete'] = false;

                $data['is_disqualified'] = false;
                $this->runQueryFunctions($data);
                $this->logActivity('Applicant', 'Client', 'Qualified to Phase 2', $user->name . ' Qualified to Phase 2 of Application', $user->id);

                Session::flash('success', 'Your Section 1 Application has been submitted and approved. Please enter your financial details and upload relevant documents to proceed to the next stage of the application');

                Session::flash('success', 'Your Section 1 Application has been submitted and approved. Please enter your financial details and upload relevant documents to proceed to the next stage of the application');
                // Log::info('failing to run return after this line ');
                return $this->successJsonMsg('redirect', route('section2.view.filled'));
            }
        }


        $data['is_disqualified'] = true;

        $data['application_stage'] = 'Stage 1';

        $this->runQueryFunctions($data);

        $this->logActivity('Applicant', 'Client', 'Application Disqualified at Stage 1', $user->name . ' has been Disqualified', $user->id);

        Mail::to($user->email)->send(new RejectedApplicationMail($user));
        // move applicatant to rejectedtablemove
        $uu = Users::where('user_id', $user->id)->first();
        $moveapp = RejectedAppMove::create([
            'userid' => $user->id,
            'name' => $user->name,
            'position' => $user->position,
            'email' => $user->email,
            'phone' => $user->phone,
            'company_name' => $user->company_name,
            'application_status' => $user->application_status,
            'dob' => $user->dob,
            'gender' => $user->gender,
            'physical_address' => $uu->physical_address ?? null,
            'application_funds' => $uu->application_funds,
            'emails' => $uu->email,
            'postal_address' => $uu->postal_address,
            'digital_address' => $uu->digital_address,
            'applicant_name' => $uu->applicant_name,
            'applicant_address' => $uu->applicant_address,
            'business_phone' => $uu->business_phone,
            'primary_contact' => $uu->primary_contact,
            'primary_contact_phone' => $uu->primary_contact_phone,
            'current_bankers' => $uu->current_bankers,
            'branch' => $uu->branch,
            'business_structure' => $uu->business_structure,
            'business_structure_state' => $uu->business_structure_state,
            'business_established_date' => $uu->business_established_date,
            'tin' => $uu->tin,
            'nature_of_business' => $uu->nature_of_business,
            'business_type' => $uu->business_type,
            'business_premises' => $uu->business_premises,
            'business_premise' => $uu->business_premise,
            'outstanding_years' => $uu->outstanding_years,
            'business_commencement_date' => $uu->business_commencement_date,
            'incorporation_date' => $uu->incorporation_date,
            'full_time_employees' => $uu->full_time_employees,
            'part_time_employees' => $uu->part_time_employees,
            'audited_financials' => $uu->audited_financials,
            'has_bank_account' => $uu->has_bank_account,
            'required_licenses' => $uu->required_licenses,
            'expected_jobs' => $uu->expected_jobs,
            'expected_full_time_employees' => $uu->expected_full_time_employees,
            'expected_part_time_employees' => $uu->expected_part_time_employees,
            'proposed_facility_tenure' => $uu->proposed_facility_tenure,
            'credit_facilities' => $uu->credit_facilities,
            'credit_facilities_others' => $uu->credit_facilities_others,
            'application_stage' => $uu->application_stage,
            'is_stage_complete' => $uu->is_stage_complete,
            'is_application_complete' => $uu->is_application_complete,
            'is_disqualified' => $uu->is_disqualified,
            'credit_facilities_other_banks_others' => $uu->credit_facilities_other_banks_others,
            'credit_facilities_others_fidelity' => $uu->credit_facilities_others_fidelity,
            'comment' => $uu->comment,
            'application_statuss' => $uu->application_status,
            'project_stat' => $uu->project_stat,
            'credit_stat' => $uu->credit_stat,
            'projectanalyst_id' => $uu->projectanalyst_id,
            'creditanalyst_id' => $uu->creditanalyst_id,
            'full_time_male' => $uu->full_time_male,
            'full_time_female' => $uu->full_time_female,
            'part_time_male' => $uu->part_time_male,
            'part_time_female' => $uu->part_time_female,
            'industry_desc' => $uu->industry_desc,
            'reason' => 'Failed to meet requirement to go to financials page.',
        ]);

        $user = UserDetails::query()->where('id', Session::get('userid'))->first();
        // delete records in users and UserDetails
        $user->delete();
        $uu->delete();



        Session::flash('success', 'Your Section 1 Application has been successfully submitted to the FYEI Team for review. You will receive feedback via email in the next 1 minute for confirmation to preceed to Section 2 of the application');

        return $this->successJsonMsg('redirect', route('apply'));
    }


    public function runQueryFunctions($data)
    {

        $application_user = User::query()->where('user_id', $data['user_id'])->first();

        if (!empty($application_user)) {

            DB::table('users')->where('user_id', $data['user_id'])->update($this->dumpUserDetails($data));
        } else {

            Users::query()->create($this->dumpUserDetails($data));
        }

        if (!empty($data['cash_collaterals'])) {

            $check_cash_collateral = CashCollateral::query()->where('user_id', $data['user_id'])->get();

            $cash_collaterals = json_decode($data['cash_collaterals'], false);

            if (!empty($check_cash_collateral)) {

                DB::table('cash_collaterals')->where('user_id', $data['user_id'])->delete();
            }

            foreach ($cash_collaterals as $cash_collateral) {

                CashCollateral::query()->create($this->generateCashCollaterals((array) $cash_collateral, $data['user_id']));
            }
        }


        if (!empty($data['credit_facility_details'])) {

            $credit_facility_details = json_decode($data['credit_facility_details'], false);

            $check_facility_details = CreditFacilityDetails::query()->where('user_id', $data['user_id'])->get();

            if (!empty($check_facility_details)) {

                DB::table('credit_facility_details')->where('user_id', $data['user_id'])->delete();
            }

            foreach ($credit_facility_details as $credit_facility_detail) {

                CreditFacilityDetails::query()->create($this->generateCreditFacilityDetails((array) $credit_facility_detail, $data['user_id']));
            }
        }


        if (!empty($data['credit_facility_others_details'])) {

            $credit_facility_others_details = json_decode($data['credit_facility_others_details'], false);

            $check_facility_details = CreditFacilityDetails::query()->where('user_id', $data['user_id'])->get();

            if (!empty($check_facility_details)) {

                DB::table('credit_facility_other_details')->where('user_id', $data['user_id'])->delete();
            }

            foreach ($credit_facility_others_details as $credit_facility_others_detail) {

                CreditFacilityOtherDetails::query()->create($this->generateCreditFacilityOtherDetails((array) $credit_facility_others_detail, $data['user_id']));
            }
        }


        if (!empty($data['facility_request'])) {

            $facility_requests = json_decode($data['facility_request'], false);

            $check_facility_request = FacilityRequest::query()->where('user_id', $data['user_id'])->get();

            if (!empty($check_facility_request)) {

                DB::table('facility_requests')->where('user_id', $data['user_id'])->delete();
            }

            foreach ($facility_requests as $facility_request) {

                FacilityRequest::query()->create($this->generateFacilityRequest((array) $facility_request, $data['user_id']));
            }
        }


        if (!empty($data['key_management_personnel'])) {

            $key_management_personnels = json_decode($data['key_management_personnel'], false);

            $check_management_personnel = KeyManagementPersonnel::query()->where('user_id', $data['user_id'])->get();

            if (!empty($check_management_personnel)) {

                DB::table('key_management_personnels')->where('user_id', $data['user_id'])->delete();
            }

            foreach ($key_management_personnels as $key_management_personnel) {

                KeyManagementPersonnel::query()->create($this->generateKeyManagementPersonnel((array) $key_management_personnel, $data['user_id']));
            }
        }


        if (!empty($data['major_product_line'])) {
            $major_product_lines = json_decode($data['major_product_line'], false);

            $check_product_line = MajorProductLine::query()->where('user_id', $data['user_id'])->get();

            if (!empty($check_product_line)) {

                DB::table('major_product_lines')->where('user_id', $data['user_id'])->delete();
            }

            foreach ($major_product_lines as $major_product_line) {

                MajorProductLine::query()->create($this->generateMajorProductLine((array) $major_product_line, $data['user_id']));
            }
        }



        if (!empty($data['non_cash_collaterals'])) {
            $non_cash_collaterals = json_decode($data['non_cash_collaterals'], false);

            $check_non_cash_collaterals = NonCashCollateral::query()->where('user_id', $data['user_id'])->get();

            if (!empty($check_non_cash_collaterals)) {

                DB::table('non_cash_collaterals')->where('user_id', $data['user_id'])->delete();
            }

            foreach ($non_cash_collaterals as $non_cash_collateral) {

                NonCashCollateral::query()->create($this->generateNonCashCollaterals((array) $non_cash_collateral, $data['user_id']));
            }
        }


        if (!empty($data['ownership_applicant'])) {
            $ownership_applicants = json_decode($data['ownership_applicant'], false);

            $check_ownership_applicants = OwnershipApplicant::query()->where('user_id', $data['user_id'])->get();

            if (!empty($check_ownership_applicants)) {

                DB::table('ownership_applicants')->where('user_id', $data['user_id'])->delete();
            }


            foreach ($ownership_applicants as $ownership_applicant) {

                OwnershipApplicant::query()->create($this->generateOwnershipApplicant((array) $ownership_applicant, $data['user_id']));
            }
        }
    }


    public function checkBusinessRegistration($business_structure)
    {

        $is_registered = false;

        if ($business_structure === 'Limited Liability Company (LLC)' || $business_structure === 'Partnership' || $business_structure === 'Sole Proprietorship') {

            $is_registered = true;
        }

        return $is_registered;
    }


    public function checkBusinessSector($business_type)
    {
        $business_type = BusinessType::query()->where('id', $business_type)->first();

        $sectors = ['Agriculture', 'Manufacturing', 'Green Business', 'Creative Industry', 'Tech Related Business'];


        $is_qualified_sector = false;

        if (in_array($business_type->name, $sectors)) {

            $is_qualified_sector = true;
        }

        return $is_qualified_sector;
    }
    //
    // public function calculateDOB($user)
    //   {
    //       $gender = $user->gender;
    //
    //       $age = Carbon::parse($user->dob)->age;
    //
    //       if (!empty($gender) && $gender === 'Male' && $age > 40) {
    //
    //
    //           $is_qualified = false;
    //
    //       }elseif (!empty($gender) && $gender === 'Female' && $age > 45){
    //
    //           $is_qualified = false;
    //
    //       }else{
    //
    //           $is_qualified = true;
    //
    //       }
    //
    //       return $is_qualified;
    //
    //
    //   }

    //new comment

    //     public function calculateDOB($user, $application_status = null)
    //     {
    //         $gender = $user->gender;
    //         $age = Carbon::parse($user->dob)->age;
    //
    //
    //
    //
    //         $application_funds = $application_status;
    //
    //         if (!empty($gender) && $application_funds === 'OCIF Applicant' && $age >=18 && $age <=35) {
    //
    // // return ;
    // $is_qualified=true;
    //
    //
    //         }
    //         elseif (!empty($gender) && $gender === 'Male' && $application_funds === 'FYEF Applicant'  && $age >=18 && $age <=40){
    //
    //             $is_qualified = true;
    //
    //         }elseif(!empty($gender) && $gender === 'Female' && $application_funds === 'FYEF Applicant' &&  $age >=18 && $age <=45){
    //           $is_qualified = true;
    //         }else{
    //
    //             $is_qualified = false;
    //
    //         }
    //         return $is_qualified;
    //
    //
    //     }

    public function runValidationMsg()
    {
        return  [
            // 'application_funds.required' => 'Kindly fill the empty form fields on section 1',
            'company_name.required' => 'Kindly fill the empty form fields on section 1',
            'physical_address.required' => 'Kindly fill the empty form fields on section 1',
            'email.required' => 'Kindly fill the empty form fields on section 1',
            'postal_address.required' => 'Kindly fill the empty form fields on section 1',
            'digital_address.required' => 'Kindly fill the empty form fields on section 1',

            'applicant_name.required' => 'Kindly fill the empty form fields on section 2',
            'applicant_address.required' => 'Kindly fill the empty form fields on section 2',
            'business_phone' => 'Kindly fill the empty form fields on section 2',
            'primary_contact' => 'Kindly fill the empty form fields on section 2',
            'primary_contact_phone' => 'Kindly fill the empty form fields on section 2',
            'current_bankers' => 'Kindly fill the empty form fields on section 2',
            'branch' => 'Kindly fill the empty form fields on section 2',
            'business_structure' => 'Kindly fill the empty form fields on section 2',


            'business_established_date.required' => 'Kindly fill the empty form fields on section 3',
            'tin.required' => 'Kindly fill the empty form fields on section 3',
            // 'nature_of_business.required' => 'Kindly fill the empty form fields on section 3',


            'business_type.required' => 'Kindly fill the empty form fields on section 4',
            'industry_desc.required' => 'Kindly fill the empty form fields on section 4',
            'business_premises.required' => 'Kindly fill the empty form fields on section 4',
            'business_commencement_date.required' => 'Kindly fill the empty form fields on section 4',
            // 'incorporation_date.required' => 'Kindly fill the empty form fields on section 4',
            'full_time_employees.required' => 'Kindly fill the empty form fields on section 4',
            'part_time_employees.required' => 'Kindly fill the empty form fields on section 4',
            'full_time_male.required' => 'Kindly fill the empty form fields on section 4', // (page 4)
            'full_time_female.required' => 'Kindly fill the empty form fields on section 4', // (page 4)
            'part_time_male.required' => 'Kindly fill the empty form fields on section 4', // (page 4)
            'part_time_female.required' => 'Kindly fill the empty form fields on section 4',
            'audited_financials.required' => 'Kindly fill the empty form fields on section 4',
            'has_bank_account.required' => 'Kindly fill the empty form fields on section 4',
            'required_licenses.required' => 'Kindly fill the empty form fields on section 4',


            'expected_jobs.required' => 'Kindly fill the empty form fields on section 5',
            'expected_full_time_employees.required' => 'Kindly fill the empty form fields on section 5',
            'expected_part_time_employees.required' => 'Kindly fill the empty form fields on section 5',
            'proposed_facility_tenure.required' => 'Kindly fill the empty form fields on section 5',

            'credit_facilities.required' => 'Kindly fill the empty form fields on section 6',
            'credit_facilities_others.required' => 'Kindly fill the empty form fields on section 6',
            'comment' => 'Business goals explanation must be 50 characters or more on section 6',
            'credit_facility_details' => 'Business goals explanation must be 50 characters or more on section 6',
        ];
    }


    public function runValidations()
    {
        return [
            'company_name' => 'required',
            'physical_address' => 'required',
            // 'application_funds' => 'required',
            'email' => 'required',
            'postal_address' => 'required',
            'digital_address' => 'required',
            'applicant_name' => 'required',
            'applicant_address' => 'required',
            'business_phone' => 'required|min:10|max:20',
            'primary_contact' => 'required',
            'primary_contact_phone' => 'required|min:10|max:20',
            'current_bankers' => 'required',
            'branch' => 'required',
            'business_structure' => 'required',
            'business_structure_state' => 'required_if:business_structure,==,Others',
            'business_established_date' => 'required',
            'tin' => 'required',
            // 'nature_of_business' => 'required',
            'business_type' => 'required',
            'industry_desc' => 'required',
            'business_premises' => 'required',
            'business_premise' => 'required_if:business_premises,==,Others', //(page 4) REquired if business premises is others
            'outstanding_years' => 'required_if:business_premises,==,Rented', //(page 4 REquied if business premises is rented
            'business_commencement_date' => 'required', // (page 4)
            // 'incorporation_date' => 'required', // (page 4)
            'full_time_employees' => 'required', // (page 4)
            'part_time_employees' => 'required', // (page 4)
            'full_time_male' => 'required', // (page 4)
            'full_time_female' => 'required', // (page 4)
            'part_time_male' => 'required', // (page 4)
            'part_time_female' => 'required', // (page 4)
            'audited_financials' => 'required',
            'has_bank_account' => 'required',
            'required_licenses' => 'required',
            'expected_jobs' => 'required', // (page 5)
            'expected_full_time_employees' => 'required', // (page 5)
            'expected_part_time_employees' => 'required', // (page 5)
            'proposed_facility_tenure' => 'required', // (page 5)
            'credit_facilities' => 'required',
            'credit_facilities_others' => 'required',
            'comment' => 'string|min:50|max:200',
        ];
    }


    public function dumpUserDetails($data)
    {
        $getfund = UserDetails::where('id', $data['user_id'])->first();
        return [
            'user_id' => $data['user_id'] ?? Session::get('userid') ?? null,
            'company_name' => $data['company_name'] ?? null,
            'physical_address' => $data['physical_address'] ?? null,
            'application_funds' => $getfund->position ?? null,
            'postal_address' => $data['postal_address'] ?? null,
            'email' => $data['email'] ?? null,
            'digital_address' => $data['digital_address'] ?? null,
            'applicant_name' => $data['applicant_name'] ?? null,
            'applicant_address' => $data['applicant_address'] ?? null,
            'business_phone' => $data['business_phone'] ?? null,
            'primary_contact' => $data['primary_contact'] ?? null,
            'primary_contact_phone' => $data['primary_contact_phone'] ?? null,
            'current_bankers' => $data['current_bankers'] ?? null,
            'branch' => $data['branch'] ?? null,
            'business_structure' => $data['business_structure'] ?? null,
            'business_structure_state' => $data['business_structure_state'] ?? null,
            'business_established_date' => $data['business_established_date'] ?? null,
            'tin' => $data['tin'] ?? null,
            // 'nature_of_business' => $data['nature_of_business'] ?? null,
            'business_type' => $data['business_type'] ?? null,
            'industry_desc' => $data['industry_desc'] ?? null,
            'business_premises' => $data['business_premises'] ?? null,
            'business_premise' => $data['business_premise'] ?? null,
            'outstanding_years' => $data['outstanding_years'] ?? null,
            'business_commencement_date' => $data['business_commencement_date'] ?? null,
            'incorporation_date' => $data['incorporation_date'] ?? null,
            'full_time_employees' => $data['full_time_employees'] ?? null,
            'part_time_employees' => $data['part_time_employees'] ?? null,
            'full_time_male' => $data['full_time_male'] ?? null, // (page 4)
            'full_time_female' => $data['full_time_female'] ?? null, // (page 4)
            'part_time_male' => $data['part_time_male'] ?? null, // (page 4)
            'part_time_female' => $data['part_time_female'] ?? null, //
            'audited_financials' => $data['audited_financials'] ?? null,
            'has_bank_account' => $data['has_bank_account'] ?? null,
            'required_licenses' => $data['required_licenses'] ?? null,
            'expected_jobs' => $data['expected_jobs'] ?? null,
            'expected_full_time_employees' => $data['expected_full_time_employees'] ?? null,
            'expected_part_time_employees' => $data['expected_part_time_employees'] ?? null,
            'proposed_facility_tenure' => $data['proposed_facility_tenure'] ?? null,
            'credit_facilities' => $data['credit_facilities'] ?? null,
            'credit_facilities_others_fidelity' => $data['credit_facilities_others_fidelity'] ?? null,
            'credit_facilities_others' => $data['credit_facilities_others'] ?? null,
            'credit_facilities_other_banks_others' => $data['credit_facilities_other_banks_others'] ?? null,
            'comment' => $data['comment'] ?? null,
            'application_stage' => $data['application_stage'] ?? null,
            'is_stage_complete' => $data['is_stage_complete'] ?? null,
            'is_application_complete' => $data['is_application_complete'] ?? null,
            'is_disqualified' => $data['is_disqualified'] ?? null,
            'application_status' => $data['application_status'] ?? null
        ];
    }


    public function generateOwnershipApplicant($data, $user_id)
    {

        return [
            'user_id' => $user_id,
            'name' => $data['name'],
            'tin' => $data['tin'],
            'date' => strtotime($data['date']) ? $data['date'] : null,
            'percentage_owned' => $data['percentage_owned'],
        ];
    }


    public function generateKeyManagementPersonnel($data, $user_id)
    {
        return [
            'user_id' => $user_id,
            'name' => $data['name'],
            'title' => $data['title'],
            'years_with_company' => $data['years_with_company'],
            'date_of_birth' => strtotime($data['date_of_birth']) ? $data['date_of_birth'] : null,

        ];
    }


    public function generateMajorProductLine($data, $user_id)
    {
        return [
            'user_id' => $user_id,
            'product' => $data['product'],
            'percentage_of_sales' => $data['percentage_of_sales'],
        ];
    }


    public function generateFacilityRequest($data, $user_id)
    {
        return [
            'user_id' => $user_id,
            'request' => $data['request'],
            'amount' => $data['amount'],
        ];
    }


    public function generateCashCollaterals($data, $user_id)
    {
        return [
            'user_id' => $user_id,
            'instrument_type' => $data['instrument_type'],
            'account_name' => $data['account_name'],
            'amount' => $data['amount']
        ];
    }


    public function generateNonCashCollaterals($data, $user_id)
    {
        return [
            'product' => $data['product'],
            'user_id' => $user_id,
            'market_value' => $data['market_value']
        ];
    }


    public function generateCreditFacilityDetails($data, $user_id)
    {
        return  [
            'user_id' => $user_id,
            'facility_type' => $data['facility_type'],
            'amount' => $data['amount'],
            'outstanding_amount' => $data['outstanding_amount'],
            'monthly_repayment' => $data['monthly_repayment'],
            'expiry_date' => $data['expiry_date'] ?? null
        ];
    }


    public function generateCreditFacilityOtherDetails($data, $user_id)
    {
        return [
            'user_id' => $user_id,
            'instrument_type' => $data['instrument_type'],
            'amount' => $data['amount'],
            'outstanding_amount' => $data['outstanding_amount'],
            'monthly_repayment' => $data['monthly_repayment'],
            'expiry_date' => $data['expiry_date'] ?? null
        ];
    }



    public function viewSection2filled()
    {
        $session_id = Session::get('userid');
        $check_user = User::query()->where('user_id', $session_id)->first();

        if (!empty($check_user)) {

            // return 'i am not empty';
            if ($check_user->is_application_complete === 0 && $check_user->application_stage === 'Stage 2') {

                if ($check_user->is_disqualified === 0 || $check_user->is_disqualified === null) {

                    $id = Session::get('userid');
                    $user = UserDetails::where('id', $id)->first();
                    $business_types = BusinessType::query()->get();
                    $fin = NewFinancialPerformance::query()->where('user_id', $id)->first();
                    $acc_file = ManagementAccountFile::query()->where('user_id', $id)->first();
                    $idcard_file = IdCardFile::query()->where('user_id', $id)->count();
                    $busregs_file = BusinessRegistrationDocuments::query()->where('user_id', $id)->count();
                    $banksta_file = BankStatement::query()->where('user_id', $id)->count();
                    $permit_file = Permits::query()->where('user_id', $id)->count();
                    $hist_fin_file = HistoricalFinancial::query()->where('user_id', $id)->count();
                    $data = [
                        'id' => $id,
                        'name' => $user->name,
                        'phone' => $user->phone,
                        'email' => $user->email,
                        'company_name' => $user->company_name,
                        'dob' => $user->dob,
                        'fin' => $fin,
                        'acc_file' => $acc_file,
                        'idcard_file' => $idcard_file,
                        'busregs_file' => $busregs_file,
                        'banksta_file' => $banksta_file,
                        'permit_file' => $permit_file,
                        'hist_fin_file' => $hist_fin_file,

                    ];

                    // return 'one';
                    if ($user->position == 'OCIF Applicant') {
                        return view('application.ociffinancialtwo', $data);
                    } else {
                        return view('application.financialtwo', $data);
                    }
                }
            } else  if ($check_user->is_application_complete === 1 && $check_user->application_stage === 'Stage 2') {
                if ($check_user->is_disqualified === 0 || $check_user->is_disqualified === null) {
                    // return 'two';
                    $id = Session::get('userid');
                    $user = UserDetails::where('id', $id)->first();
                    $business_types = BusinessType::query()->get();
                    $fin = NewFinancialPerformance::query()->where('user_id', $id)->first();
                    $acc_file = ManagementAccountFile::query()->where('user_id', $id)->first();
                    $idcard_file = IdCardFile::query()->where('user_id', $id)->count();
                    $busregs_file = BusinessRegistrationDocuments::query()->where('user_id', $id)->count();
                    $banksta_file = BankStatement::query()->where('user_id', $id)->count();
                    $permit_file = Permits::query()->where('user_id', $id)->count();
                    $hist_fin_file = HistoricalFinancial::query()->where('user_id', $id)->count();
                    $data = [
                        'id' => $id,
                        'name' => $user->name,
                        'phone' => $user->phone,
                        'email' => $user->email,
                        'company_name' => $user->company_name,
                        'dob' => $user->dob,
                        'fin' => $fin,
                        'acc_file' => $acc_file,
                        'idcard_file' => $idcard_file,
                        'busregs_file' => $busregs_file,
                        'banksta_file' => $banksta_file,
                        'permit_file' => $permit_file,
                        'hist_fin_file' => $hist_fin_file,

                    ];


                    if ($user->position == 'OCIF Applicant') {
                        return view('application.ociffinancialtwo', $data);
                    } else {
                        return view('application.financialtwo', $data);
                    }
                }
            }
        }


        return redirect()->route('apply');
    }



    // public function viewSection2()
    // {
    //
    //
    //     $session_id = Session::get('userid');
    //
    //     $check_user = User::query()->where('user_id', $session_id)->first();
    //
    //     if (!empty($check_user)) {
    //
    //
    //         if ($check_user->is_application_complete === 0 && $check_user->application_stage === 'Stage 2') {
    //
    //             if ($check_user->is_disqualified === 0 || $check_user->is_disqualified === null) {
    //
    //                 $id = Session::get('userid');
    //                 $user = UserDetails::where('id',$id)->first();
    //                 $business_types = BusinessType::query()->get();
    //                 $data = [
    //                     'id'=>$id,
    //                     'name'=>$user->name,
    //                     'phone'=>$user->phone,
    //                     'email'=>$user->email,
    //                     'company_name'=>$user->company_name,
    //                     'dob' => $user->dob,
    //                 ];
    //
    //
    //
    //                 return view('application.financial', $data);
    //
    //             }
    //         }
    //     }
    //
    //
    //
    //     return redirect()->route('apply');
    // }


    //

    public function processSection2two(Request $request)
    {
        $data = $request->all();
        Log::info('Stage 2 submit data: ' . json_encode($data, true));
        // $validate = Validator::make($data, $this->processSection2Validation(), $this->generateValidationMsg());
        //
        // if ($validate->fails()){
        //     return $this->failJsonMsg($validate->errors()->first());
        // }

        $allowedfileExtension = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'];

        $data['user_id'] = Session::get('userid');

        if (!empty($request->file('management_account'))) {
            foreach ($request->file('management_account') as $item) {

                $extension = $item->getClientOriginalExtension();
                $check = in_array($extension, $allowedfileExtension);

                if (!$check) {
                    return $this->failJsonMsg('Management Account must be a file of type: jpg, jpeg, png, pdf, doc, docx');
                }
            }
        }

        if ($request->isocif == 0) {
            if (!empty($request->file('historic_financial'))) {
                foreach ($request->file('historic_financial') as $item) {

                    $extension = $item->getClientOriginalExtension();
                    $check = in_array($extension, $allowedfileExtension);

                    if (!$check) {
                        return $this->failJsonMsg('Historic Financial must be a file of type: jpg, jpeg, png, pdf, doc, docx');
                    }
                }
            }
        }



        if (!empty($request->file('business_registration_documents'))) {
            foreach ($request->file('business_registration_documents') as $item) {
                $extension = $item->getClientOriginalExtension();
                $check = in_array($extension, $allowedfileExtension);

                if (!$check) {
                    return $this->failJsonMsg('Business Registration Document must be a file of type: jpg, jpeg, png, pdf, doc, docx');
                }
            }
        }

        if (!empty($request->file('id_cards'))) {
            foreach ($request->file('id_cards') as $item) {

                $extension = $item->getClientOriginalExtension();
                $check = in_array($extension, $allowedfileExtension);

                if (!$check) {
                    return $this->failJsonMsg('ID Card must be a file of type: jpg, jpeg, png, pdf, doc, docx');
                }
            }
        }
        if (!empty($request->file('permits'))) {
            foreach ($request->file('permits') as $item) {

                $extension = $item->getClientOriginalExtension();
                $check = in_array($extension, $allowedfileExtension);

                if (!$check) {
                    return $this->failJsonMsg('Permit must be a file of type: jpg, jpeg, png, pdf, doc, docx');
                }
            }
        }


        $get_user = NewFinancialPerformance::query()->where('user_id', $data['user_id'])->first();

        if (empty($get_user)) {

            $get_user = NewFinancialPerformance::query()->create($this->dumpFinancialData($data));
        } else {

            $get_user->update($this->dumpFinancialData($data));
        }


        if (!empty($request->file('business_plan'))) {

            if (File::exists($get_user->business_plan)) {

                File::delete($get_user->business_plan);
            }
            $get_user->update([
                'business_plan' => $this->performUpload($request->file('business_plan'), "business/" . $data['user_id'] . "/")
            ]);
        }


        if (!empty($request->file('projected_financial_statement'))) {

            if (File::exists($get_user->projected_financial_statement)) {

                File::delete($get_user->projected_financial_statement);
            }

            $get_user->update([
                'projected_financial_statement' => $this->performUpload($request->file('projected_financial_statement'), "projected_financial_statement/" . $data['user_id'] . "/")
            ]);
        }




        $this->runFileUploads($request, $data);

        Users::query()->where('user_id', $data['user_id'])->update([
            'is_application_complete' => true,
            'is_disqualified' => false,
        ]);


        $user = UserDetails::query()->where('id', $data['user_id'])->first();

        $user->application_status = 'Completed';
        $user->save();

        $data['name'] = $user->name;

        Mail::to($user->email)->send(new ApplicationCompletedMail($data));
        Mail::to('partnerships&youthenterprise@myfidelitybank.net')->send(new ApplicationCompletedMail($data));



        // assign admin project and credit to application
        // project and credit admin with least appcount
        $projectwithleast = AdminModel::where('role', '2')->orderBy('appcount', 'desc')->first();
        $creditwithleast = AdminModel::where('role', '3')->orderBy('appcount', 'desc')->first();


        if ($projectwithleast !== null) {

            $assignagent = Users::where('user_id', $data['user_id'])->whereNull('projectanalyst_id')->update([
                'projectanalyst_id' => $projectwithleast->id,
            ]);
            $newcount = $projectwithleast->appcount + 1;
            $projectwithleast->update([
                'appcount' => $newcount
            ]);

            $data = [
                'proj' => $projectwithleast->name,
                'appname' => $user->name,
                'company_name' => $user->company_name,
            ];




            Mail::to($projectwithleast->email)->send(new FYEIApplicationAssignment($data));
        }

        if ($creditwithleast !== null) {
            $assignagents = Users::where('user_id', $data['user_id'])->whereNull('projectanalyst_id')->update([
                'creditanalyst_id' => $creditwithleast->id,
            ]);
            $newcountd = $creditwithleast->appcount + 1;
            $creditwithleast->update([
                'appcount' => $newcountd
            ]);


            $datax = [
                'credit' => $creditwithleast->name,
                'appname' => $user->name,
                'company_name' => $user->company_name,
            ];
            Mail::to($creditwithleast->email)->send(new FYEIApplicationAssignments($datax));
        }




        // $details=[
        //
        //     'greeting' => 'Hello Team,',
        //     'body'=> 'An application has been submitted by '.$user->name,
        //     'actiontext' => 'Go to site',
        //     'actionurl' => '/',
        //     'lastline' => 'Thank you'
        // ];
        // // Notification::route('mail', ['partnerships&youthenterprise@myfidelitybank.net'])->notify(new SendEmailNotification($details));
        // Notification::route('mail', ['sbeng@npontu.com'])->notify(new SendEmailNotification($details));
        //


        return $this->successJsonMsg('redirect', route('completed.form'));
    }

    //





    public function viewSection2()
    {

        $session_id = Session::get('userid');

        $check_user = User::query()->where('user_id', $session_id)->first();

        if (!empty($check_user)) {


            if ($check_user->is_application_complete === 0 && $check_user->application_stage === 'Stage 2') {

                if ($check_user->is_disqualified === 0 || $check_user->is_disqualified === null) {

                    $id = Session::get('userid');
                    $user = UserDetails::where('id', $id)->first();
                    $business_types = BusinessType::query()->get();
                    $data = [
                        'id' => $id,
                        'name' => $user->name,
                        'phone' => $user->phone,
                        'email' => $user->email,
                        'company_name' => $user->company_name,
                        'dob' => $user->dob,
                    ];

                    if ($user->position == 'OCIF Applicant') {
                        return view('application.ociffinancial', $data);
                    } else {
                        return view('application.financial', $data);
                    }
                }
            }
        }



        return redirect()->route('apply');
    }


    public function processSection2(Request $request)
    {
        $data = $request->all();
        Log::info('Stage 2 submit data: ' . json_encode($data, true));

        $validate = Validator::make($data, $this->processSection2Validation(), $this->generateValidationMsg());

        if ($validate->fails()) {
            return $this->failJsonMsg($validate->errors()->first());
        }

        $allowedfileExtension = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'];

        $data['user_id'] = Session::get('userid');

        if (!empty($request->file('management_account'))) {
            foreach ($request->file('management_account') as $item) {

                $extension = $item->getClientOriginalExtension();
                $check = in_array($extension, $allowedfileExtension);

                if (!$check) {
                    return $this->failJsonMsg('Management Account must be a file of type: jpg, jpeg, png, pdf, doc, docx');
                }
            }
        } else {

            return $this->failJsonMsg('Kindly fill Management Account Field');
        }


        if ($request->isocif == 0) {
            if (!empty($request->file('historic_financial'))) {
                foreach ($request->file('historic_financial') as $item) {

                    $extension = $item->getClientOriginalExtension();
                    $check = in_array($extension, $allowedfileExtension);

                    if (!$check) {
                        return $this->failJsonMsg('Historic Financial must be a file of type: jpg, jpeg, png, pdf, doc, docx');
                    }
                }
            } else {

                return $this->failJsonMsg('Kindly fill Historic Financial Field');
            }
        }


        if (!empty($request->file('business_registration_documents'))) {
            foreach ($request->file('business_registration_documents') as $item) {
                $extension = $item->getClientOriginalExtension();
                $check = in_array($extension, $allowedfileExtension);

                if (!$check) {
                    return $this->failJsonMsg('Business Registration Document must be a file of type: jpg, jpeg, png, pdf, doc, docx');
                }
            }
        } else {
            return $this->failJsonMsg('Kindly fill Business Management Account Field');
        }

        if (!empty($request->file('id_cards'))) {
            foreach ($request->file('id_cards') as $item) {

                $extension = $item->getClientOriginalExtension();
                $check = in_array($extension, $allowedfileExtension);

                if (!$check) {
                    return $this->failJsonMsg('ID Card must be a file of type: jpg, jpeg, png, pdf, doc, docx');
                }
            }
        } else {
            return $this->failJsonMsg('Kindly fill ID Card Field');
        }
        if (!empty($request->file('permits'))) {
            foreach ($request->file('permits') as $item) {

                $extension = $item->getClientOriginalExtension();
                $check = in_array($extension, $allowedfileExtension);

                if (!$check) {
                    return $this->failJsonMsg('Permit must be a file of type: jpg, jpeg, png, pdf, doc, docx');
                }
            }
        } else {
            return $this->failJsonMsg('Kindly fill Permit Field');
        }


        $get_user = NewFinancialPerformance::query()->where('user_id', $data['user_id'])->first();

        if (empty($get_user)) {

            $get_user = NewFinancialPerformance::query()->create($this->dumpFinancialData($data));
        } else {

            $get_user->update($this->dumpFinancialData($data));
        }


        if (!empty($request->file('business_plan'))) {

            if (File::exists($get_user->business_plan)) {

                File::delete($get_user->business_plan);
            }
            $get_user->update([
                'business_plan' => $this->performUpload($request->file('business_plan'), "business/" . $data['user_id'] . "/")
            ]);
        }


        if (!empty($request->file('projected_financial_statement'))) {

            if (File::exists($get_user->projected_financial_statement)) {

                File::delete($get_user->projected_financial_statement);
            }

            $get_user->update([
                'projected_financial_statement' => $this->performUpload($request->file('projected_financial_statement'), "projected_financial_statement/" . $data['user_id'] . "/")
            ]);
        }



        $this->runFileUploads($request, $data);

        Users::query()->where('user_id', $data['user_id'])->update([
            'is_application_complete' => true,
            'is_disqualified' => false,
        ]);


        $user = UserDetails::query()->where('id', $data['user_id'])->first();


        $user->application_status = 'Completed';
        $user->save();

        $this->logActivity('Applicant', 'Client', 'Completed Application', $user->name . ' completed application', $user->id);

        $data['name'] = $user->name;

        Mail::to($user->email)->cc('partnerships&youthenterprise@myfidelitybank.net')->send(new ApplicationCompletedMail($data));


        // assign admin project and credit to application
        // project and credit admin with least appcount
        $projectwithleast = AdminModel::where('role', '2')->orderBy('appcount', 'desc')->first();
        $creditwithleast = AdminModel::where('role', '3')->orderBy('appcount', 'desc')->first();
        // return $projectwithleast;

        if ($projectwithleast !== null) {
            $assignagent = Users::where('user_id', $user->id)->update([
                'projectanalyst_id' => $projectwithleast->id,
            ]);
            $newcount = $projectwithleast->appcount + 1;

            $projectwithleast->update([
                'appcount' => $newcount
            ]);
            // return $newcount;
            $data = [
                'proj' => $projectwithleast->name,
                'appname' => $user->name,
                'company_name' => $user->company_name,
            ];
            Mail::to($projectwithleast->email)->send(new FYEIApplicationAssignment($data));
        }

        if ($creditwithleast !== null) {
            $assignagents = Users::where('user_id', $user->id)->update([
                'creditanalyst_id' => $creditwithleast->id,
            ]);
            $newcountd = $creditwithleast->appcount + 1;
            $creditwithleast->update([
                'appcount' => $newcountd
            ]);

            $datax = [
                'credit' => $creditwithleast->name,
                'appname' => $user->name,
                'company_name' => $user->company_name,
            ];



            Mail::to($creditwithleast->email)->send(new FYEIApplicationAssignments($datax));
        }






        // $details=[
        //
        //     'greeting' => 'Hello Team,',
        //     'body'=> 'An application has been submitted by '.$user->name,
        //     'actiontext' => 'Go to site',
        //     'actionurl' => '/',
        //     'lastline' => 'Thank you'
        // ];
        // // Notification::route('mail', ['partnerships&youthenterprise@myfidelitybank.net'])->notify(new SendEmailNotification($details));
        // Notification::route('mail', ['sbeng@npontu.com'])->notify(new SendEmailNotification($details));



        return $this->successJsonMsg('redirect', route('completed.form'));
    }







    public function runFileUploads($request, $data)
    {
        if (!empty($request->file('management_account'))) {

            $management_account = collect();

            $check_management_account = ManagementAccountFile::query()->where('user_id', $data['user_id'])->get();

            if (!empty($check_management_account)) {
                foreach ($check_management_account as $item) {
                    if (File::exists($item->path)) {

                        File::delete($item->path);
                    }
                }
            }

            foreach ($request->file('management_account') as $file) {

                $management_account->push([
                    'user_id' => $data['user_id'],
                    'path' => $this->performUpload($file, "management_account/" . $data['user_id'] . "/")
                ]);
            }

            DB::table('management_account_files')->insert($management_account->toArray());
        }

        if ($request->isocif == 0) {
            if (!empty($request->file('historic_financial'))) {

                $historic_financial = collect();

                $check_historic_financial = HistoricalFinancial::query()->where('user_id', $data['user_id'])->get();

                if (!empty($check_historic_financial)) {
                    foreach ($check_historic_financial as $item) {
                        if (File::exists($item->historical_financial)) {

                            File::delete($item->historical_financial);
                        }
                        $item->delete();
                    }
                }

                foreach ($request->file('historic_financial') as $file) {

                    $historic_financial->push([
                        'user_id' => $data['user_id'],
                        'historical_financial' => $this->performUpload($file, "historic_financial/" . $data['user_id'] . "/")
                    ]);
                }

                DB::table('historical_financial')->insert($historic_financial->toArray());
            }
        }



        if (!empty($request->file('id_cards'))) {

            $id_cards = collect();


            $files = IdCardFile::query()->where('user_id', $data['user_id'])->get();

            if (!empty($files)) {
                foreach ($files as $item) {
                    if (File::exists($item->path)) {

                        File::delete($item->path);
                    }
                }
            }


            foreach ($request->file('id_cards') as $file) {
                $id_cards->push([
                    'user_id' => $data['user_id'],
                    'path' => $this->performUpload($file, "id_cards/" . $data['user_id'] . "/")
                ]);
            }

            DB::table('id_card_files')->insert($id_cards->toArray());
        }




        if (!empty($request->file('business_registration_documents'))) {

            $business_registration_documents = collect();

            $files = BusinessRegistrationDocuments::query()->where('user_id', $data['user_id'])->get();

            if (!empty($files)) {
                foreach ($files as $item) {
                    if (File::exists($item->path)) {

                        File::delete($item->path);
                    }
                }
            }

            foreach ($request->file('business_registration_documents') as $file) {
                $business_registration_documents->push([
                    'user_id' => $data['user_id'],
                    'path' => $this->performUpload($file, "business_registration_documents/" . $data['user_id'] . "/")
                ]);
            }

            DB::table('business_registration_documents')->insert($business_registration_documents->toArray());
        }




        if (!empty($request->file('bank_statements'))) {

            $bank_statements = collect();

            $files = BankStatement::query()->where('user_id', $data['user_id'])->get();

            if (!empty($files)) {
                foreach ($files as $item) {
                    if (File::exists($item->path)) {

                        File::delete($item->path);
                    }
                }
            }

            foreach ($request->file('bank_statements') as $file) {
                $bank_statements->push([
                    'user_id' => $data['user_id'],
                    'path' => $this->performUpload($file, "bank_statements/" . $data['user_id'] . "/")
                ]);
            }

            DB::table('bank_statements')->insert($bank_statements->toArray());
        }



        if (!empty($request->file('permits'))) {

            $permits = collect();

            $files = Permits::query()->where('user_id', $data['user_id'])->get();

            if (!empty($files)) {
                foreach ($files as $item) {
                    if (File::exists($item->path)) {

                        File::delete($item->path);
                    }
                }
            }

            foreach ($request->file('permits') as $file) {
                $permits->push([
                    'user_id' => $data['user_id'],
                    'path' => $this->performUpload($file, "permits/" . $data['user_id'] . "/")
                ]);
            }

            DB::table('permits')->insert($permits->toArray());
        }
    }



    public function performUpload($file, $path)
    {

        # Add random string to filename
        $file_name = time() . '' . $file->getClientOriginalName();

        # Get absolute path for file storage
        $abs_path = storage_path("app/public/$path");

        //        Storage::put($abs_path, $file_name);
        $file->move($abs_path, $file_name);

        return "storage/$path" . $file_name;
    }


    public function processSection2Validation()
    {

        return [
            'avg_inventory' => 'required',
            'avg_inventory_21' => 'required_if:isocif,==,1',
            'cost_of_sales' => 'required',
            'cost_of_sales_21' => 'required_if:isocif,==,1',
            'credit_purchases' => 'required',
            'credit_purchases_21' => 'required_if:isocif,==,1',
            'credit_sales' => 'required',
            'credit_sales_21' => 'required_if:isocif,==,1',
            'current_assets' => 'required',
            'current_assets_21' => 'required_if:isocif,==,1',
            'current_liabilities' => 'required',
            'current_liabilities_21' => 'required_if:isocif,==,1',
            'gross_profit' => 'required',
            'gross_profit_21' => 'required_if:isocif,==,1',
            'inventory' => 'required',
            'inventory_21' => 'required_if:isocif,==,1',
            'net_profit' => 'required',
            'net_profit_21' => 'required_if:isocif,==,1',
            'sales_turnover' => 'required',
            'sales_turnover_21' => 'required_if:isocif,==,1',
            // 'sales_turnover_revenue' => 'required',
            // 'sales_turnover_revenue_21' => 'required_if:isocif,==,1',
            'share_equity' => 'required',
            'share_equity_21' => 'required_if:isocif,==,1',
            'total_debt' => 'required',
            'total_debt_21' => 'required_if:isocif,==,1',
            'trade_payables' => 'required',
            'trade_payables_21' => 'required_if:isocif,==,1',
            'trade_receivables' => 'required',
            'trade_receivables_21' => 'required_if:isocif,==,1',
            'historic_financial' => 'required_if:isocif,==,0',
            'bank_statements.*' => 'required|mimes:pdf,doc,docx,jpeg,jpg,png',
            'business_plan' => 'required|mimes:pdf,doc,docx,jpeg,jpg,png',
            'business_registration_documents.*' => 'required|mimes:pdf,doc,docx,jpeg,jpg,png',
            'id_cards.*' => 'required|mimes:pdf,doc,docx,jpeg,jpg,png',
            'management_account.*' => 'required|mimes:pdf,doc,docx,jpeg,jpg,png',
            'permits.*' => 'required|mimes:pdf,doc,docx,jpeg,jpg,png',
            'projected_financial_statement' => 'required|mimes:pdf,doc,docx,jpeg,jpg,png',
        ];
    }


    public function generateValidationMsg()
    {
        return [
            'avg_inventory' => 'Kindly Fill all Required Form Fields',
            'avg_inventory_21' => 'Kindly Fill all Required Form Fields',
            'cost_of_sales' => 'Kindly Fill all Required Form Fields',
            'cost_of_sales_21' => 'Kindly Fill all Required Form Fields',
            'credit_purchases' => 'Kindly Fill all Required Form Fields',
            'credit_purchases_21' => 'Kindly Fill all Required Form Fields',
            'credit_sales' => 'Kindly Fill all Required Form Fields',
            'credit_sales_21' => 'Kindly Fill all Required Form Fields',
            'current_assets' => 'Kindly Fill all Required Form Fields',
            'current_assets_21' => 'Kindly Fill all Required Form Fields',
            'current_liabilities' => 'Kindly Fill all Required Form Fields',
            'current_liabilities_21' => 'Kindly Fill all Required Form Fields',
            'gross_profit' => 'Kindly Fill all Required Form Fields',
            'gross_profit_21' => 'Kindly Fill all Required Form Fields',
            'inventory' => 'Kindly Fill all Required Form Fields',
            'inventory_21' => 'Kindly Fill all Required Form Fields',
            'net_profit' => 'Kindly Fill all Required Form Fields',
            'net_profit_21' => 'Kindly Fill all Required Form Fields',
            'sales_turnover' => 'Kindly Fill all Required Form Fields',
            'sales_turnover_21' => 'Kindly Fill all Required Form Fields',
            // 'sales_turnover_revenue' => 'Kindly Fill all Required Form Fields',
            // 'sales_turnover_revenue_21' => 'Kindly Fill all Required Form Fields',
            'share_equity' => 'Kindly Fill all Required Form Fields',
            'share_equity_21' => 'Kindly Fill all Required Form Fields',
            'total_debt' => 'Kindly Fill all Required Form Fields',
            'total_debt_21' => 'Kindly Fill all Required Form Fields',
            'trade_payables' => 'Kindly Fill all Required Form Fields',
            'trade_payables_21' => 'Kindly Fill all Required Form Fields',
            'trade_receivables' => 'Kindly Fill all Required Form Fields',
            'trade_receivables_21' => 'Kindly Fill all Required Form Fields',
            // 'application_funds.required' => 'Kindly fill the empty form fields on section 1',
            'historic_financial' => 'Kindly fill the 1 year historical financial statements',
            'company_name.required' => 'Kindly fill the empty form fields on section 1',
            'physical_address.required' => 'Kindly fill the empty form fields on section 1',
            'email.required' => 'Kindly fill the empty form fields on section 1',
            'postal_address.required' => 'Kindly fill the empty form fields on section 1',
            'digital_address.required' => 'Kindly fill the empty form fields on section 1',
        ];
    }


    public function formatValues($number)
    {
        return number_format($number, 3);
    }


    public function checkDivisionByZero($num, $denom)
    {
        return $denom == 0 ? ($num / 1) : ($num / $denom);
    }

    public function calculateQuickRatio($data)
    {


        $quick_ratio = $this->checkDivisionByZero(($data['current_assets'] - $data['inventory']), $data['current_liabilities']);
        if ($data['isocif'] == 0) {
            $quick_ratio_2021 = 0;
        } else {
            $quick_ratio_2021 = $this->checkDivisionByZero(($data['current_assets_21'] - $data['inventory_21']), $data['current_liabilities_21']);
        }

        return [
            '2020' => $this->formatValues($quick_ratio),
            '2021' => $this->formatValues($quick_ratio_2021)
        ];
    }



    public function calculateCurrentRatio($data)
    {
        $current_ratio =  $this->checkDivisionByZero($data['current_assets'], $data['current_liabilities']);
        if ($data['isocif'] == 0) {
            $current_ratio_21 = 0;
        } else {
            $current_ratio_21 =  $this->checkDivisionByZero($data['current_assets_21'], $data['current_liabilities_21']);
        }


        return  [
            '2020' => $this->formatValues($current_ratio),
            '2021' => $this->formatValues($current_ratio_21),
        ];
    }

    public function calculateGearing($data)
    {
        $gearing = $this->checkDivisionByZero($data['total_debt'], $data['share_equity']);

        if ($data['isocif'] == 0) {
            $gearing_21 = 0;
        } else {
            $gearing_21 = $this->checkDivisionByZero($data['total_debt_21'], $data['share_equity_21']);
        }



        return [
            '2020' => $this->formatValues($gearing),
            '2021' => $this->formatValues($gearing_21)
        ];
    }

    public function calculateGrossProfitMargin($data)
    {
        $grossProfit = ($this->checkDivisionByZero($data['gross_profit'], $data['sales_turnover'])) * 100;


        if ($data['isocif'] == 0) {
            $grossProfit_21 = 0;
        } else {
            $grossProfit_21 = ($this->checkDivisionByZero($data['gross_profit_21'], $data['sales_turnover_21'])) * 100;
        }




        return [
            '2020' => $this->formatValues($grossProfit),
            '2021' => $this->formatValues($grossProfit_21)
        ];
    }

    public function calculateNetProfitMargin($data)
    {

        $netProfit = ($this->checkDivisionByZero($data['net_profit'], $data['sales_turnover'])) * 100;


        if ($data['isocif'] == 0) {
            $netProfit_21 = 0;
        } else {
            $netProfit_21 = ($this->checkDivisionByZero($data['net_profit_21'], $data['sales_turnover_21'])) * 100;
        }



        return [
            '2020' => $this->formatValues($netProfit),
            '2021' => $this->formatValues($netProfit_21)
        ];
    }

    public function calculateEfficiencyRatio($data)
    {

        $trade_receivable = ($this->checkDivisionByZero($data['trade_receivables'], $data['credit_sales'])) * 365;


        if ($data['isocif'] == 0) {
            $trade_receivable_21 = 0;
            $payable_days_21 = 0;
            $inventory_days_21 = 0;
        } else {
            $trade_receivable_21 = ($this->checkDivisionByZero($data['trade_receivables_21'], $data['credit_sales_21'])) * 365;
            $payable_days_21 = ($this->checkDivisionByZero($data['trade_receivables_21'], $data['credit_purchases_21'])) * 365;
            $inventory_days_21 = ($this->checkDivisionByZero($data['avg_inventory_21'], $data['cost_of_sales_21'])) * 365;
        }



        $payable_days = ($this->checkDivisionByZero($data['trade_receivables'], $data['credit_purchases'])) * 365;


        $inventory_days = ($this->checkDivisionByZero($data['avg_inventory'], $data['cost_of_sales'])) * 365;




        return [
            '2020' => $this->formatValues(($trade_receivable + $inventory_days) - $payable_days),
            '2021' => $this->formatValues(($trade_receivable_21 + $inventory_days_21) - $payable_days_21)
        ];
    }


    public function dumpFinancialData($data)
    {
        return [
            'user_id' => $data['user_id'],
            'avg_inventory' => $data['avg_inventory'],
            'cost_of_sales' => $data['cost_of_sales'],
            'credit_purchases' => $data['credit_purchases'],
            'credit_sales' => $data['credit_sales'],
            'current_assets' => $data['current_assets'],
            'current_liabilities' => $data['current_liabilities'],
            'gross_profit' => $data['gross_profit'],
            'inventory' => $data['inventory'],
            'net_profit' => $data['net_profit'],
            'sales_turnover' => $data['sales_turnover'],
            // 'sales_turnover_revenue' => $data['sales_turnover_revenue'],
            'share_equity' => $data['share_equity'],
            'total_debt' => $data['total_debt'],
            'trade_payables' => $data['trade_payables'],
            'trade_receivables' => $data['trade_receivables'],
            'avg_inventory_21' => $data['avg_inventory_21'] ?? null,
            'cost_of_sales_21' => $data['cost_of_sales_21'] ?? null,
            'credit_purchases_21' => $data['credit_purchases_21'] ?? null,
            'credit_sales_21' => $data['credit_sales_21'] ?? null,
            'current_assets_21' => $data['current_assets_21'] ?? null,
            'current_liabilities_21' => $data['current_liabilities_21'] ?? null,
            'gross_profit_21' => $data['gross_profit_21'] ?? null,
            'inventory_21' => $data['inventory_21'] ?? null,
            'net_profit_21' => $data['net_profit_21'] ?? null,
            'sales_turnover_21' => $data['sales_turnover_21'] ?? null,
            // 'sales_turnover_revenue_21' => $data['sales_turnover_revenue_21']??null,
            'share_equity_21' => $data['share_equity_21'] ?? null,
            'total_debt_21' => $data['total_debt_21'] ?? null,
            'trade_payables_21' => $data['trade_payables_21'] ?? null,
            'trade_receivables_21' => $data['trade_receivables_21'] ?? null,
            'quick_ratio_total' => $this->calculateQuickRatio($data)['2020'],
            'quick_ratio_total_21' => $this->calculateQuickRatio($data)['2021'] ?? null,
            'current_ratio_total' => $this->calculateCurrentRatio($data)['2020'],
            'current_ratio_total_21' => $this->calculateCurrentRatio($data)['2021'] ?? null,
            'gearing_total' => $this->calculateGearing($data)['2020'],
            'gearing_total_21' => $this->calculateGearing($data)['2021'] ?? null,
            'gross_profit_margin_total' => $this->calculateGrossProfitMargin($data)['2020'],
            'gross_profit_margin_total_21' => $this->calculateGrossProfitMargin($data)['2021'] ?? null,
            'net_profit_margin_total' => $this->calculateNetProfitMargin($data)['2020'],
            'net_profit_margin_total_21' => $this->calculateNetProfitMargin($data)['2021'] ?? null,
            'efficiency_ratio_total' => $this->calculateEfficiencyRatio($data)['2020'],
            'efficiency_ratio_total_21' => $this->calculateEfficiencyRatio($data)['2021'] ?? null,
        ];
    }
}
