<?php

namespace App\Http\Controllers;

use App\BusinessType;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
use App\OtpModel;
use App\UserDetails;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use App\MachineUsedModel;
use App\OperationsModel;
use App\DirectorsModel;
use App\BankMomo;
use App\BusRegs;
use App\HistoricalFinancial;
use App\License;
use App\Pitchdeck;
use App\AcceptedOfferLetter;
use App\DirectionalSketch;
use App\EsrmReport;
use App\FyepApplication;
use App\IrrevocableInstruction;
use App\OperatingPermit;
use App\RequestFacility;
use App\UpfrontPayment;
use App\FinancialRatios;
use App\OwnershipApplicant;
use App\KeyManagementPersonnel;
use App\MajorProductLine;
use App\NonCashCollateral;
use App\FacilityRequest;
use App\CashCollateral;
use App\InitialReject;

use Carbon\Carbon;
use Mail;
use App\Mail\ApplicationCompletedMail;
use App\Mail\RejectedApplication;

use App\FinancialPerformanceModel;
use App\KpiModel;
use App\CreditHistoryModel;
use App\OperatingPersonnelModel;
use App\ProductionLevelsModel;
use App\ProductPackagingModel;
use App\AddtionalMachineModel;
use GuzzleHttp\Client as GuzzleClient;
use Illuminate\Support\Facades\Session;

class PagesController extends Controller
{

  public function index(){

    return view('index');
  }

  public function startapplication(){
    return view('application.index');
  }


  public function sendotp(Request $r){
    $validatedData = $r->validate([
                'name' => 'required|max:255',
                'company_name' => 'required|max:255',
                'email' => 'required|email',
                'date_of_birth' => 'required|',
                'gender' => 'required',
                'application_funds' => 'required',
                'phone' => 'required',

            ]);

    $outputString = preg_replace('/[^0-9]/', '', $r->phone);
    $ed=  strlen($outputString);
    if ($ed==10||$ed==12) {
      $checkemail = UserDetails::where('email',$r->email)->orWhere('phone',$r->phone)->first();
      if ($checkemail !== null) {
        return redirect()->back()->with('error','Email/Phone Already Exists, Please use the restore progress option to continue');
      }


      session(['name' => $r->input('name')]);
      session(['email' => $r->input('email')]);
      session(['phone' => $r->input('phone')]);
      session(['date_of_birth' => $r->input('date_of_birth')]);
      session(['company_name' => $r->input('company_name')]);
      session(['gender' => $r->input('gender')]);
      session(['application_funds' => $r->input('application_funds')]);
      $otp =rand(1000,9999);
      $saveotp = OtpModel::create([
        'code'=>$otp,
      ]);

      session(['optid'=>$saveotp->id]);


// check age and application type
  $age = Carbon::parse($r->date_of_birth)->age;
  $application_funds = $r->application_funds;
  if (!empty($r->gender) && $application_funds === 'OCIF Applicant' && $age >=18 && $age <=35) {

// return $age;
    //send otp sms
    $number = $r->input('phone');
    $source='FYEI';
    $message="Hello, Your OTP code is ".$otp;
    $sms_name = env('SMS_USERNAME');
    $sms_pass = env('SMS_PASSWORD');
  /////////// ////////////
    $url = "https://deywuro.com/api/sms?username=$sms_name&password=$sms_pass&source=$source&destination=" . $number . "&message=" . $message;

    $client = new GuzzleClient();

    $request = $client->request('GET', $url, [
      'http_errors' => false,
    ]);
    $response = json_decode($request->getBody()->getContents(),true);
    //////// ////////////////
    return redirect()->route('showverify');


  }
  elseif (!empty($r->gender) && $r->gender === 'Male' && $application_funds === 'FYEF Applicant'  && $age >=18 && $age <=40){

    //send otp sms
    $number = $r->input('phone');
    $source='FYEI';
    $message="Hello, Your OTP code is ".$otp;
    $sms_name = env('SMS_USERNAME');
    $sms_pass = env('SMS_PASSWORD');
    /////////// ///////////////
    $url = "https://deywuro.com/api/sms?username=$sms_name&password=$sms_pass&source=$source&destination=" . $number . "&message=" . $message;
    $client = new GuzzleClient();

    $request = $client->request('GET', $url, [
      'http_errors' => false,
    ]);

    $response = json_decode($request->getBody()->getContents(),true);
    ////////// //////////////
    return redirect()->route('showverify');

  }elseif(!empty($r->gender) && $r->gender === 'Female' && $application_funds === 'FYEF Applicant' &&  $age >=18 && $age <=45){
    //send otp sms
    ////////// //////////////
    $number = $r->input('phone');
    $source='FYEI';
    $message="Hello, Your OTP code is ".$otp;
    $sms_name = env('SMS_USERNAME');
    $sms_pass = env('SMS_PASSWORD');
    //
    $url = "https://deywuro.com/api/sms?username=$sms_name&password=$sms_pass&source=$source&destination=" . $number . "&message=" . $message;
    $client = new GuzzleClient();

    $request = $client->request('GET', $url, [
      'http_errors' => false,
    ]);

    $response = json_decode($request->getBody()->getContents(),true);
    ////////// //////////////////
    return redirect()->route('showverify');
  }else{
    // return $gender;
// store details for reff
$store = InitialReject::create([
  'name'=>$r->name,
  'company_name'=>$r->company_name,
  'email'=>$r->email,
  'phone'=>$r->phone,
  'dob'=>$r->date_of_birth,
  'gender'=>$r->gender,
  'app_fund'=>$r->application_funds,
]);


$data = [
  'name'=>$r->name,
];
     Mail::to($r->email)->send(new RejectedApplication($data));
return redirect()->back()->with('success','Your application could not be completed. Please find reason(s) in your mail.');
  }




    }else {
      return redirect()->back()->with('error','Invalid Phone Number Format');
    }

  }

  public function sentotp(){
    return view('application.showverify');
  }

  public function verifyotp(Request $r){
    $one = $r->input('one');
    $two = $r->input('two');
    $three = $r->input('three');
    $four = $r->input('four');

    $code = $one.$two.$three.$four;

    $checkotp = OtpModel::where('code',$code)->where('used_at',null)->first();
    if ($checkotp!==null) {
      $checkotp->used_at=date('d-m-y h:i:s');
      $checkotp->save();

      $name = Session::get('name')==null ?'':Session::get('name');
      $date_of_birth = Session::get('date_of_birth');
      $email = Session::get('email');
      $phone = Session::get('phone');
      $company_name = Session::get('company_name');
      $gender = Session::get('gender');
      $application_funds = Session::get('application_funds');

      $newnum ='';
      $outputString = preg_replace('/[^0-9]/', '', $phone);
      // return $checkstring;
      $checkstring = substr( $outputString, 0,1);
      if ($checkstring == 0) {
        $newnum = "233".substr( $outputString,1);
      }elseif($checkstring == 2) {
        $newnum = "0".substr( $outputString,3);
      }
      $checkuser=UserDetails::where('phone',$outputString)->orWhere('phone',$newnum)->first();

      if ($checkuser == null) {
        $createuser = UserDetails::create([
          'name'=>$name,
          'email'=>$email,
          'phone'=>$phone,
          'dob'=>$date_of_birth,
          'company_name'=>$company_name,
          'application_status'=> 'Not Started',
            'gender' => $gender,
            'position'=>$application_funds,
        ]);
        session(['check' => 'true']);
        session(['userid' => $createuser->id]);
        session()->forget(['name','email','phone']);

        $this->logActivity('New Applicant', 'Client', 'New Application', $name.' started a new application', $createuser->id);


        return redirect()->route('companydetails');
      }else {
        session(['userid' => $checkuser->id]);

        // Custom function to redirect some users to financial page
          $check_user = User::query()->where('user_id', $checkuser->id)->first();


         // return $check_user->getUserDetails;

          if (!empty($check_user)){
            // if ($check_user->is_disqualified === 1) {
            //   return redirect()->route('apply')->with('success','Application Rejected. Kindly check your mail for reasons!');
            // }else
            if ($check_user->is_disqualified === 2) {
              return redirect()->route('apply')->with('success','Application Under Review. Application may not be edited!');
            }
            // elseif ($check_user->is_disqualified === 3) {
            //   return redirect()->route('apply')->with('success','Application Rejected. Kindly check your mail for reasons.!');
            // }
            elseif ($check_user->is_disqualified === 4) {

                $this->logActivity('Applicant', 'Client', 'Moved to Post/Pre Disbursement Stage', $check_user->name.' moved to Pre/Post Disbursement Stage of Application', $check_user->id);

                return redirect()->route('view.post.index');

            }
            // else {
            // if ($check_user->is_application_complete === 0 && $check_user->application_stage === 'Stage 2'){
            //
            //     $this->logActivity('Applicant', 'Client', 'Continued Phase 2', $check_user->name.' Continued Phase 2 of Application', $check_user->id);
            //
            //     return redirect()->route('section2.view');
            // }
            // }

              $this->logActivity('Applicant', 'Client', 'Continued Phase 1', $check_user->name.' continued Phase 1 of Application', $check_user->id);


// return 'lol';
              return redirect()->route('continue.form');



          }else {

              // $this->logActivity('Applicant', 'Client', 'Started Phase 1', $check_user->getUserDetails->name.' started Phase 1 of Application', $check_user->getUserDetails->id);


              // return 'olo';
          return redirect()->route('companydetails');
          }



//        if ($checkuser->application_status == 'Under Review') {
//          session()->forget(['name','email','phone','check']);
//          return redirect()->route('view.under.review')->with('success','Your Application is under Review, you can only view submitted application');
//        }
//
       // if ($checkuser->application_status == 'Completed Review') {
       //   return redirect()->route('view.post.index');
       // }
//
//        if ($checkuser->application_status == 'Not Started') {
//          return redirect()->route('companydetails');
//        }
//
//
//        session(['check' => 'true']);
//        session()->forget(['name','email','phone']);
//        return redirect()->route('continue.form');
      }


    }else {
      return redirect()->back()->with('error', 'Invalid OTP Entered!');
    }
  }

  public function showcompanydetailsform(){

      // if (Session::get('check')== true) {


      // Custom function to redirect some users to financial page
      if (empty(Session::get('userid'))){
          return redirect()->route('apply');
      }

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

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

      if (!empty($check_user) && $check_user->is_disqualified === false && $check_user->is_application_complete === false && $check_user->application_stage === 'Stage 2'){
          return view('application.financial');
      }


    $id = Session::get('userid');
    $user = UserDetails::where('id',$id)->first();
    // $userinfo = User::where('user_id',$id)->first();

    $business_types = BusinessType::query()->get();
    $data = [
      'userinfo'=>$user,
      'id'=>$id,
      'name'=>$user->name,
      'phone'=>$user->phone,
      'email'=>$user->email,
      'company_name'=>$user->company_name,
        'dob' => $user->dob,
        'business_types' => $business_types,
        // 'form_data' => $form_data
    ];

    return view('application.companydetails_new',$data);
      // }else {
      //   return redirect()->route('apply')->with('error','Please Complete the form below');
      // }

  }

  public function ownership_applicant($id){
    $ownership_applicant =OwnershipApplicant::where('user_id',$id)->get();
    return $ownership_applicant;
  }

  public function key($id){
    $key_management_personnel =KeyManagementPersonnel::where('user_id',$id)->get();
    return $key_management_personnel;
  }

  public function major($id){
    $major_product_line =MajorProductLine::where('user_id',$id)->get();
    return $major_product_line;
  }

  public function request($id){
    $facility_request =FacilityRequest::where('user_id',$id)->get();
    return $facility_request;
  }

  public function non_cash_collaterals_grid($id){
    $non_cash_collaterals =NonCashCollateral::where('user_id',$id)->get();
    return $non_cash_collaterals;
  }

  public function ncash_collaterals_grid($id){
    $cash_collaterals =CashCollateral::where('user_id',$id)->get();
    return $cash_collaterals;
  }

  public function submitform(Request $r){
   $id = Session::get('userid');
   $machineusedlist = json_decode($r->machineusedlist);
   $additionalmachine = json_decode($r->additionalmachine);
   $productionlevels = json_decode($r->productionlevels);
   $directors = json_decode($r->directors);
   $operatingperson = json_decode($r->operatingperson);
   $product_packaging = json_decode($r->product_packaging);
   $credit_history = json_decode($r->credit_history);
   session(['machineusedlist' => $machineusedlist]);
   session(['additionalmachine' => $additionalmachine]);
   session(['productionlevels' => $productionlevels]);
   session(['directors' => $directors]);
   session(['operatingperson' => $operatingperson]);
   session(['product_packaging' => $product_packaging]);
   session(['credit_history' => $credit_history]);
   $grant_amt =$r->input('grant_amt');
   $eco_sector =$r->input('eco_sector');
   $grant_purpose =$r->input('grant_purpose');
   $company_name = $r->input('company_name');
   $year_established = $r->input('year_established');
   $tin_num =$r->input('tin_num');
   $physical_address =$r->input('physical_address');
   $city =$r->input('city');
   $gps =$r->input('gps');
   $contact_p_1 =$r->input('contact_p_1');
   $contact_p_1_num =$r->input('contact_p_1_num');
   $contact_p_2 =$r->input('contact_p_2');
   $contact_p_2_num =$r->input('contact_p_2_num');
   $telephone =$r->input('telephone');
   $comp_email =$r->input('comp_email');
   $website = $r->input('website');
   $business_desc =$r->input('business_desc');
   $location_desc =$r->input('location_desc');
   $struct_desc =$r->input('struct_desc');
   $additional_cost =$r->input('additional_cost');
   $raw_material =$r->input('raw_material');
   $innovative_product =$r->input('innovative_product');
   $promote_product =$r->input('promote_product');
        // $price_policy =$r->input('price_policy');
   $distribute_product =$r->input('distribute_product');
   $major_customers =$r->input('major_customers');
   $off_taker =$r->input('off_taker');
   $major_competitor =$r->input('major_competitor');
   $better_than =$r->input('better_than');
   $business_plan =$r->input('business_plan');
   $vision =$r->input('vision');
   $mission =$r->input('mission');
   $strength =$r->input('strength');
   $weakness =$r->input('weakness');
   $opportunity =$r->input('opportunity');
   $other_business_benefit =$r->input('other_business_benefit');
   $threats =$r->input('threats');
   $sales_past =$r->input('sales_past');
   $sales_current =$r->input('sales_current');
   $sales_year_1 =$r->input('sales_year_1');
   $sales_year_2 =$r->input('sales_year_2');
   $cost_sales_past =$r->input('cost_sales_past');
   $cost_sales_current =$r->input('cost_sales_current');
   $cost_sales_year_1 =$r->input('cost_sales_year_1');
   $cost_sales_year_2 =$r->input('cost_sales_year_2');
   $grossprofit_past =$r->input('grossprofit_past');
   $grossprofit_current =$r->input('grossprofit_current');
   $grossprofit_year_1 =$r->input('grossprofit_year_1');
   $grossprofit_year_2 =$r->input('grossprofit_year_2');
   $sundry_past =$r->input('sundry_past');
   $sundry_current =$r->input('sundry_current');
   $sundry_year_1 =$r->input('sundry_year_1');
   $sundry_year_2 =$r->input('sundry_year_2');
   $selling_past =$r->input('selling_past');
   $selling_current =$r->input('selling_current');
   $selling_year_1 =$r->input('selling_year_1');
   $selling_year_2 =$r->input('selling_year_2');
   $netprofit_past =$r->input('netprofit_past');
   $netprofit_current =$r->input('netprofit_current');
   $netprofit_year_1 =$r->input('netprofit_year_1');
   $netprofit_year_2 =$r->input('netprofit_year_2');
   $breakeven_past =$r->input('breakeven_past');
   $breakeven_current =$r->input('breakeven_current');
   $breakeven_year_1 =$r->input('breakeven_year_1');
   $breakeven_year_2 =$r->input('breakeven_year_2');
   $fixedassets_past =$r->input('fixedassets_past');
   $fixedassets_current =$r->input('fixedassets_current');
   $fixedassets_year_1 =$r->input('fixedassets_year_1');
   $fixedassets_year_2 =$r->input('fixedassets_year_2');
   $currentassets_past =$r->input('currentassets_past');
   $currentassets_current =$r->input('currentassets_current');
   $currentassets_year_1 =$r->input('currentassets_year_1');
   $currentassets_year_2 =$r->input('currentassets_year_2');
   $liability_past =$r->input('liability_past');
   $liability_current =$r->input('liability_current');
   $liability_year_1 =$r->input('liability_year_1');
   $liability_year_2 =$r->input('liability_year_2');
   $capital_past =$r->input('capital_past');
   $capital_current =$r->input('capital_current');
   $capital_year_1 =$r->input('capital_year_1');
   $capital_year_2 =$r->input('capital_year_2');
   $netassets_past =$r->input('netassets_past');
   $netassets_current =$r->input('netassets_current');
   $netassets_year_1 =$r->input('netassets_year_1');
   $netassets_year_2 =$r->input('netassets_year_2');
   $turnover_six_months =$r->input('turnover_six_months');
   $turnover_one_year =$r->input('turnover_one_year');
   $turnover_two_year =$r->input('turnover_two_year');
   $netprofit_six_months =$r->input('netprofit_six_months');
   $netprofit_one_year =$r->input('netprofit_one_year');
   $netprofit_two_year =$r->input('netprofit_two_year');
   $newjobs_six_months =$r->input('newjobs_six_months');
   $newjobs_one_year =$r->input('newjobs_one_year');
   $newjobs_two_year =$r->input('newjobs_two_year');
   $annualpay_six_months =$r->input('annualpay_six_months');
   $annualpay_one_year =$r->input('annualpay_one_year');
   $annualpay_two_year =$r->input('annualpay_two_year');
   $productivity_six_months =$r->input('productivity_six_months');
   $productivity_one_year =$r->input('productivity_one_year');
   $productivity_two_year =$r->input('productivity_two_year');
   $new_jobs =$r->input('new_jobs');
   $impact_safety =$r->input('impact_safety');
   $board =$r->input('board');

   $perma_male =$r->input('perma_male');
   $perma_female =$r->input('perma_female');
   $perma_range =$r->input('perma_range');
   $hired_male =$r->input('hired_male');
   $hired_female =$r->input('hired_female');
   $hired_range =$r->input('hired_range');
   $num_workers =$r->input('num_workers');
   $business_obj =$r->input('business_obj');
   $applied_loan =$r->input('applied_loan');
   $acc_software =$r->input('acc_software');

   $business_assoc =$r->input('business_assoc');
   $women_in_lead =$r->input('women_in_lead');


   $existing_customer = $r->input('existing_customer');
   $exist_acc_name = $r->input('exist_acc_name');
   $exist_acc_num = $r->input('exist_acc_num');
   $exist_acc_branch = $r->input('exist_acc_branch');
   $applied_loan_facility = $r->input('applied_loan_facility');
   $collateral = $r->input('collateral');
   $tenor = $r->input('tenor');


/////////?Financial ratio elements/////////////////
   $curr_asset = $r->input('curr_asset');
   $curr_lia = $r->input('curr_lia') == 0 ? 1 : $r->input('curr_lia');
   $inventory = $r->input('inventory');
   $total_debt = $r->input('total_debt');
   $share_equity = $r->input('share_equity') == 0 ? 1 : $r->input('share_equity');
   $trade_receivables = $r->input('trade_receivables');
   $credit_sales = $r->input('credit_sales') == 0 ? 1 :$r->input('credit_sales');
   $trade_payables = $r->input('trade_payables');
   $credit_purchases = $r->input('credit_purchases') == 0 ? 1 : $r->input('credit_purchases');
   $avg_inventory = $r->input('avg_inventory');
   $cost_sales = $r->input('cost_sales') == 0 ? 1 : $r->input('cost_sales');
   $gross_profit = $r->input('gross_profit');
   $sales_turnover = $r->input('sales_turnover') == 0 ? 1 : $r->input('sales_turnover');
   $net_profit = $r->input('net_profit');
   $sales_turnover_revenue = $r->input('sales_turnover_revenue') == 0 ? 1 :$r->input('sales_turnover_revenue');

        ////////////?Calc financialratio//////////////////
   $current_ratio = $curr_asset/$curr_lia;
   $quick_ratio = ($curr_asset - $inventory)/$curr_lia;
   $gearing_ratio = $total_debt/$share_equity;
   $trade_receivables_days = ($trade_receivables/$credit_sales)*365;
   $payable_days = ($trade_payables/$credit_purchases)*365;
   $inventory_days = ($avg_inventory/$cost_sales)*365 ;
   $cash_conversion = $trade_receivables_days + $inventory_days -   $payable_days;
   $gross_profit_margin = ($gross_profit/$sales_turnover)*100;
   $net_profit_margin = ($net_profit/$sales_turnover_revenue)*100;
        ////////////?Calc financialratio//////////////////

   $checkimage = OperationsModel::where('user_id',$id)->first();
   if ($checkimage !== null) {
    if($r->hasFile('company_regulation')) {
      if ($checkimage->company_regulation != null) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$checkimage->company_regulation);


      }


      $img = $r->file('company_regulation');
      $extension = $img->getClientOriginalExtension();
      if ($extension == 'pdf') {
        $company_regulation_file_name = Str::random(4) . '' . $img->getClientOriginalName();
        $path = "ApplicationImages/";

        $abs_path = storage_path("app/public/$path");
        $img->move($abs_path, $company_regulation_file_name);

        $file_path_to_store = "storage/$path" . $company_regulation_file_name;
        $checkimage->company_regulation=$company_regulation_file_name;
        $checkimage->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Company Regulation!')->withInput();
      }

    }






    if($r->hasFile('building_img')) {
      if ($checkimage->building_img != null) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$checkimage->building_img);
      }


      $img = $r->file('building_img');
      $extension = $img->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp') {
        $building_img_file_name = Str::random(4) . '' . $img->getClientOriginalName();
        $path = "ApplicationImages/";

        $abs_path = storage_path("app/public/$path");
        $img->move($abs_path, $building_img_file_name);

        $file_path_to_store = "storage/$path" . $building_img_file_name;
        $checkimage->building_img=$building_img_file_name;
        $checkimage->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Description of Business Location !')->withInput();
      }

    }

    if($r->hasFile('tax_payment')) {
      if ($checkimage->tax_payment != null) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$checkimage->tax_payment);


      }


      $img = $r->file('tax_payment');
      $extension = $img->getClientOriginalExtension();
      if ($extension == 'pdf') {
        $tax_payment_file_name = Str::random(4) . '' . $img->getClientOriginalName();
        $path = "ApplicationImages/";

        $abs_path = storage_path("app/public/$path");
        $img->move($abs_path, $tax_payment_file_name);

        $file_path_to_store = "storage/$path" . $tax_payment_file_name;
        $checkimage->tax_payment=$tax_payment_file_name;
        $checkimage->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Tax And SSNIT Payment!')->withInput();
      }

    }

    if($r->hasFile('land_detail')) {
      if ($checkimage->land_detail != null) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$checkimage->land_detail);


      }


      $img = $r->file('land_detail');
      $extension = $img->getClientOriginalExtension();
      if ($extension == 'pdf') {
        $land_detail_file_name = Str::random(4) . '' . $img->getClientOriginalName();
        $path = "ApplicationImages/";

        $abs_path = storage_path("app/public/$path");
        $img->move($abs_path, $land_detail_file_name);

        $file_path_to_store = "storage/$path" . $land_detail_file_name;
        $checkimage->land_detail=$land_detail_file_name;
        $checkimage->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Land Title Details!');
      }

    }

    if($r->hasFile('org_chart')) {
      if ($checkimage->org_chart != null) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$checkimage->org_chart);


      }


      $img = $r->file('org_chart');
      $extension = $img->getClientOriginalExtension();
      if ($extension == 'pdf') {
        $org_chart_file_name = Str::random(4) . '' . $img->getClientOriginalName();
        $path = "ApplicationImages/";

        $abs_path = storage_path("app/public/$path");
        $img->move($abs_path, $org_chart_file_name);

        $file_path_to_store = "storage/$path" . $org_chart_file_name;
        $checkimage->org_chart=$org_chart_file_name;
        $checkimage->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Land Title Details!')->withInput();
      }

    }
  }else {
    $checkimage = new OperationsModel();
    if($r->hasFile('company_regulation')) {



      $img = $r->file('company_regulation');
      $extension = $img->getClientOriginalExtension();
      if ($extension == 'pdf') {
        $company_regulation_file_name = $img->getClientOriginalName();
        $path = "ApplicationImages/";

        $abs_path = storage_path("app/public/$path");
        $img->move($abs_path, $company_regulation_file_name);

        $file_path_to_store = "storage/$path" . $company_regulation_file_name;
        $checkimage->company_regulation=$company_regulation_file_name;
        $checkimage->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Company Regulation!')->withInput();
      }
    }



    if($r->hasFile('building_img')) {



      $img = $r->file('building_img');
      $extension = $img->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp') {
        $building_img_file_name = $img->getClientOriginalName();
        $path = "ApplicationImages/";

        $abs_path = storage_path("app/public/$path");
        $img->move($abs_path, $building_img_file_name);

        $file_path_to_store = "storage/$path" . $building_img_file_name;
        $checkimage->building_img=$building_img_file_name;
        $checkimage->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Building Images!')->withInput();
      }
    }

    if($r->hasFile('tax_payment')) {

      $img = $r->file('tax_payment');
      $extension = $img->getClientOriginalExtension();
      if ($extension == 'pdf') {
        $tax_payment_file_name = $img->getClientOriginalName();
        $path = "ApplicationImages/";

        $abs_path = storage_path("app/public/$path");
        $img->move($abs_path, $tax_payment_file_name);

        $file_path_to_store = "storage/$path" . $tax_payment_file_name;
        $checkimage->tax_payment=$tax_payment_file_name;
        $checkimage->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Tax And SSNIT Payment!')->withInput();
      }
    }

    if($r->hasFile('land_detail')) {
      $img = $r->file('land_detail');
      $extension = $img->getClientOriginalExtension();
      if ($extension == 'pdf') {
        $land_detail_file_name = $img->getClientOriginalName();
        $path = "ApplicationImages/";

        $abs_path = storage_path("app/public/$path");
        $img->move($abs_path, $land_detail_file_name);

        $file_path_to_store = "storage/$path" . $land_detail_file_name;
        $checkimage->land_detail=$land_detail_file_name;
        $checkimage->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Land Title Details!')->withInput();
      }
    }

    if($r->hasFile('org_chart')) {



      $img = $r->file('org_chart');
      $extension = $img->getClientOriginalExtension();
      if ($extension == 'pdf') {
        $org_chart_file_name = $img->getClientOriginalName();
        $path = "ApplicationImages/";

        $abs_path = storage_path("app/public/$path");
        $img->move($abs_path, $org_chart_file_name);

        $file_path_to_store = "storage/$path" . $org_chart_file_name;
        $checkimage->org_chart=$org_chart_file_name;
        $checkimage->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Land Title Details!')->withInput();
      }
    }
  }

// //////////////////////
  if($r->hasFile('business_reg')) {
    $checkexist = BusRegs::where('user_id',$id)->get();
    if ($checkexist !== null) {
      foreach ($checkexist as $key) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$key->bus_regs);

        $key->delete();
      }
    }
    foreach($r->file('business_reg') as $file){
      $extension = $file->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp'||$extension == 'pdf') {
        $business_reg_file_name = Str::random(4) . '' . $file->getClientOriginalName();
        $path = "ApplicationImages/";
        $abs_path = storage_path("app/public/$path");
        $file->move($abs_path, $business_reg_file_name);
        $busregs = new BusRegs();
        $file_path_to_store = "storage/$path" . $business_reg_file_name;
        $busregs->user_id=$id;
        $busregs->bus_regs=$business_reg_file_name;
        $busregs->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Business Registeration!')->withInput();
      }
    }
  }

  if($r->hasFile('hist_fin')) {
    $checkexist = HistoricalFinancial::where('user_id',$id)->get();
    if ($checkexist !== null) {
      foreach ($checkexist as $key) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$key->historical_financial);

        $key->delete();
      }
    }
    foreach($r->file('hist_fin') as $file){
      $extension = $file->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp'||$extension == 'pdf') {
        $hist_fin_file_name = Str::random(4) . '' . $file->getClientOriginalName();
        $path = "ApplicationImages/";
        $abs_path = storage_path("app/public/$path");
        $file->move($abs_path, $hist_fin_file_name);
        $busregs = new HistoricalFinancial();
        $file_path_to_store = "storage/$path" . $hist_fin_file_name;
        $busregs->user_id=$id;

        $busregs->historical_financial=$hist_fin_file_name;
        $busregs->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Historical Financial!')->withInput();
      }
    }
  }

  if($r->hasFile('pitchdeck')) {
    $checkexist = Pitchdeck::where('user_id',$id)->get();
    if ($checkexist !== null) {
      foreach ($checkexist as $key) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$key->pitchdeck);

        $key->delete();
      }
    }
    foreach($r->file('pitchdeck') as $file){
      $extension = $file->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp'||$extension == 'pdf') {
        $pitchdeck_file_name = Str::random(4) . '' . $file->getClientOriginalName();
        $path = "ApplicationImages/";
        $abs_path = storage_path("app/public/$path");
        $file->move($abs_path, $pitchdeck_file_name);
        $busregs = new Pitchdeck();
        $file_path_to_store = "storage/$path" . $pitchdeck_file_name;
        $busregs->user_id=$id;

        $busregs->pitchdeck=$pitchdeck_file_name;
        $busregs->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Pitch Deck!')->withInput();
      }
    }
  }

  if($r->hasFile('license')) {
    $checkexist = License::where('user_id',$id)->get();
    if ($checkexist !== null) {
      foreach ($checkexist as $key) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$key->licenses);

        $key->delete();
      }
    }
    foreach($r->file('license') as $file){
      $extension = $file->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp'||$extension == 'pdf') {
        $licenses_file_name = Str::random(4) . '' . $file->getClientOriginalName();
        $path = "ApplicationImages/";
        $abs_path = storage_path("app/public/$path");
        $file->move($abs_path, $licenses_file_name);
        $busregs = new License();
        $file_path_to_store = "storage/$path" . $licenses_file_name;
        $busregs->user_id=$id;

        $busregs->licenses=$licenses_file_name;
        $busregs->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Licences!')->withInput();
      }
    }
  }

  if($r->hasFile('bankmomo')) {
    $checkexist = BankMomo::where('user_id',$id)->get();
    if ($checkexist !== null) {
      foreach ($checkexist as $key) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$key->bank_momo);

        $key->delete();
      }
    }
    foreach($r->file('bankmomo') as $file){
      $extension = $file->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp'||$extension == 'pdf') {
        $bankmomo_file_name = Str::random(4) . '' . $file->getClientOriginalName();
        $path = "ApplicationImages/";
        $abs_path = storage_path("app/public/$path");
        $file->move($abs_path, $bankmomo_file_name);
        $busregs = new BankMomo();
        $file_path_to_store = "storage/$path" . $bankmomo_file_name;
        $busregs->user_id=$id;

        $busregs->bank_momo=$bankmomo_file_name;
        $busregs->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Bank/Momo Statement!')->withInput();
      }
    }
  }


// /////////////////////


//////////////////////New additions fyei//////////////////////////
  if($r->hasFile('request_facility')) {
    $checkexist = RequestFacility::where('user_id',$id)->get();
    if ($checkexist !== null) {
      foreach ($checkexist as $key) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$key->request_facility);

        $key->delete();
      }
    }
    foreach($r->file('request_facility') as $file){
      $extension = $file->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp'||$extension == 'pdf') {
        $request_facility_file_name = Str::random(4) . '' . $file->getClientOriginalName();
        $path = "ApplicationImages/";
        $abs_path = storage_path("app/public/$path");
        $file->move($abs_path, $request_facility_file_name);
        $busregs = new RequestFacility();
        $file_path_to_store = "storage/$path" . $request_facility_file_name;
        $busregs->user_id=$id;
        $busregs->formal_request=$request_facility_file_name;
        $busregs->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For formal request for the facility!')->withInput();
      }
    }
  }

  if($r->hasFile('accepted_offer_letter')) {
    $checkexist = AcceptedOfferLetter::where('user_id',$id)->get();
    if ($checkexist !== null) {
      foreach ($checkexist as $key) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$key->accepted_offer_letter);

        $key->delete();
      }
    }
    foreach($r->file('accepted_offer_letter') as $file){
      $extension = $file->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp'||$extension == 'pdf') {
        $accepted_offer_letter_file_name = Str::random(4) . '' . $file->getClientOriginalName();
        $path = "ApplicationImages/";
        $abs_path = storage_path("app/public/$path");
        $file->move($abs_path, $accepted_offer_letter_file_name);
        $busregs = new AcceptedOfferLetter();
        $file_path_to_store = "storage/$path" . $accepted_offer_letter_file_name;
        $busregs->user_id=$id;
        $busregs->accepted_offer_letter=$accepted_offer_letter_file_name;
        $busregs->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Accepted offer letter!')->withInput();
      }
    }
  }


  if($r->hasFile('upfront_payment')) {
    $checkexist = UpfrontPayment::where('user_id',$id)->get();
    if ($checkexist !== null) {
      foreach ($checkexist as $key) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$key->upfront_payment);

        $key->delete();
      }
    }
    foreach($r->file('upfront_payment') as $file){
      $extension = $file->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp'||$extension == 'pdf') {
        $upfront_payment_file_name = Str::random(4) . '' . $file->getClientOriginalName();
        $path = "ApplicationImages/";
        $abs_path = storage_path("app/public/$path");
        $file->move($abs_path, $upfront_payment_file_name);
        $busregs = new UpfrontPayment();
        $file_path_to_store = "storage/$path" . $upfront_payment_file_name;
        $busregs->user_id=$id;
        $busregs->upfront_payment=$upfront_payment_file_name;
        $busregs->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For Upfront Payment!')->withInput();
      }
    }
  }


  if($r->hasFile('fyep_application')) {
    $checkexist = FyepApplication::where('user_id',$id)->get();
    if ($checkexist !== null) {
      foreach ($checkexist as $key) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$key->fyep_application);

        $key->delete();
      }
    }
    foreach($r->file('fyep_application') as $file){
      $extension = $file->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp'||$extension == 'pdf') {
        $fyep_application_file_name = Str::random(4) . '' . $file->getClientOriginalName();
        $path = "ApplicationImages/";
        $abs_path = storage_path("app/public/$path");
        $file->move($abs_path, $fyep_application_file_name);
        $busregs = new FyepApplication();
        $file_path_to_store = "storage/$path" . $fyep_application_file_name;
        $busregs->user_id=$id;
        $busregs->fyep_application=$fyep_application_file_name;
        $busregs->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For FYEP Application form!')->withInput();
      }
    }
  }




  if($r->hasFile('irrevocable_instruction')) {
    $checkexist = IrrevocableInstruction::where('user_id',$id)->get();
    if ($checkexist !== null) {
      foreach ($checkexist as $key) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$key->irrevocable_instruction);

        $key->delete();
      }
    }
    foreach($r->file('irrevocable_instruction') as $file){
      $extension = $file->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp'||$extension == 'pdf') {
        $irrevocable_instruction_file_name = Str::random(4) . '' . $file->getClientOriginalName();
        $path = "ApplicationImages/";
        $abs_path = storage_path("app/public/$path");
        $file->move($abs_path, $irrevocable_instruction_file_name);
        $busregs = new IrrevocableInstruction();
        $file_path_to_store = "storage/$path" . $irrevocable_instruction_file_name;
        $busregs->user_id=$id;
        $busregs->irrevocable_instruction=$irrevocable_instruction_file_name;
        $busregs->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For FYEP Application form!')->withInput();
      }
    }
  }
  if($r->hasFile('operating_permit')) {
    $checkexist = OperatingPermit::where('user_id',$id)->get();
    if ($checkexist !== null) {
      foreach ($checkexist as $key) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$key->operating_permit);

        $key->delete();
      }
    }
    foreach($r->file('operating_permit') as $file){
      $extension = $file->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp'||$extension == 'pdf') {
        $operating_permit_file_name = Str::random(4) . '' . $file->getClientOriginalName();
        $path = "ApplicationImages/";
        $abs_path = storage_path("app/public/$path");
        $file->move($abs_path, $operating_permit_file_name);
        $busregs = new OperatingPermit();
        $file_path_to_store = "storage/$path" . $operating_permit_file_name;
        $busregs->user_id=$id;
        $busregs->operating_permit=$operating_permit_file_name;
        $busregs->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For FYEP Application form!')->withInput();
      }
    }
  }
  if($r->hasFile('esrm_report')) {
    $checkexist = EsrmReport::where('user_id',$id)->get();
    if ($checkexist !== null) {
      foreach ($checkexist as $key) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$key->esrm_report);

        $key->delete();
      }
    }
    foreach($r->file('esrm_report') as $file){
      $extension = $file->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp'||$extension == 'pdf') {
        $esrm_report_file_name = Str::random(4) . '' . $file->getClientOriginalName();
        $path = "ApplicationImages/";
        $abs_path = storage_path("app/public/$path");
        $file->move($abs_path, $esrm_report_file_name);
        $busregs = new EsrmReport();
        $file_path_to_store = "storage/$path" . $esrm_report_file_name;
        $busregs->user_id=$id;
        $busregs->esrm_report=$esrm_report_file_name;
        $busregs->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For FYEP Application form!')->withInput();
      }
    }
  }
  if($r->hasFile('directional_sketch')) {
    $checkexist = DirectionalSketch::where('user_id',$id)->get();
    if ($checkexist !== null) {
      foreach ($checkexist as $key) {
        $abs_path = public_path("storage/ApplicationImages/");
        File::delete($abs_path.$key->directional_sketch);

        $key->delete();
      }
    }
    foreach($r->file('directional_sketch') as $file){
      $extension = $file->getClientOriginalExtension();
      if ($extension == 'jpg'||$extension == 'jpeg'||$extension == 'png'||$extension == 'webp'||$extension == 'pdf') {
        $directional_sketch_file_name = Str::random(4) . '' . $file->getClientOriginalName();
        $path = "ApplicationImages/";
        $abs_path = storage_path("app/public/$path");
        $file->move($abs_path, $directional_sketch_file_name);
        $busregs = new DirectionalSketch();
        $file_path_to_store = "storage/$path" . $directional_sketch_file_name;
        $busregs->user_id=$id;
        $busregs->directional_sketch=$directional_sketch_file_name;
        $busregs->save();
      }else {
        return redirect()->back()->with('error', 'Invalid file format selected For FYEP Application form!')->withInput();
      }
    }
  }

/////////////////////New additions fyei//////////////////////////

  if ($r->input('saveforlater') !== null) {

          // financialratio
    $savefinancialratio = FinancialRatios::updateOrCreate(['user_id'=>$id],[
      'current_ratio'=>$current_ratio,
      'quick_ratio'=>$quick_ratio,
      'gearing_ratios'=>$gearing_ratio,
      'trade_receivable_days'=>$trade_receivables_days,
      'payable_days'=>$payable_days,
      'inventory_days'=>$inventory_days,
      'cash_conv'=>$cash_conversion,
      'gross_profit_margin'=>$gross_profit_margin,
      'net_profit_margin'=>$net_profit_margin,
      'curr_asset'=>$curr_asset,
      'curr_lia'=>$curr_lia,
      'inventory'=>$inventory,
      'total_debt'=>$total_debt,
      'share_equity'=>$share_equity,
      'trade_receivables'=>$trade_receivables,
      'credit_sales'=>$credit_sales,
      'trade_payables'=>$trade_payables,
      'credit_purchases'=>$credit_purchases,
      'avg_inventory'=>$avg_inventory,
      'cost_sales'=>$cost_sales,
      'gross_profit'=>$gross_profit,
      'sales_turnover'=>$sales_turnover,
      'net_profit'=>$net_profit,
      'sales_turnover_revenue'=>$sales_turnover_revenue,
    ]);

          // save company details
    $savecompanydetails = UserDetails::updateOrCreate(['id'=> $id],[
      'company_name'=>$company_name,
      'year_established'=>$year_established,
      'tin_num'=>$tin_num,
      'physical_address'=>$physical_address,
      'city'=>$city,
      'gps'=>$gps,
      'contact_p_1'=>$contact_p_1,
      'contact_p_1_num'=>$contact_p_1_num,
      'contact_p_2'=>$contact_p_2,
      'contact_p_2_num'=>$contact_p_2_num,
      'website'=>$website,
      'business_desc'=>$business_desc,
      'telephone'=>$telephone,
      'comp_email'=>$comp_email,
      'eco_sector'=> $eco_sector ==null ?'N/A':$eco_sector,
      'grant_purpose'=>$grant_purpose,
      'grant_amt'=>$grant_amt,
      'existing_customer'=> $existing_customer==null ?'N/A':$existing_customer,
      'exist_acc_name'=> $exist_acc_name,
      'exist_acc_num'=> $exist_acc_num,
      'exist_acc_branch'=> $exist_acc_branch,
      'application_status'=> 'Started',
    ]);

    // save operations

    $saveoperations = OperationsModel::updateOrCreate(['user_id'=> $id],[
      'location_desc'=>$location_desc,
      'struct_desc'=>$struct_desc,
      'additional_cost'=>$additional_cost,
      'raw_material'=>$raw_material,
      'innovative_product'=>$innovative_product,
  // 'price_policy'=>$price_policy,
      'promote_product'=>$promote_product,
      'distribute_product'=>$distribute_product,
      'major_customers'=>$major_customers,
      'off_taker'=>$off_taker,
      'major_competitor'=>$major_competitor,
      'better_than'=>$better_than,
      'business_plan'=>$business_plan ==null ?'N/A':$business_plan,
      'vision'=>$vision,
      'mission'=>$mission,
      'strength'=>$strength,
      'weakness'=>$weakness,
      'threats'=>$threats,
      'other_business_benefit'=>$other_business_benefit,
      'new_jobs'=>$new_jobs,
      'impact_safety'=>$impact_safety,
      'perma_male'=>$perma_male,
      'perma_female'=>$perma_female,
      'perma_range'=>$perma_range,
      'hired_male'=>$hired_male,
      'hired_female'=>$hired_female,
      'hired_range'=>$hired_range,
      'board'=>$board,
      'num_workers'=>$num_workers,
      'business_obj'=>$business_obj,
      'applied_loan'=>$applied_loan==null ?'N/A':$applied_loan,
      'applied_loan_facility'=>$applied_loan_facility,
      'acc_software'=>$acc_software,
      'opportunity'=>$opportunity,
      'business_assoc'=>$business_assoc,
      'women_in_lead'=>$women_in_lead,
      'collateral'=>$collateral,
      'tenor'=>$tenor,
    ]);

    // save finnancial performnce

    $savefinancial = FinancialPerformanceModel::updateOrCreate(['user_id'=> $id],[
      'sales_past'=>$sales_past,
      'sales_current'=>$sales_current,
      'sales_year_1'=>$sales_year_1,
      'sales_year_2'=>$sales_year_2,
      'grossprofit_past'=>$grossprofit_past,
      'grossprofit_current'=>$grossprofit_current,
      'grossprofit_year_1'=>$grossprofit_year_1,
      'grossprofit_year_2'=>$grossprofit_year_2,
      'cost_sales_past'=>$cost_sales_past,
      'cost_sales_current'=>$cost_sales_current,
      'cost_sales_year_1'=>$cost_sales_year_1,
      'cost_sales_year_2'=>$cost_sales_year_2,
      'sundry_past'=>$sundry_past,
      'sundry_current'=>$sundry_current,
      'sundry_year_1'=>$sundry_year_1,
      'sundry_year_2'=>$sundry_year_2,
      'selling_past'=>$selling_past,
      'selling_current'=>$selling_current,
      'selling_year_1'=>$selling_year_1,
      'selling_year_2'=>$selling_year_2,
      'netprofit_past'=>$netprofit_past,
      'netprofit_current'=>$netprofit_current,
      'netprofit_year_1'=>$netprofit_year_1,
      'netprofit_year_2'=>$netprofit_year_2,
      'breakeven_past'=>$breakeven_past,
      'breakeven_current'=>$breakeven_current,
      'breakeven_year_1'=>$breakeven_year_1,
      'breakeven_year_2'=>$breakeven_year_2,
      'fixedassets_past'=>$fixedassets_past,
      'fixedassets_current'=>$fixedassets_current,
      'fixedassets_year_1'=>$fixedassets_year_1,
      'fixedassets_year_2'=>$fixedassets_year_2,
      'currentassets_past'=>$currentassets_past,
      'currentassets_current'=>$currentassets_current,
      'currentassets_year_1'=>$currentassets_year_1,
      'currentassets_year_2'=>$currentassets_year_2,
      'liability_past'=>$liability_past,
      'liability_current'=>$liability_current,
      'liability_year_1'=>$liability_year_1,
      'liability_year_2'=>$liability_year_2,
      'capital_past'=>$capital_past,
      'capital_current'=>$capital_current,
      'capital_year_1'=>$capital_year_1,
      'capital_year_2'=>$capital_year_2,
      'netassets_past'=>$netassets_past,
      'netassets_current'=>$netassets_current,
      'netassets_year_1'=>$netassets_year_1,
      'netassets_year_2'=>$netassets_year_2,
    ]);

    // save kpi
    $savekpi = KpiModel::updateOrCreate(['user_id'=> $id],[
      'turnover_six_months'=>$turnover_six_months,
      'turnover_one_year'=>$turnover_one_year,
      'turnover_two_year'=>$turnover_two_year,
      'netprofit_six_months'=>$netprofit_six_months,
      'netprofit_one_year'=>$netprofit_one_year,
      'netprofit_two_year'=>$netprofit_two_year,
      'newjobs_six_months'=>$newjobs_six_months,
      'newjobs_one_year'=>$newjobs_one_year,
      'newjobs_two_year'=>$newjobs_two_year,
      'annualpay_six_months'=>$annualpay_six_months,
      'annualpay_one_year'=>$annualpay_one_year,
      'annualpay_two_year'=>$annualpay_two_year,
      'productivity_six_months'=>$productivity_six_months,
      'productivity_one_year'=>$productivity_one_year,
      'productivity_two_year'=>$productivity_two_year,
    ]);

    //machine used
    $getmachineused = MachineUsedModel::where('user_id',$id)->delete();
    if ($machineusedlist !==null) {
      foreach ($machineusedlist as $key) {
        $savemachineusedlist = MachineUsedModel::create([
          'user_id'=>$id,
          'item_desc'=>$key->item_desc,
          'qty'=>$key->qty,
          'age'=>$key->age,
          'present_condition'=>$key->present_condition,
        ]);
      }
    }else {
      $rr = new MachineUsedModel();
      $rr->user_id=$id;
      $rr->save();
    }


//additionalmachine
    $getadditionalmachine = AddtionalMachineModel::where('user_id',$id)->delete();
    if ($additionalmachine !==null) {
      foreach ($additionalmachine as $adm) {
        $saveadditionalmachine = AddtionalMachineModel::create([
          'user_id'=>$id,
          'item_desc'=>$adm->item_desc,
          'qty'=>$adm->qty,
          'supplier'=>$adm->supplier,
          'estimated_cost'=>$adm->estimated_cost,
        ]);
      }
    }else {
      $rr = new AddtionalMachineModel();
      $rr->user_id=$id;
      $rr->save();
    }



// productionlevels
    $getproductionlevels = ProductionLevelsModel::where('user_id',$id)->delete();
    if ($productionlevels !==null) {
      foreach ($productionlevels as $pl) {
        $saveproductionlevels = ProductionLevelsModel::create([
          'user_id'=>$id,
          'product'=>$pl->product,
          'annual_capacity'=>$pl->annual_capacity,
          'past'=>$pl->past,
          'current'=>$pl->current,
          'year_1'=>$pl->year_1,
          'year_2'=>$pl->year_2,
        ]);
      }
    }else {
      $rr = new ProductionLevelsModel();
      $rr->user_id=$id;
      $rr->save();
    }


// directors
// $getdirectors = DirectorsModel::where('user_id',$id)->delete();
// foreach ($directors as $dir) {
//   $savedirectors = DirectorsModel::create([
//     'user_id'=>$id,
//     'name'=>$dir->name,
//     'academic_qua'=>$dir->academic_qua,
//     'working_exp'=>$dir->working_exp,
//     'years_as_board'=>$dir->years_as_board,
//   ]);
// }

// operatingperson
    $getoperatingperson = OperatingPersonnelModel::where('user_id',$id)->delete();
    if ($operatingperson!==null) {
      foreach ($operatingperson as $op) {
        $saveoperatingperson = OperatingPersonnelModel::create([
          'user_id'=>$id,
          'name'=>$op->name,
          'academic_qua'=>$op->academic_qua,
          'working_exp'=>$op->working_exp,
          'years_with_company'=>$op->years_with_company,
        ]);
      }
    }else {
      $rr = new OperatingPersonnelModel();
      $rr->user_id=$id;
      $rr->save();
    }


// product_packaging
    $getproduct_packaging = ProductPackagingModel::where('user_id',$id)->delete();
    if ($product_packaging !== null) {
      foreach ($product_packaging as $pp) {
        $saveproduct_packaging = ProductPackagingModel::create([
          'user_id'=>$id,
          'product'=>$pp->product,
          'packaging'=>$pp->packaging,
        ]);
      }
    }else {
      $rr = new ProductPackagingModel();
      $rr->user_id=$id;
      $rr->save();
    }


// credit_history
    $getcredit_history = CreditHistoryModel::where('user_id',$id)->delete();
    if ($credit_history !== null) {
      foreach ($credit_history as $ch) {
        $savecredit_history = CreditHistoryModel::create([
          'user_id'=>$id,
          'bank'=>$ch->bank,
          'loan_date'=>$ch->loan_date,
          'amt'=>$ch->amt,
          'payment_history'=>$ch->payment_history,
        ]);
      }
    }else {
      $rr = new CreditHistoryModel();
      $rr->user_id=$id;
      $rr->save();
    }


    return redirect()->route('continue.form')->with('success','Form Saved For Later');
  }elseif ($r->input('complete') !== null) {


    if ($r->filled('company_name') && $r->filled('year_established') &&$r->filled('tin_num') &&
      $r->filled('physical_address') &&$r->filled('city') &&$r->filled('gps') &&$r->filled('contact_p_1') &&$r->filled('contact_p_1_num') &&$r->filled('contact_p_2') &&$r->filled('contact_p_2_num')  &&
      $r->filled('business_desc') &&$r->filled('telephone') &&$r->filled('comp_email') &&$r->filled('eco_sector') &&$r->filled('grant_purpose') &&$r->filled('grant_amt')) {


  // financialratio
      $savefinancialratio = FinancialRatios::updateOrCreate(['user_id'=>$id],[
        'current_ratio'=>$current_ratio,
        'quick_ratio'=>$quick_ratio,
        'gearing_ratios'=>$gearing_ratio,
        'trade_receivable_days'=>$trade_receivables_days,
        'payable_days'=>$payable_days,
        'inventory_days'=>$inventory_days,
        'cash_conv'=>$cash_conversion,
        'gross_profit_margin'=>$gross_profit_margin,
        'net_profit_margin'=>$net_profit_margin,
        'curr_asset'=>$curr_asset,
        'curr_lia'=>$curr_lia,
        'inventory'=>$inventory,
        'total_debt'=>$total_debt,
        'share_equity'=>$share_equity,
        'trade_receivables'=>$trade_receivables,
        'credit_sales'=>$credit_sales,
        'trade_payables'=>$trade_payables,
        'credit_purchases'=>$credit_purchases,
        'avg_inventory'=>$avg_inventory,
        'cost_sales'=>$cost_sales,
        'gross_profit'=>$gross_profit,
        'sales_turnover'=>$sales_turnover,
        'net_profit'=>$net_profit,
        'sales_turnover_revenue'=>$sales_turnover_revenue,
      ]);

  // save company details
    $savecompanydetails = UserDetails::updateOrCreate(['id'=> $id],[
      'company_name'=>$company_name,
      'year_established'=>$year_established,
      'tin_num'=>$tin_num,
      'physical_address'=>$physical_address,
      'city'=>$city,
      'gps'=>$gps,
      'contact_p_1'=>$contact_p_1,
      'contact_p_1_num'=>$contact_p_1_num,
      'contact_p_2'=>$contact_p_2,
      'contact_p_2_num'=>$contact_p_2_num,
      'website'=>$website,
      'business_desc'=>$business_desc,
      'telephone'=>$telephone,
      'comp_email'=>$comp_email,
      'eco_sector'=>$eco_sector,
      'grant_purpose'=>$grant_purpose,
      'grant_amt'=>$grant_amt,
      'existing_customer'=>$existing_customer==null ?'N/A':$existing_customer,
      'exist_acc_name'=>$exist_acc_name,
      'exist_acc_num'=>$exist_acc_num,
      'exist_acc_branch'=>$exist_acc_branch,
      'application_status'=>'Completed',
    ]);

  // save operations
    $saveoperations = OperationsModel::updateOrCreate(['user_id'=> $id],[
      'location_desc'=>$location_desc,
      'struct_desc'=>$struct_desc,
      'additional_cost'=>$additional_cost,
      'raw_material'=>$raw_material,
      'innovative_product'=>$innovative_product,
// 'price_policy'=>$price_policy,
      'promote_product'=>$promote_product,
      'distribute_product'=>$distribute_product,
      'major_customers'=>$major_customers,
      'off_taker'=>$off_taker,
      'major_competitor'=>$major_competitor,
      'better_than'=>$better_than,
      'business_plan'=>$business_plan == null ?'N/A':$business_plan,
      'vision'=>$vision,
      'mission'=>$mission,
      'strength'=>$strength,
      'weakness'=>$weakness,
      'threats'=>$threats,
      'other_business_benefit'=>$other_business_benefit,
      'new_jobs'=>$new_jobs,
      'impact_safety'=>$impact_safety,
      'perma_male'=>$perma_male,
      'perma_female'=>$perma_female,
      'perma_range'=>$perma_range,
      'hired_male'=>$hired_male,
      'hired_female'=>$hired_female,
      'hired_range'=>$hired_range,
// 'company_regulation'=>$company_regulation_file_name,
// 'land_detail'=>$land_detail_file_name,
// 'tax_payment'=>$tax_payment_file_name,
// 'org_chart'=>$org_chart_file_name,
      'board'=>$board,
      'num_workers'=>$num_workers,
      'business_obj'=>$business_obj,
      'applied_loan'=>$applied_loan==null ?'N/A':$applied_loan,
      'applied_loan_facility'=>$applied_loan_facility,'acc_software'=>$acc_software,
      'opportunity'=>$opportunity,
      'business_assoc'=>$business_assoc,
      'women_in_lead'=>$women_in_lead,
      'collateral'=>$collateral,
      'tenor'=>$tenor,
    ]);

// save finnancial performnce
    $savefinancial = FinancialPerformanceModel::updateOrCreate(['user_id'=> $id],[
      'sales_past'=>$sales_past,
      'sales_current'=>$sales_current,
      'sales_year_1'=>$sales_year_1,
      'sales_year_2'=>$sales_year_2,
      'grossprofit_past'=>$grossprofit_past,
      'grossprofit_current'=>$grossprofit_current,
      'grossprofit_year_1'=>$grossprofit_year_1,
      'grossprofit_year_2'=>$grossprofit_year_2,
      'cost_sales_past'=>$cost_sales_past,
      'cost_sales_current'=>$cost_sales_current,
      'cost_sales_year_1'=>$cost_sales_year_1,
      'cost_sales_year_2'=>$cost_sales_year_2,
      'sundry_past'=>$sundry_past,
      'sundry_current'=>$sundry_current,
      'sundry_year_1'=>$sundry_year_1,
      'sundry_year_2'=>$sundry_year_2,
      'selling_past'=>$selling_past,
      'selling_current'=>$selling_current,
      'selling_year_1'=>$selling_year_1,
      'selling_year_2'=>$selling_year_2,
      'netprofit_past'=>$netprofit_past,
      'netprofit_current'=>$netprofit_current,
      'netprofit_year_1'=>$netprofit_year_1,
      'netprofit_year_2'=>$netprofit_year_2,
      'breakeven_past'=>$breakeven_past,
      'breakeven_current'=>$breakeven_current,
      'breakeven_year_1'=>$breakeven_year_1,
      'breakeven_year_2'=>$breakeven_year_2,
      'fixedassets_past'=>$fixedassets_past,
      'fixedassets_current'=>$fixedassets_current,
      'fixedassets_year_1'=>$fixedassets_year_1,
      'fixedassets_year_2'=>$fixedassets_year_2,
      'currentassets_past'=>$currentassets_past,
      'currentassets_current'=>$currentassets_current,
      'currentassets_year_1'=>$currentassets_year_1,
      'currentassets_year_2'=>$currentassets_year_2,
      'liability_past'=>$liability_past,
      'liability_current'=>$liability_current,
      'liability_year_1'=>$liability_year_1,
      'liability_year_2'=>$liability_year_2,
      'capital_past'=>$capital_past,
      'capital_current'=>$capital_current,
      'capital_year_1'=>$capital_year_1,
      'capital_year_2'=>$capital_year_2,
      'netassets_past'=>$netassets_past,
      'netassets_current'=>$netassets_current,
      'netassets_year_1'=>$netassets_year_1,
      'netassets_year_2'=>$netassets_year_2,
    ]);

// save kpi
    $savekpi = KpiModel::updateOrCreate(['user_id'=> $id],[
      'turnover_six_months'=>$turnover_six_months,
      'turnover_one_year'=>$turnover_one_year,
      'turnover_two_year'=>$turnover_two_year,
      'netprofit_six_months'=>$netprofit_six_months,
      'netprofit_one_year'=>$netprofit_one_year,
      'netprofit_two_year'=>$netprofit_two_year,
      'newjobs_six_months'=>$newjobs_six_months,
      'newjobs_one_year'=>$newjobs_one_year,
      'newjobs_two_year'=>$newjobs_two_year,
      'annualpay_six_months'=>$annualpay_six_months,
      'annualpay_one_year'=>$annualpay_one_year,
      'annualpay_two_year'=>$annualpay_two_year,
      'productivity_six_months'=>$productivity_six_months,
      'productivity_one_year'=>$productivity_one_year,
      'productivity_two_year'=>$productivity_two_year,
    ]);
//machine used
    $getmachineused = MachineUsedModel::where('user_id',$id)->delete();
    if ($machineusedlist !==null) {
      foreach ($machineusedlist as $key) {
        $savemachineusedlist = MachineUsedModel::create([
          'user_id'=>$id,
          'item_desc'=>$key->item_desc,
          'qty'=>$key->qty,
          'age'=>$key->age,
          'present_condition'=>$key->present_condition,
        ]);
      }
    }else {
      $rr = new MachineUsedModel();
      $rr->user_id=$id;
      $rr->save();
    }


//additionalmachine
    $getadditionalmachine = AddtionalMachineModel::where('user_id',$id)->delete();
    if ($additionalmachine !==null) {
      foreach ($additionalmachine as $adm) {
        $saveadditionalmachine = AddtionalMachineModel::create([
          'user_id'=>$id,
          'item_desc'=>$adm->item_desc,
          'qty'=>$adm->qty,
          'supplier'=>$adm->supplier,
          'estimated_cost'=>$adm->estimated_cost,
        ]);
      }
    }else {
      $rr = new AddtionalMachineModel();
      $rr->user_id=$id;
      $rr->save();
    }



// productionlevels
    $getproductionlevels = ProductionLevelsModel::where('user_id',$id)->delete();
    if ($productionlevels !==null) {
      foreach ($productionlevels as $pl) {
        $saveproductionlevels = ProductionLevelsModel::create([
          'user_id'=>$id,
          'product'=>$pl->product,
          'annual_capacity'=>$pl->annual_capacity,
          'past'=>$pl->past,
          'current'=>$pl->current,
          'year_1'=>$pl->year_1,
          'year_2'=>$pl->year_2,
        ]);
      }
    }else {
      $rr = new ProductionLevelsModel();
      $rr->user_id=$id;
      $rr->save();
    }


// directors
// $getdirectors = DirectorsModel::where('user_id',$id)->delete();
// foreach ($directors as $dir) {
//   $savedirectors = DirectorsModel::create([
//     'user_id'=>$id,
//     'name'=>$dir->name,
//     'academic_qua'=>$dir->academic_qua,
//     'working_exp'=>$dir->working_exp,
//     'years_as_board'=>$dir->years_as_board,
//   ]);
// }

// operatingperson
    $getoperatingperson = OperatingPersonnelModel::where('user_id',$id)->delete();
    if ($operatingperson!==null) {
      foreach ($operatingperson as $op) {
        $saveoperatingperson = OperatingPersonnelModel::create([
          'user_id'=>$id,
          'name'=>$op->name,
          'academic_qua'=>$op->academic_qua,
          'working_exp'=>$op->working_exp,
          'years_with_company'=>$op->years_with_company,
        ]);
      }
    }else {
      $rr = new OperatingPersonnelModel();
      $rr->user_id=$id;
      $rr->save();
    }


// product_packaging
    $getproduct_packaging = ProductPackagingModel::where('user_id',$id)->delete();
    if ($product_packaging !== null) {
      foreach ($product_packaging as $pp) {
        $saveproduct_packaging = ProductPackagingModel::create([
          'user_id'=>$id,
          'product'=>$pp->product,
          'packaging'=>$pp->packaging,
        ]);
      }
    }else {
      $rr = new ProductPackagingModel();
      $rr->user_id=$id;
      $rr->save();
    }


// credit_history
    $getcredit_history = CreditHistoryModel::where('user_id',$id)->delete();
    if ($credit_history !== null) {
      foreach ($credit_history as $ch) {
        $savecredit_history = CreditHistoryModel::create([
          'user_id'=>$id,
          'bank'=>$ch->bank,
          'loan_date'=>$ch->loan_date,
          'amt'=>$ch->amt,
          'payment_history'=>$ch->payment_history,
        ]);
      }
    }else {
      $rr = new CreditHistoryModel();
      $rr->user_id=$id;
      $rr->save();
    }

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

    ];

     Mail::to($user->email)->send(new ApplicationCompletedMail($data));
    return redirect()->route('completed.form');
  }else {
    return redirect()->back()->with('error','Application Incomplete. Kindly use the "Save For Later Button" to save your current progress')->withInput();
  }
}


}






public function completedform(){
  session()->flush();
  return view('application.completed');
}


}