<?php

namespace App\Http\Controllers\Administrator;
use App\Classes\Reschedule;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Support\Facades\Crypt;
use App\LoanProcessModel;
use App\ApproveInstalmentModel;
use App\ApproveInstalmentStepModel;
use App\Helpers\LogActivity;
use App\LoanModel;
use App\SaleStockModel;
use App\ClientModel;
use App\ProvinceModel;
use App\DiscountModel;
use App\ClientRelationshipModel;
use App\User;

class RescheduleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct(){
        $this->middleware('permission:Client-Payment-Reschedule',['only'=>['create','store']]);
    }
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($loan_id=null, $sale_id=null)
    {
        $loan_id  = Crypt::decrypt($loan_id);

        $sale_decrypt_id    = Crypt::decrypt($sale_id);

        $client_decrypt_id = LoanModel::find($loan_id)->loan_clientid;

        $data['client_id']     = $client_decrypt_id;

        $data['sale_id']    = $sale_decrypt_id;

        $data['loan_id'] = $loan_id;

        $client = ClientModel::find($client_decrypt_id);

        $provinces = ProvinceModel::select(
            DB::raw('CONCAT(province_id," ",province_en," ",province_km) AS province_mixed'),
            'province_id'
        )
            ->pluck('province_mixed', 'province_id')
            ->prepend('Please Select', '');//don't use anymore.but can't delete

        $data['data'] = DB::select("SELECT nso007_sale_policy_payment.payment_policy_id,nso007_sale_policy_payment.policy_detail_id,nso007_loan.loan_discount as sale_discount,nso007_loan.loan_amountos as sale_amount,nso007_sale_stock.sale_receive,nso007_loan.loan_agentid as agency_id,nso007_loan.loan_close_saleid as close_sale_id FROM nso007_loan INNER JOIN nso007_sale_stock ON nso007_loan.loan_saleid = nso007_sale_stock.id INNER JOIN nso007_sale_policy_payment ON nso007_sale_policy_payment.sale_id = nso007_sale_stock.id WHERE nso007_loan.id = $loan_id");

        $data['client_name'] = ClientModel::where('id', $client_decrypt_id)->select(DB::raw('concat(client_firstname," ",client_lastname) As client_fullname'))->first();

        $discount = DiscountModel::pluck('name', 'id')->prepend('Select Discount', '');//don't use anymore.but can't delete

        $relationship   = ClientRelationshipModel::select('id', DB::raw('CONCAT(clientship_phone1, " | ", clientship_fullname) AS clientship_fullname'))->pluck('clientship_fullname', 'id')->prepend('Please Select', '');//don't use anymore.but can't delete

        $parent_id = User::select(DB::Raw('GROUP_CONCAT(id) as ids'))->where([['role', 'Agencies'], ['parent_id', 0]])->first()->ids;//don't use anymore.but can't delete

        $agencyLV2 = User::select(DB::raw('GROUP_CONCAT(id) as ids'))->whereIn('parent_id', explode(',', $parent_id))->first()->ids;//don't use anymore.but can't delete

        $agency         = User::select('id', DB::raw('CONCAT(user_firstname, " ", user_lastname) AS agency_name'))
            ->where([['user_status', 2]])
            ->where(function ($query) use ($agencyLV2) {
                $query->orwhereIn('parent_id', explode(',', $agencyLV2));
                $query->orwhere('agency_type', 1);
            })
            ->pluck('agency_name', 'id')
            ->prepend('Please Select', '');//don't use anymore.but can't delete
            
        $closesale = User::where('role', 'Agencies')
            ->select(DB::raw('CONCAT(user_firstname," ",user_lastname) As closesale'), 'id')
            ->pluck('closesale', 'id')->prepend('Select Close Sale', '');//don't use anymore.but can't delete

        if(empty($data['data'])) return \back()->with("danger","your request is fail !");

        $payment_policies = DB::table('nso007_payment_policy')->pluck("name","id")->prepend("Please Select","");

        $sale_policy_payment = DB::table('nso007_sale_policy_payment')->where("sale_id",$sale_decrypt_id)->first();
        if(!empty($sale_policy_payment)){
            $payment_policy_detail = DB::table('nso007_payment_policy_detail')->where('policy_id',$sale_policy_payment->payment_policy_id)->pluck('name','id');
        }
        else{
            $payment_policy_detail = [];
        }

        return view('administrator.reschedule.create', compact('data', 'discount', 'client', 'provinces', 'agency','closesale'), ['relationship' => $relationship,'payment_policies'=>$payment_policies,'sale_policy_payment'=>$sale_policy_payment,'payment_policy_detail'=>$payment_policy_detail]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'loan_id'=>'required'
        ]);

        if((!empty($request->itempro_payamount[0])&&$request->itempro_payamount[0]>0) || (!empty($request->loan_amount)&& $request->loan_amount>0&&$request->first_loan_condition==1&&isset($request->loan_interest)&&$request->loan_interest>=0) || ($request->change_rate_condition==1&&!empty($request->loan_amount_second)&&$request->loan_amount_second>0&&!empty($request->loan_duration_second)&&$request->loan_duration_second>0&&isset($request->loan_interest_second)&&$request->loan_interest_second>=0)){
            if(empty($request->itempro_payamount[0])){
//            $this->validate($request,[
//                'loan_duration' => 'required',
//                'loan_interest' => 'required',
//                'loan_type'     => 'required'
//            ]);
            }
            $depositAmount      = DB::table('nso007_sale_stock as sale')->join('nso007_deposit as deposit','deposit.deposit_saleid','sale.id')
                ->select(DB::raw('SUM(deposit.deposit_amount) as deposit_amount'))
                ->where('sale.id',LoanModel::find($request->loan_id)->loan_saleid)->first()->deposit_amount;

            $installmentAmount  = $request->item_cost_remain;
            $loantype           = $request->loan_type;
            $loanID             = $request->loan_id;
            $loanDuration       = $request->loan_duration;
            $loanInterest       = $request->loan_interest;
            $LoanNo             = 1;
            $incrementPrincipal = $depositAmount+LoanModel::find($request->loan_id)->loan_discount;
            $incrementInterest  = 0;
            $startDate          = date('Y-m-d',strtotime($request->loan_firstpaydate));
            $decrementPrincipal = $installmentAmount;
            $pmStep             = $request->itempro_payamount;
            $pmDate             = $request->itempro_date;

            LoanProcessModel::where('loanprocess_loanid',$loanID)->whereNull('loanprocess_paid')->delete();
            $loanProcessPaidLast = LoanProcessModel::where('loanprocess_loanid',$loanID)->orderBy('id','desc')->first();

            if(!empty($loanProcessPaidLast)){
                $LoanNo             = $loanProcessPaidLast->loanprocess_no+1;
                $incrementPrincipal = $loanProcessPaidLast->loanprocess_accprinciple;
                $incrementInterest  = $loanProcessPaidLast->loanprocess_accinterest;
            }
            
            //Payment Step
            if(!empty($request->itempro_payamount[0])&&$request->itempro_payamount[0]>0){
                foreach($pmStep as $j => $pm){
                    $installmentAmount  -= $pm;
                    $decrementPrincipal -= $pm;
                    $incrementPrincipal += $pm;
                    $incrementInterest  += 0;
                    LoanProcessModel::insert([
                        'loanprocess_loanid'        => $loanID,
                        'loanprocess_no'            => $LoanNo,
                        'loanprocess_datepayment'   => date('Y-m-d', strtotime($pmDate[$j])),
                        'loanprocess_interest'      => 0,
                        'loanprocess_interestpay'   => 0,
                        'loanprocess_principle'     => $pm,
                        'loanprocess_principlepay'  => $pm,
                        'loanprocess_principleos'   => $decrementPrincipal,
                        'loanprocess_accprinciple'  => $incrementPrincipal,
                        'loanprocess_accinterest'   => $incrementInterest,
                        'loanprocess_amountpaid'    => $incrementPrincipal,
                        'loanprocess_amountcredit'  => $decrementPrincipal,
                        'loanprocess_owe'           => $pm,
                        'loanprocess_owepay'        => $pm,
                        'loanprocess_status'        => 2,
                    ]);
                    $LoanNo++;
                }
            }

            //End
            //Loan Generate
            if(!empty($request->loan_amount)&& $request->loan_amount>0&&$request->first_loan_condition==1&&isset($request->loan_interest)&&$request->loan_interest>=0){
                $return_data = $this->LoanprocessGenerator($loanID,$request->loan_amount,$loantype,$loanDuration,$loanInterest,$startDate,$LoanNo,$incrementInterest,$incrementPrincipal,$decrementPrincipal);
                $LoanNo = $return_data['no'];
                $decrementPrincipal = $return_data['decrementPrincipal'];
                $incrementPrincipal = $return_data['incrementPrincipal'];
                $incrementInterest = $return_data['incrementInterest'];
            }
            //End
            
            //Loan Change Rate
            if($request->change_rate_condition==1&&!empty($request->loan_amount_second)&&$request->loan_amount_second>0&&!empty($request->loan_duration_second)&&$request->loan_duration_second>0&&isset($request->loan_interest_second)&&$request->loan_interest_second>=0){
                // if(isset($request->change_rate_from[0])&&isset($request->change_rate_to[0])&&isset($request->rate_condition[0])){
                $remainingBalance = $request->loan_amount_second;
                // dd($remainingBalance);
                $startDate = $request->loan_firstpaydate_second;
                // $decrementPrincipal = $remainingBalance;
                $rate_change=0;
                if ($request->loan_type_second == 2 || ($request->loan_type_second == 1 && $request->change_rate_to[0] <= 0)) {
                    // dd("1");
                    $principal=$remainingBalance / $request->loan_duration_second;
                    $rate = $request->loan_interest_second / 100;
                    $rate_change=$rate;

                    for ($i = 1; $i <= $request->loan_duration_second; $i++) {
                        $month_from_r = 0;$month_to_r=0;
                        $interest = $rate * $remainingBalance;
                        $rate_change=$rate;
                        if(!empty($request->change_rate_from)){
                            foreach ($request->change_rate_from as $key => $value) {
                                if($value<=$i&&$request->change_rate_to[$key]>=$i){
                                    $interest = $remainingBalance*$request->rate_condition[$key]/100;
                                    $rate_change = $request->rate_condition[$key];
                                    $month_from_r = $value;$month_to_r=$request->change_rate_to[$key];
                                }
                            }
                        }

                        $remainingBalance   -= $principal;
                        $payment            = $interest + $principal;
                        $incrementPrincipal += $principal;
                        $incrementInterest  += $interest;
                        $decrementPrincipal -= $principal;
                        LoanProcessModel::insert([
                            'loanprocess_loanid'        => $loanID,
                            'loanprocess_no'            => $LoanNo,
                            'loanprocess_datepayment'   => date("Y-m-d",strtotime($startDate)),
                            'loanprocess_interest'      => $interest,
                            'loanprocess_interestpay'   => $interest,
                            'loanprocess_principle'     => $principal,
                            'loanprocess_principlepay'  => $principal,
                            'loanprocess_principleos'   => $decrementPrincipal,
                            'loanprocess_accprinciple'  => $incrementPrincipal,
                            'loanprocess_accinterest'   => $incrementInterest,
                            'loanprocess_amountpaid'    => $incrementPrincipal,
                            'loanprocess_amountcredit'  => $decrementPrincipal,
                            'loanprocess_owe'           => $payment,
                            'loanprocess_owepay'        => $payment,
                            'loanprocess_status'        => 4,
                            'note_type'                 => 1,
                            'rate_for_change'           => $rate_change,
                            'rate_change_month_from'    => $month_from_r,
                            'rate_change_month_to'      => $month_to_r
                        ]);
                        $LoanNo++;
                        $startDate = $this->Loan_date_generator($startDate);
                    }

                } else {
                    // dd("2");
                    // $rate = $request->loan_interest_second/ 100;
                    $rate = $request->rate_condition[0] / 100;
                    $loanDuration = $request->loan_duration_second;
                    $remainingBalance = $request->loan_amount_second;
                    if($request->change_rate_to[0]>0){
                        $payment = ($remainingBalance * $rate) / (1 - (pow((1 + $rate), -$loanDuration)));
                    }
                    else{
                        $payment = ($remainingBalance * $rate) / (1 - (pow((1 + $rate), -$loanDuration)));
                    }
                    
                    $index_count_month = 0;
                    
                    $check_change_rate = $rate;
                    $rate_cp = $rate;
                    
                    for ($i = 1; $i <= $loanDuration; $i++) {
                        $month_from_r = 0;$month_to_r=0;
                        $start = $i + 1;
                        $check_change_rate = $rate;
                        if(!empty($request->change_rate_from)){
                            foreach ($request->change_rate_from as $key => $value) {
                                if($value<=$i&&$request->change_rate_to[$key]>=$i){
                                    $check_change_rate =  $request->rate_condition[$key]/100;
                                    $month_from_r =  $value;$month_to_r=$request->change_rate_to[$key];
                                }
                            }
                        }

                        if($rate_cp!=$check_change_rate){
                            $rate_cp = $check_change_rate;
                            $payment = ($remainingBalance * $check_change_rate) / (1 - (pow((1 + $check_change_rate), -($loanDuration-$index_count_month))));
                        }
                        $index_count_month++;
                        $interest           = $remainingBalance * $check_change_rate;
                        $principal              = $payment - $interest;
                        $remainingBalance   -= $principal;
                        $incrementInterest     += $interest;
                        $incrementPrincipal    += $principal;
                        $decrementPrincipal    -= $principal;
                        LoanProcessModel::insert([
                            'loanprocess_loanid'        => $loanID,
                            'loanprocess_no'            => $LoanNo,
                            'loanprocess_datepayment'   => date("Y-m-d",strtotime($startDate)),
                            'loanprocess_interest'      => $interest,
                            'loanprocess_interestpay'   => $interest,
                            'loanprocess_principle'     => $principal,
                            'loanprocess_principlepay'  => $principal,
                            'loanprocess_principleos'   => $decrementPrincipal,
                            'loanprocess_accprinciple'  => $incrementPrincipal,
                            'loanprocess_accinterest'   => $incrementInterest,
                            'loanprocess_amountpaid'    => $incrementPrincipal,
                            'loanprocess_amountcredit'  => $decrementPrincipal,
                            'loanprocess_owe'           => $payment,
                            'loanprocess_owepay'        => $payment,
                            'loanprocess_status'        => 4,
                            'note_type'                 => 1,
                            'rate_for_change'           => $check_change_rate,
                            'rate_change_month_from'    => $month_from_r,
                            'rate_change_month_to'      => $month_to_r
                        ]);
                        $LoanNo++;
                        $startDate = $this->Loan_date_generator($startDate);
                    }
                }
                // }
            }
            //End
            //Update Loan
            LoanModel::where("id",$request->loan_id)->update(['loan_duration'=>($LoanNo-1)]);
            //End

            //Insert Payment Policy & Payment Policy Detail
            DB::table("nso007_sale_policy_payment")->where("sale_id",$request->salename_id)->update(['payment_policy_id'=>$request->payment_policy,'policy_detail_id'=>$request->payment_policy_detail]);
            //End

            $loanprocesses_done = LoanProcessModel::where("loanprocess_loanid",$request->loan_id)->get();
            
            foreach($loanprocesses_done as $p_key => $process_done){
                LoanProcessModel::where("id",$process_done->id)->update(['loanprocess_no'=>$p_key]);
            }

            LogActivity::addToLog('Reschedule successfully!');
            $clientID = LoanModel::find($request->loan_id)->loan_clientid;
            return redirect()->route('client-payment-list.show',Crypt::encrypt($clientID))
            ->with('success','You have reschedule client payment successfully!');
        }
        
    }
    public function Loan_date_generator($date)
    {
        return date('Y-m-d', strtotime("$date +1 month"));
    }
    public function LoanprocessGenerator($loanID,$installmentAmount,$loantype,$loanDuration,$loanInterest,$startDate,$loanNumberstart,$incrementInterest,$incrementPrincipal,$decrementPrincipal){
        $rate = (float)$loanInterest/100;
        $remainingBalance = $installmentAmount;
        if($loantype==2 || ($loantype==1 && $loanInterest<=0)){
            $principal = $installmentAmount/$loanDuration;
            for($i=1;$i<=$loanDuration;$i++){
                $interest           = $rate*$remainingBalance;
                $remainingBalance   -= $principal;
                $payment            = $interest+$principal;
                // dd($payment);
                $incrementPrincipal += $principal;
                $incrementInterest  += $interest;
                $decrementPrincipal -= $principal;
                LoanProcessModel::insert([
                    'loanprocess_loanid'        => $loanID,
                    'loanprocess_no'            => $loanNumberstart,
                    'loanprocess_datepayment'   => $startDate,
                    'loanprocess_interest'      => $interest,
                    'loanprocess_interestpay'   => $interest,
                    'loanprocess_principle'     => $principal,
                    'loanprocess_principlepay'  => $principal,
                    'loanprocess_principleos'   => $decrementPrincipal,
                    'loanprocess_accprinciple'  => $incrementPrincipal,
                    'loanprocess_accinterest'   => $incrementInterest,
                    'loanprocess_amountpaid'    => $incrementPrincipal,
                    'loanprocess_amountcredit'  => $decrementPrincipal,
                    'loanprocess_owe'           => $payment,
                    'loanprocess_owepay'        => $payment,
                    'loanprocess_status'        => 3,
                ]);
                $loanNumberstart++;
                $startDate = $this->Loan_date_generator($startDate);
            }
        }else{
            $payment = ($installmentAmount * $rate) / (1 - (pow((1 + $rate), -$loanDuration)));
            for ($i = 1; $i <= $loanDuration; $i++) {
                $start              = $i + 1;
                $interest           = $remainingBalance * $rate;
                $remainingBalance   = ((pow((1 + $rate), $start - 1) * $installmentAmount) - (((pow((1 + $rate), $start - 1) - 1) / $rate) * $payment));

                $principal              = $payment - $interest;
                $incrementInterest     += $interest;
                $incrementPrincipal    += $principal;
                $decrementPrincipal    -= $principal;
                LoanProcessModel::insert([
                    'loanprocess_loanid'        => $loanID,
                    'loanprocess_no'            => $loanNumberstart,
                    'loanprocess_datepayment'   => $startDate,
                    'loanprocess_interest'      => $interest,
                    'loanprocess_interestpay'   => $interest,
                    'loanprocess_principle'     => $principal,
                    'loanprocess_principlepay'  => $principal,
                    'loanprocess_principleos'   => $decrementPrincipal,
                    'loanprocess_accprinciple'  => $incrementPrincipal,
                    'loanprocess_accinterest'   => $incrementInterest,
                    'loanprocess_amountpaid'    => $incrementPrincipal,
                    'loanprocess_amountcredit'  => $decrementPrincipal,
                    'loanprocess_owe'           => $payment,
                    'loanprocess_owepay'        => $payment,
                    'loanprocess_status'        => 3,
                ]);
                $loanNumberstart++;
                $startDate = $this->Loan_date_generator($startDate);
            }
        }
        $data_return = array("no"=>$loanNumberstart,"incrementPrincipal"=>$incrementPrincipal,"incrementInterest"=>$incrementInterest,'decrementPrincipal'=>$decrementPrincipal);
        return $data_return;
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $id           = $id;

        $installment  = DB::table('nso007_approve_instalment as install')
            ->join('nso007_client as client','client.id','install.loan_clientid')
            ->select('install.*','client.client_fullname')
            ->where('install.loan_saleid',$id)->first();

        $installment_step   = ApproveInstalmentStepModel::where('approve_instalment_id', $installment->id)->orderby('id')->get();
        $installment_count   =DB::table("nso007_approve_instalment_step")
            ->select(DB::raw("COUNT(*) as app_st_count"))
            ->where('approve_instalment_id', $installment->id)
            ->groupBy("approve_instalment_id")
            ->get();

        $loan_amount=$installment->loan_amount;

        $data_loan=[];

        if ($installment->loan_type==1){
            $paymentByStep          = $installment->loan_amount_payment; // Total paid in payment step
            $loanprocess_amountpaid = $paymentByStep; // Total payment step

            $amountLoan             = $installment->loan_amount; // Old Total Price for monthly payment
            $duration               = $installment->loan_duration; // Duration pay
            $interest               = $installment->loan_interest; // Interest
            $principlePay           = $amountLoan / $duration; // Payment for monthly
            $amountOS               = $amountLoan; // Old Total Price for monthly payment
            $no                     = $installment_count[0]->app_st_count+1; // Count up +1 after payment step
            $accPrinciple           = $paymentByStep; // Old total paid in payment step
            $accInterest            = 0; // Old interest
            $amountPaid             = 0; // Old paid amount
            $paid_alone             = 0;
            for ($i = 0; $i < $duration; $i++) {
                $interestPay        = ($amountOS * $interest / 100); // Calculate interest monthly
                $principlePay       = $principlePay; // Monthly payment
                $amountOS          -= $principlePay; // Old Total Price after paid monthly
                $accPrinciple       = ($accPrinciple + $principlePay);
                $accInterest        = ($accInterest + $interestPay);
                $totalAmountCredit  = $amountLoan + $interestPay;
                $payment            = ($principlePay + $interestPay);
                $amountPaid        += $payment;
                $loanprocess_amountpaid += $payment;
                $paid_alone        += $principlePay;
                $amountCredit       = $amountLoan - $paid_alone;

                $data = array(
                    'loanprocess_no'            => $no,
                    'loanprocess_datepayment'   => date('Y-m-d', strtotime($installment->loan_firstpaydate . " + $i month")),
                    'loanprocess_interest'      => $interestPay,
                    'loanprocess_interestpay'   => $interestPay,
                    'loanprocess_principle'     => $principlePay,
                    'loanprocess_principlepay'  => $principlePay,
                    'loanprocess_principleos'   => $amountOS,
                    'loanprocess_accprinciple'  => $accPrinciple,
                    'loanprocess_accinterest'   => $accInterest,
                    'loanprocess_amountpaid'    => $loanprocess_amountpaid,
                    'loanprocess_amountcredit'  => $amountCredit,
                    'loanprocess_owe'           => $payment,
                    'loanprocess_owepay'        => $payment,
                );

                $no++;
                $data_loan[$no]=$data;
            }
        }else{
            $paymentByStep          = $installment->loan_amount_payment;; // Total paid in payment step
            $loanprocess_amountpaid = $paymentByStep; // Total payment step

            $amountLoan = $installment->loan_amount; // Old Total Price for monthly payment
            $duration = $installment->loan_duration; // Duration pay
            $interest = $installment->loan_interest;; // Interest
            $amountOS = $amountLoan; // Old Total Price for monthly payment
            $no = $installment_count[0]->app_st_count + 1; // Count up +1 after payment step
            $accPrinciple = $paymentByStep; // Old total paid in payment step
            $accInterest = 0;
            $rate = $interest / 100;
            $zero = (1 - pow((1 + $rate), - $duration));
            if(!empty($zero))
            {
                $payment1 = ($amountLoan * $rate) / $zero;
            }
            else
            {
                $payment1 = 0;
            }
            $newPrincipal = $amountLoan;
            for ($i = 0; $i < $duration; $i++) {
                $newInterest    = $rate * $newPrincipal;
                $principlepay   = $payment1 - $newInterest;
                $newPrincipal   = $newPrincipal - $principlepay;


                $amountOS      -= $principlepay; // Old Total Price after paid monthly

                $accPrinciple   = ($accPrinciple + $payment1);
                $accInterest    = ($accInterest + $newInterest);

                $loanprocess_amountpaid += $payment1;
                $amountCredit   = $newPrincipal - $principlepay;

                $data = array(
                    'loanprocess_no'            => $no,
                    'loanprocess_datepayment'   => date('Y-m-d', strtotime($installment->loan_firstpaydate . " + $i month")),
                    'loanprocess_interest'      => $newInterest,
                    'loanprocess_interestpay'   => $newInterest,
                    'loanprocess_principle'     => $principlepay,
                    'loanprocess_principlepay'  => $principlepay,
                    'loanprocess_principleos'   => $amountOS,
                    'loanprocess_accprinciple'  => $accPrinciple,
                    'loanprocess_accinterest'   => $accInterest,
                    'loanprocess_amountpaid'    => $loanprocess_amountpaid,
                    'loanprocess_amountcredit'  => $amountOS,
                    'loanprocess_owe'           => $payment1,
                    'loanprocess_owepay'        => $payment1,
                );
                $no++;
                $data_loan[$no]=$data;
            }
        }

        //dd($data_loan[2]['loanprocess_no']);
        return view('administrator.reschedule.view_reschedule',compact('loan_amount','data_loan','installment','installment_step'));
    }

    public function approve_reschedule(Request $request){
        $id           = $request->sale_id;

        $loan_data=DB::table("nso007_loan")->where("loan_saleid",$id)->first();
        LoanProcessModel::where("loanprocess_loanid",$loan_data->id)->where("loanprocess_activity",null)->where("loanprocess_datepaid",null)->delete();
        $data=LoanProcessModel::where("loanprocess_loanid",$loan_data->id)->select(DB::raw("count(id) as d"))->first();

        $installment  = DB::table('nso007_approve_instalment as install')
            ->join('nso007_client as client','client.id','install.loan_clientid')
            ->select('install.*','client.client_fullname')
            ->where('install.loan_saleid',$id)->first();

        $installment_step   = ApproveInstalmentStepModel::where('approve_instalment_id', $installment->id)->orderby('id')->get();
        $installment_count   =DB::table("nso007_approve_instalment_step")
            ->select(DB::raw("COUNT(*) as app_st_count"))
            ->where('approve_instalment_id', $installment->id)
            ->groupBy("approve_instalment_id")
            ->get();

        $loan_amount=$installment->loan_amount;

        $data_loan=[];

        if ($installment->loan_type==1){
            $paymentByStep          = $installment->loan_amount_payment; // Total paid in payment step
            $loanprocess_amountpaid = $paymentByStep; // Total payment step

            $amountLoan             = $installment->loan_amount; // Old Total Price for monthly payment
            $duration               = $installment->loan_duration; // Duration pay
            $interest               = $installment->loan_interest; // Interest
            $principlePay           = $amountLoan / $duration; // Payment for monthly
            $amountOS               = $amountLoan; // Old Total Price for monthly payment
            if(!empty($data->d)) $no = $data->d+1; // Count up +1 after payment step
            else $no=1;
            $accPrinciple           = $paymentByStep; // Old total paid in payment step
            $accInterest            = 0; // Old interest
            $amountPaid             = 0; // Old paid amount
            $paid_alone             = 0;
            for ($i = 0; $i < $duration; $i++) {
                $interestPay        = ($amountOS * $interest / 100); // Calculate interest monthly
                $principlePay       = $principlePay; // Monthly payment
                $amountOS          -= $principlePay; // Old Total Price after paid monthly
                $accPrinciple       = ($accPrinciple + $principlePay);
                $accInterest        = ($accInterest + $interestPay);
                $totalAmountCredit  = $amountLoan + $interestPay;
                $payment            = ($principlePay + $interestPay);
                $amountPaid        += $payment;
                $loanprocess_amountpaid += $payment;
                $paid_alone        += $principlePay;
                $amountCredit       = $amountLoan - $paid_alone;

                $data = array(
                    'loanprocess_loanid'        => $loan_data->id,
                    'loanprocess_no'            => $no,
                    'loanprocess_datepayment'   => date('Y-m-d', strtotime($installment->loan_firstpaydate . " + $i month")),
                    'loanprocess_interest'      => $interestPay,
                    'loanprocess_interestpay'   => $interestPay,
                    'loanprocess_principle'     => $principlePay,
                    'loanprocess_principlepay'  => $principlePay,
                    'loanprocess_principleos'   => $amountOS,
                    'loanprocess_accprinciple'  => $accPrinciple,
                    'loanprocess_accinterest'   => $accInterest,
                    'loanprocess_amountpaid'    => $loanprocess_amountpaid,
                    'loanprocess_amountcredit'  => $amountCredit,
                    'loanprocess_owe'           => $payment,
                    'loanprocess_owepay'        => $payment,
                );

                $no++;
                LoanProcessModel::insert($data);
            }
        }else{
            $paymentByStep          = $installment->loan_amount_payment;; // Total paid in payment step
            $loanprocess_amountpaid = $paymentByStep; // Total payment step

            $amountLoan = $installment->loan_amount; // Old Total Price for monthly payment
            $duration = $installment->loan_duration; // Duration pay
            $interest = $installment->loan_interest;; // Interest
            $amountOS = $amountLoan; // Old Total Price for monthly payment
            if(!empty($data->d)) $no = $data->d+1; // Count up +1 after payment step
            else $no=1;
            $accPrinciple = $paymentByStep; // Old total paid in payment step
            $accInterest = 0;
            $rate = $interest / 100;
            $zero = (1 - pow((1 + $rate), - $duration));
            if(!empty($zero))
            {
                $payment1 = ($amountLoan * $rate) / $zero;
            }
            else
            {
                $payment1 = 0;
            }
            $newPrincipal = $amountLoan;
            for ($i = 0; $i < $duration; $i++) {
                $newInterest    = $rate * $newPrincipal;
                $principlepay   = $payment1 - $newInterest;
                $newPrincipal   = $newPrincipal - $principlepay;


                $amountOS      -= $principlepay; // Old Total Price after paid monthly

                $accPrinciple   = ($accPrinciple + $payment1);
                $accInterest    = ($accInterest + $newInterest);

                $loanprocess_amountpaid += $payment1;
                $amountCredit   = $newPrincipal - $principlepay;

                $data = array(
                    'loanprocess_loanid'        => $loan_data->id,
                    'loanprocess_no'            => $no,
                    'loanprocess_datepayment'   => date('Y-m-d', strtotime($installment->loan_firstpaydate . " + $i month")),
                    'loanprocess_interest'      => $newInterest,
                    'loanprocess_interestpay'   => $newInterest,
                    'loanprocess_principle'     => $principlepay,
                    'loanprocess_principlepay'  => $principlepay,
                    'loanprocess_principleos'   => $amountOS,
                    'loanprocess_accprinciple'  => $accPrinciple,
                    'loanprocess_accinterest'   => $accInterest,
                    'loanprocess_amountpaid'    => $loanprocess_amountpaid,
                    'loanprocess_amountcredit'  => $amountOS,
                    'loanprocess_owe'           => $payment1,
                    'loanprocess_owepay'        => $payment1,
                );
                $no++;
                LoanProcessModel::insert($data);
            }
            //update duration loan
            $loan_duration=LoanProcessModel::where("loanprocess_loanid",$loan_data->id)->select(DB::raw("count(id) as dur"))->first();
            DB::table("nso007_loan")->where("id",$loan_data->id)->update(['loan_duration'=>$loan_duration->dur]);
        }

        //clear status to normal
        $installment1  = DB::table('nso007_approve_instalment as install')
            ->join('nso007_client as client','client.id','install.loan_clientid')
            ->select('install.*','client.client_fullname')
            ->where('install.loan_saleid',$id)->first();

        ApproveInstalmentStepModel::where('approve_instalment_id', $installment1->id)->delete();

        DB::table('nso007_approve_instalment')
            ->where('loan_saleid',$id)->delete();


        $sale_table = SaleStockModel::find($id);
        $sale_table->status_pos_approve_type = 0;
        $sale_table->save();

        //dd($data_loan[2]['loanprocess_no']);
        \LogActivity::addToLog('approve reschedule successfully!');
        return \back();
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $installment  = DB::table('nso007_approve_instalment as install')
            ->join('nso007_client as client','client.id','install.loan_clientid')
            ->select('install.*','client.client_fullname')
            ->where('install.loan_saleid',$id)->first();

        $installment_step   = ApproveInstalmentStepModel::where('approve_instalment_id', $installment->id)->delete();

        DB::table('nso007_approve_instalment')
            ->where('loan_saleid',$id)->delete();


        $sale_table = SaleStockModel::find($id);
        $sale_table->status_pos_approve_type = 0;
        $sale_table->save();

        \LogActivity::addToLog('Reject Reschedule successfully!');

        return redirect()->back()
        ->with('success','You have reject-reschedule client payment successfully!');
    }
    public function get_payment_policy_detail($id){
        return json_encode(DB::table('nso007_payment_policy_detail')->where('policy_id',$id)->get());
    }
}
