<?php

namespace App\Http\Controllers\Administrator;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use DataTables;
use Illuminate\Support\Facades\Crypt;
use Gate;
use App\Helpers\LogActivity;
use App\AccountChartModel;
use App\BankAgencyModel;
use App\CommissionConditionModel;
use App\ClientModel;
use App\LoanModel;
use App\DepositModel;
use App\JournalModel;
use App\MaintenanceProcessPaidModel;
use App\MaintenanceProcessModel;
use App\User;
use Session;
use Auth;
use App\BranchModel;
class MaintenanceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct()
    {
       $this->middleware('permission:Client-Payment-Contract-maintenance', ['only' => ['contract_maintenance_fee']]);
       $this->middleware('permission:Client-Maintenance-House-List', ['only' => ['index']]);
       $this->middleware('permission:Client-Maintenance-House-View', ['only' => ['show']]);
       $this->middleware('permission:Client-Maintenance-House-Generate-Schedule',['only'=>['client_maintenance_generate']]);
       $this->middleware('permission:Client-Maintenance-House-Print-Schedule',['only'=>['contract_maintenance']]);
       $this->middleware('permission:Client-Maintenance-House-Print-Invoice',['only'=>['client_maintenance_payment_print_invoice']]);
       $this->middleware('permission:Client-Maintenance-House-Pay',['only'=>['payment']]);
    }
    public function index(Request $request)
    {
        if($request->ajax()){
            $client = DB::table('nso007_client as client')
                    ->join('nso007_sale_stock as sale','sale.sale_clientid','client.id')
                    ->join('nso007_loan as loan',function($join){
                        $join->on('loan.loan_saleid',"=",'sale.id')
                        ->whereNull("loan.loan_cancel_status")
                        ->orWhere("loan.loan_cancel_status",1);
                    })
                    ->select(DB::raw('CONCAT(client_firstname," ",client_lastname) as client_fullname'),
                            'client.client_gender',
                            'client.id',
                            'client.client_dob',
                            'client.client_address',
                            'client.client_phone1',
                            DB::raw("lPAD(client.id,6,0) AS client_code"))
                    
                    ->when(\Branch::branch_id()!=1,function($query){
                        return $query->where('loan.branch_id',\Branch::branch_id());
                    })
                    ->groupBy('client.id')->get();
            return DataTables::of($client)
            ->addIndexColumn()
            ->editColumn("client_dob",function($client){
                return date("d-m-Y",strtotime($client->client_dob));
            })
            ->addColumn('action',function($client){
                $btn = '';
               if(Gate::check('Client-Maintenance-House-View')){
                $btn = '<a href="'.route('maintenance-list.show',Crypt::encrypt($client->id)).'" class="button_info fa fa-eye"></a>';
               }
                    return $btn;

            })->make(true);
        }
        return view('administrator.client-maintenance-house.sale');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    public function show($id)
    {
        $client_id = Crypt::decrypt($id);
        $bank_data = AccountChartModel::select('id', 'acc_name')
            ->whereIn('id', [11001, 11002, 11012])
            ->pluck('acc_name', 'id')
            ->prepend('Please Select', '');
        $method = AccountChartModel::select('id', 'acc_name')
        ->whereIn('id', [11001, 11002,11012])
        ->pluck('acc_name', 'id')
        ->prepend('Please Select', '');
        // dd($bank_data);
        $agents = DB::table('users')->join('nso007_loan', 'users.id', 'nso007_loan.loan_agentid')
            ->select('users.id', DB::raw('CONCAT(users.user_firstname, " ", users.user_lastname) AS agent_name'))
            ->get();
        $agency = User::select('id', DB::raw('CONCAT(user_firstname, " ", user_lastname) AS agency_name'))
            ->where('user_status', 2)
            ->pluck('agency_name', 'id')
            ->prepend('Please Select', '');
        $condition = CommissionConditionModel::select('condition', 'id')->from('nso007_commission_condition')
            ->pluck('condition', 'id')
            ->prepend('Please Select', '');
        $commission = CommissionConditionModel::select('commission')->from('nso007_commission_condition')
            ->pluck('commission', 'commission')
            ->prepend('Please Select', '');
        Session::put('client_id', $client_id);
        $client = ClientModel::select('id','client_fullname as client_name')
            ->pluck('client_name', 'id')
            ->prepend('Please Select', '');
        $data = DB::select("
            SELECT nso007_client.id,
            nso007_loan.id AS loan_id,
            nso007_loan.loan_amount,
            nso007_loan.loan_discount,
            nso007_sale_stock.sale_receive,
            nso007_loan.loan_amountos,
            detail.saledetail_itemid,
            item.item_name,
            item.item_street,
	        item.item_house,
	        ((nso007_sale_stock.sale_receive*100)/nso007_loan.loan_amount) as percentage,
            project.project_name,
            category.category_name,
            nso007_client.client_fullname,
            nso007_client.client_gender,
            nso007_client.client_phone1,
            nso007_client.client_cardid,
            nso007_client.client_img,
            nso007_client.client_dob,
            nso007_loan.loan_duration,
            nso007_loan.loan_interest
            FROM nso007_client
            LEFT JOIN nso007_loan ON nso007_loan.loan_clientid = nso007_client.id
            LEFT JOIN nso007_sale_stock ON nso007_sale_stock.id = nso007_loan.loan_saleid
            LEFT JOIN nso007_sale_detail_stock AS detail ON detail.saledetail_saleid = nso007_sale_stock.id
            LEFT JOIN nso007_item_stock AS item ON item.id = detail.saledetail_itemid
            LEFT JOIN nso007_project_stock AS project ON project.id = item.item_projectid
            LEFT JOIN nso007_category_stock AS category ON category.id = item.item_categoryid
            WHERE nso007_client.id = $client_id
        ");
        $total_saleamount = $data[0]->loan_amount - $data[0]->loan_amountos - $data[0]->loan_discount;
        $percentage = ($total_saleamount * 100) / $data[0]->loan_amount;
        return view('administrator.client-maintenance-house.show-index', compact('client','data', 'bank_data', 'percentage', 'agents', 'agency', 'condition', 'commission', 'method'));
    }
    public function get_client_maintenance_list()
    {
        $client_id = Session::get('client_id');
        $data = LoanModel::join('nso007_client as client', 'client.id', 'nso007_loan.loan_clientid')
            ->join('nso007_sale_stock as sale_stock', 'sale_stock.id', 'nso007_loan.loan_saleid')
            ->join('nso007_sale_detail_stock as sale', 'sale.saledetail_saleid', 'sale_stock.id')
            ->join('nso007_item_stock as item', 'item.id', 'sale.saledetail_itemid')
            ->join('nso007_project_stock as project', 'project.id', 'item.item_projectid')
            ->join('nso007_category_stock as category', 'category.id', 'item.item_categoryid')
            ->select(
                'sale_stock.id',
                'nso007_loan.id AS loan_id',
                'nso007_loan.loan_amount',
                'nso007_loan.loan_cancel_status',
                DB::raw('(nso007_loan.loan_amount-nso007_loan.loan_discount) as salling_price'),
                'nso007_loan.loan_discount',
                'sale_stock.sale_receive',
                'sale_stock.commission_request',
                'sale_stock.status_pos_approve_type',
                'nso007_loan.loan_percentpay',
                'nso007_loan.request_payoff',
                'nso007_loan.loan_amountos',
                'nso007_loan.loan_status',
                DB::raw('GROUP_CONCAT(item.item_house) as item_name'),
                'client.id AS client_id',
                'project.project_name',
                'category.category_name',
                'nso007_loan.loan_interest',
                'nso007_loan.loan_commission_status',
                'nso007_loan.discount_commis'
            )->where([['client.id', $client_id]])
            ->where(function ($query) {
                $query->where('nso007_loan.loan_cancel_status', '!=', 2);
                $query->orwhere('nso007_loan.loan_cancel_status', null);
            })
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('project.branch_id', \Branch::branch_id());
            })
            ->groupBy('sale_stock.id')->get();
        return Datatables::of($data)
            ->addIndexColumn()
            ->setRowId('loan_id')
            ->addColumn('action', function ($data) {
                $btn_generate_service_maintenance = '';
                $btn_contract_maintenance='';


               if(Gate::check('Client-Maintenance-House-Generate-Schedule')){
                    $btn_generate_service_maintenance = ' <a style="color:white;margin-left:0;" href="' . Route("client_maintenance_generate", array(Crypt::encrypt($data->loan_id), Crypt::encrypt($data->id))) . '" target="_blank" class="button_warning btn-circle"><i class="glyphicon glyphicon-plus" title="Add Schedule Maintenance"></i></a>';
               }
               if(Gate::check('Client-Maintenance-House-Print-Schedule')){
                    $btn_contract_maintenance = '<a style="color:white;margin-left:0;" href="' . Route("contract-maintenance-client-payment", Crypt::encrypt($data->loan_id)) . '" class="button_success btn-circle" title="Print Schedule Maintenance"><i class="glyphicon glyphicon-list-alt"></i></a>';
               }

                return $btn_generate_service_maintenance.$btn_contract_maintenance;
            })
            ->addColumn('details_url', function ($data) {
                if ($data->status_pos_approve_type == 7) return 0;
                return route('get_client_maintenance_process', $data->loan_id);
            })
            ->editColumn('salling_price', function ($data) {
                return "$ " . number_format($data->salling_price, 2);
            })
            ->editColumn('amountOS', function ($data) {
                $remain = $data->loan_amountos;
                if ($remain < 0) {
                    $remain = 0;
                }
                return "$ " . number_format($remain, 2);
            })
            ->editColumn('deposit', function ($data) {
                return "$ " . number_format(DepositModel::select(DB::raw('SUM(deposit_amount) as amount'))->where('deposit_saleid', $data->id)->first()->amount, 2);
            })
            ->editColumn('loan_percentpay', function ($data) {
                return number_format($data->loan_percentpay, 2) . " %";
            })
            ->editColumn('loan_duration', function ($data) {
                return $data->loanprocess()->count();
            })
            ->rawColumns(['details_url' => 'details_url', 'action' => 'action'])
            ->make(true);
    }
    public function client_maintenance_generate($loan_id=null, $sale_id=null)
    {
        $loan_id  = Crypt::decrypt($loan_id);

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

        $data['sale_id']    = $sale_decrypt_id;

        $data['loan_id'] = $loan_id;

        $sub_category_amount = DB::table('nso007_loan')
            ->leftJoin('nso007_sale_stock','nso007_sale_stock.id','nso007_loan.loan_saleid')
            ->leftJoin('nso007_sale_detail_stock','nso007_sale_detail_stock.saledetail_saleid','nso007_sale_stock.id')
            ->leftJoin('nso007_item_stock','nso007_item_stock.id','nso007_sale_detail_stock.saledetail_itemid')
            ->leftJoin('nso007_sub_category_stock','nso007_sub_category_stock.id','nso007_item_stock.item_sub_categoryid')
            ->select(
                'nso007_sub_category_stock.sub_category_name',
                'nso007_sub_category_stock.sub_category_amount',
                'nso007_sub_category_stock.sub_category_code'

            )

            ->where('nso007_loan.id',$loan_id)
            ->first();

        $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");

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

        return view('administrator.client-maintenance-house.create-generate', compact('data','sub_category_amount','loan_id'));
    }

    public function store(Request $request)
    {
        $this->validate($request,[
            'loan_id'=>'required'
        ]);
        $Amount  = $request->loan_amount;
        $loanID             = $request->loan_id;
        $loanDuration       = $request->loan_duration;
        $startDate          = date('Y-m-d',strtotime($request->loan_firstpaydate));
        $max_status_show         = DB::table('nso007_maintenance_process')
            ->select(DB::raw("Max(id) as last_id"),
                DB::raw("Max(maintenance_process_status_show) as last_status_show"))
            ->where('maintenance_process_loanid',$loanID)->first();
        $max_status         =MaintenanceProcessModel::where('maintenance_process_loanid',$loanID)
                                                    ->where('maintenance_process_status_show',$max_status_show->last_status_show)->first();
        if (!empty($max_status)){
            $status=$max_status->maintenance_process_status_show+1;
        }else{
            $status=1;
        }
        for($LoanNo=1; $LoanNo<=$loanDuration; $LoanNo++){
            MaintenanceProcessModel::insert([
                'maintenance_process_loanid'        => $loanID,
                'maintenance_process_no'            => $LoanNo,
                'maintenance_process_datepayment'   => $startDate,
                'maintenance_process_amount'     => $Amount,
                'maintenance_process_amount_pay'  => $Amount,
                'maintenance_process_owe'           => $Amount,
                'maintenance_process_owepay'        => $Amount,
                'maintenance_process_status_show'        => $status,
            ]);
            $startDate = $this->Loan_date_generator($startDate);

        }


        LogActivity::addToLog('Generate Schedule Maintenance Successfully!');
        $clientID = LoanModel::find($request->loan_id)->loan_clientid;
        return redirect()->route('maintenance-list.show',Crypt::encrypt($clientID))
            ->with('success','You have Generate Schedule Maintenance successfully!');
    }
    public function Loan_date_generator($date)
    {
        return date('Y-m-d', strtotime("$date +1 month"));
    }

    public function contract_maintenance($id)
    {
        $loan_id = Crypt::decrypt($id);
        $max_status         = DB::table('nso007_maintenance_process')
                                    ->select(DB::raw("Max(id) as last_id"),
                                        DB::raw("Max(maintenance_process_status_show) as last_status_show"))
                                    ->where('maintenance_process_loanid',$loan_id)->first();

        $contract = DB::table('nso007_loan')
            ->leftJoin('nso007_maintenance_process','nso007_maintenance_process.maintenance_process_loanid','nso007_loan.id')
            ->leftJoin('nso007_sale_stock','nso007_sale_stock.id','nso007_loan.loan_saleid')
            ->leftJoin('nso007_sale_detail_stock','nso007_sale_detail_stock.saledetail_saleid','nso007_sale_stock.id')
            ->leftJoin('nso007_item_stock','nso007_item_stock.id','nso007_sale_detail_stock.saledetail_itemid')
            ->leftJoin('nso007_sub_category_stock','nso007_sub_category_stock.id','nso007_item_stock.item_sub_categoryid')
            ->leftJoin('nso007_project_stock','nso007_project_stock.id','nso007_item_stock.item_projectid')
            ->leftJoin('nso007_client','nso007_client.id','nso007_sale_stock.sale_clientid')
            ->select(

                DB::raw("CONCAT(nso007_client.client_firstname,' ',nso007_client.client_lastname) as client_fullname"),
                'nso007_client.client_phone1',
                'nso007_sale_stock.id',
                'nso007_project_stock.project_name',
                'nso007_item_stock.item_house',
                'nso007_item_stock.item_street',
                'nso007_sub_category_stock.sub_category_name',
                'nso007_maintenance_process.maintenance_process_no',
                'nso007_maintenance_process.maintenance_process_amount',
                'nso007_maintenance_process.maintenance_process_datepayment',
                'nso007_sub_category_stock.sub_category_code'

            )

            ->where('nso007_maintenance_process.maintenance_process_loanid',$loan_id)
            ->where('nso007_maintenance_process.maintenance_process_status_show',$max_status->last_status_show)
            ->get();

        $date = date("Y-m-d"); // or specific date that you want
        if(empty($contract[0])) return \back()->with("warning","request is fail! Please generate schedule maintenance");
//        $khmer = new KhmerDatetime($date);
//        $khmer_date_now = $khmer->getDate();
        return view('administrator.report-client-payment.contract-maintenance',compact('contract'));
    }

    public function contract_maintenance_fee($id)
    {
        $loan_id = Crypt::decrypt($id);

        $contract = DB::table('nso007_sale_detail_stock')
            ->leftJoin('nso007_loan','nso007_loan.loan_saleid','nso007_sale_detail_stock.saledetail_saleid')
            ->leftJoin('nso007_item_stock','nso007_item_stock.id','nso007_sale_detail_stock.saledetail_itemid')
            ->leftJoin('nso007_sub_category_stock','nso007_sub_category_stock.id','nso007_item_stock.item_sub_categoryid')
            ->leftJoin('nso007_project_stock','nso007_project_stock.id','nso007_item_stock.item_projectid')
            ->leftJoin('nso007_client','nso007_client.id','nso007_loan.loan_clientid')
            ->select(
                DB::raw("CONCAT(nso007_client.client_firstname,' ',nso007_client.client_lastname) as client_fullname"),
                'nso007_client.client_phone1',
                'nso007_project_stock.project_name',
                'nso007_item_stock.item_house',
                'nso007_item_stock.item_street',
                'nso007_sub_category_stock.sub_category_name',
                'nso007_sub_category_stock.sub_category_code',
                'nso007_sub_category_stock.sub_category_amount'
            )
            ->where("nso007_loan.id",$loan_id)
            ->groupBy("nso007_sale_detail_stock.id")
            ->get();
        return view('administrator.report-client-payment.contract-maintenance-fee',compact('contract'));
    }

    public function get_client_maintenance_process($id)
    {
        $max_status  = DB::table('nso007_maintenance_process')
                            ->select(DB::raw("Max(id) as last_id"),
                                DB::raw("Max(maintenance_process_status_show) as last_status_show"))
                            ->where('maintenance_process_loanid',$id)->first();
        $status='';
        if (!empty($max_status->last_status_show)){
            $status='AND nso007_maintenance_process.maintenance_process_status_show="'.$max_status->last_status_show.'"';
        }
        $clien_maintenance = DB::select("
            SELECT 
                maintenance_process_no,
                maintenance_process_datepayment,
                maintenance_process_amount,
                nso007_maintenance_process.id,
                nso007_loan.id as loanid,
                nso007_loan.loan_status,
                maintenance_process_amount_pay,
                maintenance_process_status_show,
                maintenance_process_owe,
                maintenance_process_owepay,
                maintenance_process_paid,
                maintenance_process_discount,
                maintenance_process_datepaid,
                nso007_loan.loan_commission_status AS commission_paid
            FROM nso007_maintenance_process
            INNER JOIN nso007_loan ON nso007_maintenance_process.maintenance_process_loanid = nso007_loan.id
            WHERE nso007_loan.id = $id $status
            ORDER BY nso007_maintenance_process.id ASC
        ");

        return Datatables::of($clien_maintenance)
            ->addIndexColumn()
            ->setRowId('id')
            ->editColumn('maintenance_process_datepayment', function ($clien_maintenance) {
                return date('d-m-Y', strtotime($clien_maintenance->maintenance_process_datepayment));
            })
            ->addColumn('status', function ($clien_maintenance) {
                $btnStatus          = '';
                $btnPay             = '';
                $btnInvoice         = '';
                $max_status  = DB::table('nso007_maintenance_process')
                    ->select(DB::raw("Max(id) as last_id"),
                        DB::raw("Max(maintenance_process_status_show) as last_status_show"))
                    ->where('maintenance_process_loanid',$clien_maintenance->loanid)->first();
                $PreviousLoanProcess = MaintenanceProcessModel::where([['maintenance_process_loanid', $clien_maintenance->loanid],['maintenance_process_status_show', $max_status->last_status_show], ['maintenance_process_no', $clien_maintenance->maintenance_process_no - 1]])->first();

                if (!empty($PreviousLoanProcess)) { //has previous loanprocess
                    if ($clien_maintenance->maintenance_process_paid == 1) { //and it is paid
                        if ($clien_maintenance->maintenance_process_paid == null || $clien_maintenance->maintenance_process_paid == 2) { //current loan process unpaid or partially paid

                            $btnPay = '<a data-toggle="modal" href="#form-pay" onclick="pay(this)" class="btn btn-xs btn-outline-primary"  title="Pay" ><i class="fa fa-check-circle"></i></a> Pending';
                        }
                        if ($clien_maintenance->maintenance_process_paid != null) { //loan process completely paid or partially paid
                            $Invoices = MaintenanceProcessPaidModel::where('maintenance_paid_processid', $clien_maintenance->id)->get();
                            foreach ($Invoices as $key => $invoice) {
                                $btnInvoice .= '<a target="_blank" href="' . route('client_maintenance_payment_print_invoice', $invoice->id) . '" type="button" class="btn btn-xs btn-outline-success"  title="Print Invoice" ><i class="fa fa-print"></i></a> Paid: ' . date('d-m-Y', strtotime($invoice->maintenance_paid_payment_date));
                            }
                        }
                    } else {
                        if($PreviousLoanProcess->maintenance_process_paid!=1){
                            $btnPay = '<button data-toggle="modal" disabled href="#form-pay" class="btn btn-xs btn-outline-primary btn-disable" ><i class="fa fa-check-circle"></i></button> Pending';
                        }else{
                            $btnPay = '<a data-toggle="modal" href="#form-pay" onclick="pay(this)" class="btn btn-xs btn-outline-primary"  title="Pay" ><i class="fa fa-check-circle"></i></a> Pending';
                        }
                        if ($clien_maintenance->maintenance_process_paid != null) { //loan process completely paid or partially paid
                            $Invoices = MaintenanceProcessPaidModel::where('maintenance_paid_processid', $clien_maintenance->id)->get();
                            foreach ($Invoices as $key => $invoice) {
                                $btnInvoice .= '<a target="_blank" href="' . route('client_maintenance_payment_print_invoice', $invoice->id) . '" type="button" class="btn btn-xs btn-outline-success"  title="Print Invoice" ><i class="fa fa-print"></i></a> Paid: ' . date('d-m-Y', strtotime($invoice->maintenance_paid_payment_date));
                            }
                        }
                    }
                } else {
                    if ($clien_maintenance->maintenance_process_paid == null || $clien_maintenance->maintenance_process_paid == 2) {
                        $btnPay = '<a data-toggle="modal" href="#form-pay" onclick="pay(this)" class="btn btn-xs btn-outline-primary"  title="Pay" ><i class="fa fa-check-circle"></i></a> Pending';
                    }
                    if (!empty($clien_maintenance->maintenance_process_paid)) {
                        $Invoices = MaintenanceProcessPaidModel::where('maintenance_paid_processid', $clien_maintenance->id)->get();
                        foreach ($Invoices as $key => $invoice) {
                            $btnInvoice .= '<a target="_blank"  href="' . route('client_maintenance_payment_print_invoice', $invoice->id) . '" type="button" class="btn btn-xs btn-outline-success"  title="Print Invoice" ><i class="fa fa-print"></i></a> Paid: ' . date('d-m-Y', strtotime($invoice->maintenance_paid_payment_date));
                        }
                    }
                }
                if(!Gate::check('Client-Maintenance-House-Pay')) $btnPay = '';
                if(!Gate::check('Client-Maintenance-House-Print-Invoice')) $btnInvoice = '';

                return $btnStatus = $btnInvoice . $btnPay;
            })
            ->addColumn('maintenance_process_amount', function ($clien_maintenance) {
                return '$ ' . number_format($clien_maintenance->maintenance_process_amount, 2);
            })
            ->addColumn('maintenance_process_owe', function ($clien_maintenance) {
                return '$ ' . number_format($clien_maintenance->maintenance_process_owe, 2);
            })
            ->addColumn('maintenance_process_discount', function ($clien_maintenance) {
                return '$ ' . number_format($clien_maintenance->maintenance_process_discount, 2);
            })
            ->editColumn('maintenance_process_owepay', function ($clien_maintenance) {
                return '$ ' . number_format($clien_maintenance->maintenance_process_owepay, 2);
            })
            ->rawColumns(['status' => 'status'])
            ->make(true);
    }
    public function client_maintenance_payment_print_invoice($id)
    {
        dd("Comming Soon !");
        $print_step = DB::table('nso007_maintenance_paid')
            ->join('nso007_maintenance_process', 'nso007_maintenance_paid.maintenance_paid_processid', 'nso007_maintenance_process.id')
            ->join('nso007_loan', 'nso007_loan.id', 'nso007_maintenance_process.maintenance_process_loanid')
            ->join('nso007_sale_stock', 'nso007_sale_stock.id', 'nso007_loan.loan_saleid')
            ->join('nso007_sale_detail_stock', 'nso007_sale_detail_stock.saledetail_saleid', 'nso007_sale_stock.id')
            ->join('nso007_item_stock', 'nso007_item_stock.id', 'nso007_sale_detail_stock.saledetail_itemid')
            ->join('nso007_category_stock', 'nso007_category_stock.id', 'nso007_item_stock.item_categoryid')
            ->join('nso007_sub_category_stock', 'nso007_sub_category_stock.id', 'nso007_item_stock.item_sub_categoryid')
            ->join('nso007_project_stock', 'nso007_project_stock.id', 'nso007_item_stock.item_projectid')
            ->join('nso007_client', 'nso007_client.id', 'nso007_loan.loan_clientid')
            ->select(
                'nso007_maintenance_process.maintenance_process_no',
                'nso007_loan.loan_amountos',
                'nso007_loan.id as loan_id',
                'nso007_maintenance_process.maintenance_process_datepayment',
                'nso007_maintenance_process.maintenance_process_amount',
                'nso007_project_stock.project_name',
                'nso007_sale_stock.id as sale_id',
                'nso007_sale_stock.sale_date',
                'nso007_sale_stock.sale_amount',
                'nso007_sale_stock.sale_discount',
                'nso007_item_stock.item_name',
                'nso007_item_stock.item_street',
                'nso007_client.client_fullname',
                'nso007_client.client_phone1',
                'nso007_maintenance_paid.maintenance_paid_total',
                'nso007_maintenance_paid.maintenance_paid_invoice',
                'nso007_maintenance_paid.maintenance_paid_remark',
                'nso007_maintenance_paid.maintenance_paid_payment_date',
//                'nso007_maintenance_paid.loanpaid_penalty',
//                'nso007_maintenance_paid.loanpaid_createdate as paid_date',
                'nso007_maintenance_process.maintenance_process_owe',
                'nso007_sub_category_stock.sub_category_name',
                'nso007_sub_category_stock.sub_category_code',
                'nso007_item_stock.item_house'
            )
            ->where('nso007_maintenance_paid.id', $id)
            ->first();

//        $first_date = DB::table('nso007_loan_process')
//            ->select(
//                'nso007_loan_process.loanprocess_no',
//                'nso007_loan_process.loanprocess_datepayment'
//            )
//            ->where('nso007_loan_process.loanprocess_loanid', $print_step->loan_id)
//            ->first();
//        $last_date = DB::table('nso007_loan_process')
//            ->select(
//                'nso007_loan_process.loanprocess_no',
//                DB::raw("Max(nso007_loan_process.id) as last_id"),
//                DB::raw("Max(nso007_loan_process.loanprocess_datepayment) as loanprocess_datepayment")
//            )
//            ->where('nso007_loan_process.loanprocess_loanid', $print_step->loan_id)
//            ->first();

//        $sale_id=$print_step->sale_id;
//        $sale_payment_policies = DB::table('nso007_sale_policy_payment')->where("sale_id",$sale_id)->first();
//        $payment_policy='';
//        $payment_policy_detail='';
//        if(!empty($sale_payment_policies->payment_policy_id))
//        {
//            $payment_policy.=DB::table("nso007_payment_policy")->where("id",$sale_payment_policies->payment_policy_id)->first()->name;
//
//        }
//        if(!empty($sale_payment_policies->policy_detail_id))
//        {
//
//            $payment_policy_detail.=DB::table("nso007_payment_policy_detail")->where("id",$sale_payment_policies->policy_detail_id)->first()->name;
//
//        }
       $branch = BranchModel::where('id', \Branch::branch_id())->first();
        // echo json_encode($branch);exit();
        return view('administrator.client-maintenance-house.invoice-payment-step', compact('print_step','branch'));
    }
    public function ajax_get_payment_process($id)
    {
        $data['maintenance_process'] = MaintenanceProcessModel::select(
            'id',
            'maintenance_process_loanid',
            'maintenance_process_amount',
            'maintenance_process_owepay',
            'maintenance_process_datepayment'
        )->find($id);
        echo json_encode($data);
    }

    public function payment(Request $request)
    {
        $pid        = $request->pid;
        $amount  = $request->amount;
        $payment    = $request->payment;
        $discount    = $request->discount;
        $pay        = $request->pay;
        $condition  = $request->condition;
        $penalty    = $request->penalty;
        $reference  = $request->reference;
        $date       = $request->date_pay;
        $remark     = $request->remark;
        $loan_id    = $request->loan_id;
        $bank_list  = $request->bank_list;
        $option     = $request->penalty_condition;
        $do_date    = date('Y-m-d H:i:s​​');
        // dd($option);
        $data = array(
            'id'            => $pid,
            'payment'       => $payment,
            'pay'           => $pay,
            'penalty'       => $penalty,
            'datepayment'   => $date,
            'by'            => Auth::user()->id,
            'reference'     => $reference,
            'amount'     => $amount,
            'discount'     => $discount,
            'remark'        => $remark,
            'loan_id'       => $loan_id,
            'do_date'       => $do_date,
            'bank_list'     => $bank_list,
            'fee_charge'    => 0,
            'option'        => $option
        );

        $response = ['success' => true, 'msg' => 'Successfully Paid'];
        try {
            if ($condition == 1) {
                $this->none_payment_condition($data);
            } elseif ($condition == 2) {
                $this->next_payment_condition($data);
            }
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            $response = ['success' => false, 'msg' => $msg];
        }
        return response()->json($response);
    }

    public function none_payment_condition($data)
    {
        $branch_id              = \Branch::branch_id();
        extract($data);

        $insert_invoice = $this::get_check_maintenance_paid_invoice(DB::table("nso007_loan")->where("id",$loan_id)->first()->branch_id);

        $maintenance_process       = MaintenanceProcessModel::find($id);
//        $generatedPenalty   = $penalty;
        $project_by     = DB::table('nso007_sale_stock')
            ->join('nso007_loan', 'nso007_loan.loan_saleid', 'nso007_sale_stock.id')
            ->join('nso007_sale_detail_stock', 'nso007_sale_detail_stock.saledetail_saleid', 'nso007_sale_stock.id')
            ->join('nso007_item_stock', 'nso007_item_stock.id', 'nso007_sale_detail_stock.saledetail_itemid')
            ->select(
                'nso007_item_stock.item_name',
                'nso007_item_stock.item_projectid'
            )
            ->where('nso007_loan.id', $loan_id)->first();
        if (($payment+$discount) < $maintenance_process->maintenance_process_owepay) {

                MaintenanceProcessModel::where('id', $maintenance_process->id)->update([
                    'maintenance_process_amount_pay'    => DB::raw("maintenance_process_amount_pay-($payment+$discount)"),
                    'maintenance_process_owepay'        => DB::raw("maintenance_process_owepay-($payment+$discount)"),
                    'maintenance_process_discount'        => $discount,
                    'maintenance_process_datepaid'      => date('Y-m-d', strtotime($datepayment)),
                    'maintenance_process_by'            => Auth::user()->id,
                    'maintenance_process_activity'      => 2,
                    'maintenance_process_paid_status'   => 2,
                    'maintenance_process_paid'   => 2
                ]);

                MaintenanceProcessPaidModel::insert([
                    'maintenance_paid_processid'    => $maintenance_process->id,
                    'maintenance_paid_payment_date' => date('Y-m-d', strtotime($datepayment)),
                    'maintenance_paid_amount'       => $payment,
                    'maintenance_paid_discount'     => $discount,
//                    'loanpaid_penalty'            => $generatedPenalty,
                    'maintenance_paid_total'        => ($payment+$discount),
                    'maintenance_paid_by'           => Auth::user()->id,
                    'maintenance_paid_reference'    => $reference,
                    'maintenance_paid_invoice'      => $insert_invoice,
                    'maintenance_paid_type'         => 1,
                    'maintenance_paid_remark'       => $remark,
                    'maintenance_paid_bankacc'      => $bank_list,
//                    'loanpaid_penalty_option'     => $option,
//                    'payment_fee'                 => $fee_charge,
                    'maintenance_paid_des'          => 'Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id)
                ]);
                if ($discount>0){
                    $j=JournalModel::select(DB::raw("Max(journal_tran_id) as last_num"))->first();
                    $journal=new JournalModel;
                    $journal->branch_id=0;
                    $journal->journal_parentid=0;
                    $journal->journal_type=1;
                    $journal->journal_acccode=$bank_list;
                    $journal->voucher_type=1;
                    $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                    $journal->journal_des='Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                    $journal->journal_debit=$payment;
                    $journal->journal_credit=0;
                    $journal->journal_tran_id=$j->last_num+1;
                    $journal->journal_transactiondate=date("Y-m-d");
                    $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                    $journal->journal_currency=1;
                    $journal->transaction_type='Maintenance Payment';
                    $journal->journal_referenceid=$maintenance_process->id;
                    $journal->journal_by_project=$project_by->item_projectid;
                    $journal->journal_by=auth()->user()->id;
                    $journal->save();

                    $jj=JournalModel::select(DB::raw("Max(id) as last_id"))->first();

                    $journal=new JournalModel;
                    $journal->branch_id=0;
                    $journal->journal_parentid=$jj->last_id;
                    $journal->journal_type=4;
                    $journal->journal_acccode=41000;
                    $journal->voucher_type=1;
                    $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                    $journal->journal_des='Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                    $journal->journal_debit=0;
                    $journal->journal_credit=$payment+$discount;
                    $journal->journal_tran_id=$j->last_num+1;
                    $journal->journal_transactiondate=date("Y-m-d");
                    $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                    $journal->journal_currency=1;
                    $journal->transaction_type='Maintenance Payment';
                    $journal->journal_referenceid=$maintenance_process->id;
                    $journal->journal_by_project=$project_by->item_projectid;
                    $journal->journal_by=auth()->user()->id;
                    $journal->save();
                    $jj1=JournalModel::select(DB::raw("Max(id) as last_id"))->first();

                    $journal=new JournalModel;
                    $journal->branch_id=0;
                    $journal->journal_parentid=$jj1->last_id;
                    $journal->journal_type=4;
                    $journal->journal_acccode=41005;
                    $journal->voucher_type=1;
                    $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                    $journal->journal_des='Maintenance Discount For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                    $journal->journal_debit=$discount;
                    $journal->journal_credit=0;
                    $journal->journal_tran_id=$j->last_num+1;
                    $journal->journal_transactiondate=date("Y-m-d");
                    $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                    $journal->journal_currency=1;
                    $journal->transaction_type='Maintenance Payment';
                    $journal->journal_referenceid=$maintenance_process->id;
                    $journal->journal_by_project=$project_by->item_projectid;
                    $journal->journal_by=auth()->user()->id;
                    $journal->save();
                }
                else{
                    $j=JournalModel::select(DB::raw("Max(journal_tran_id) as last_num"))->first();
                    $journal=new JournalModel;
                    $journal->branch_id=0;
                    $journal->journal_parentid=0;
                    $journal->journal_type=1;
                    $journal->journal_acccode=$bank_list;
                    $journal->voucher_type=1;
                    $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                    $journal->journal_des='Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                    $journal->journal_debit=$payment;
                    $journal->journal_credit=0;
                    $journal->journal_tran_id=$j->last_num+1;
                    $journal->journal_transactiondate=date("Y-m-d");
                    $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                    $journal->journal_currency=1;
                    $journal->transaction_type='Maintenance Payment';
                    $journal->journal_referenceid=$maintenance_process->id;
                    $journal->journal_by_project=$project_by->item_projectid;
                    $journal->journal_by=auth()->user()->id;
                    $journal->save();

                    $jj=JournalModel::select(DB::raw("Max(id) as last_id"))->first();

                    $journal=new JournalModel;
                    $journal->branch_id=0;
                    $journal->journal_parentid=$jj->last_id;
                    $journal->journal_type=4;
                    $journal->journal_acccode=41000;
                    $journal->voucher_type=1;
                    $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                    $journal->journal_des='Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                    $journal->journal_debit=0;
                    $journal->journal_credit=$payment;
                    $journal->journal_tran_id=$j->last_num+1;
                    $journal->journal_transactiondate=date("Y-m-d");
                    $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                    $journal->journal_currency=1;
                    $journal->transaction_type='Maintenance Payment';
                    $journal->journal_referenceid=$maintenance_process->id;
                    $journal->journal_by_project=$project_by->item_projectid;
                    $journal->journal_by=auth()->user()->id;
                    $journal->save();
                }


//            if ($generatedPenalty > 0 && $option == 2) { //if it is paid less than current payment and penalty step to next, so crement current loan process
//                MaintenanceProcessModel::where('id', $maintenance_process->id)->update([
//                    'penalty_paid' => $generatedPenalty
//                ]);
//            }
        } else {
            MaintenanceProcessModel::where('id', $maintenance_process->id)->update([
                'maintenance_process_amount_pay'    => 0,
                'maintenance_process_owepay'        => 0,
                'maintenance_process_discount'        => $discount,
                'maintenance_process_datepaid'      => date('Y-m-d', strtotime($datepayment)),
                'maintenance_process_by'            => Auth::user()->id,
                'maintenance_process_activity'      => 1,
                'maintenance_process_paid'      => 1,
                'maintenance_process_paid_status'   => 1
            ]);
            MaintenanceProcessPaidModel::insert([
                'maintenance_paid_processid'    => $maintenance_process->id,
                'maintenance_paid_payment_date' => date('Y-m-d', strtotime($datepayment)),
                'maintenance_paid_amount'       => $payment,
                'maintenance_paid_discount'     => $discount,
                'maintenance_paid_total'        => ($payment+$discount),
                'maintenance_paid_by'           => Auth::user()->id,
                'maintenance_paid_reference'    => $reference,
                'maintenance_paid_invoice'      => $insert_invoice,
                'maintenance_paid_type'         => 1,
                'maintenance_paid_des'          => 'Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id),
                'maintenance_paid_remark'       => $remark,
                'maintenance_paid_bankacc'      => $bank_list
            ]);

            if ($discount>0){
                $j=JournalModel::select(DB::raw("Max(journal_tran_id) as last_num"))->first();
                $journal=new JournalModel;
                $journal->branch_id=0;
                $journal->journal_parentid=0;
                $journal->journal_type=1;
                $journal->journal_acccode=$bank_list;
                $journal->voucher_type=1;
                $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                $journal->journal_des='Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                $journal->journal_debit=$payment;
                $journal->journal_credit=0;
                $journal->journal_tran_id=$j->last_num+1;
                $journal->journal_transactiondate=date("Y-m-d");
                $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                $journal->journal_currency=1;
                $journal->transaction_type='Maintenance Payment';
                $journal->journal_referenceid=$maintenance_process->id;
                $journal->journal_by_project=$project_by->item_projectid;
                $journal->journal_by=auth()->user()->id;
                $journal->save();

                $jj=JournalModel::select(DB::raw("Max(id) as last_id"))->first();

                $journal=new JournalModel;
                $journal->branch_id=0;
                $journal->journal_parentid=$jj->last_id;
                $journal->journal_type=4;
                $journal->journal_acccode=41000;
                $journal->voucher_type=1;
                $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                $journal->journal_des='Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                $journal->journal_debit=0;
                $journal->journal_credit=$payment+$discount;
                $journal->journal_tran_id=$j->last_num+1;
                $journal->journal_transactiondate=date("Y-m-d");
                $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                $journal->journal_currency=1;
                $journal->transaction_type='Maintenance Payment';
                $journal->journal_referenceid=$maintenance_process->id;
                $journal->journal_by_project=$project_by->item_projectid;
                $journal->journal_by=auth()->user()->id;
                $journal->save();
                $jj1=JournalModel::select(DB::raw("Max(id) as last_id"))->first();

                $journal=new JournalModel;
                $journal->branch_id=0;
                $journal->journal_parentid=$jj1->last_id;
                $journal->journal_type=4;
                $journal->journal_acccode=41005;
                $journal->voucher_type=1;
                $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                $journal->journal_des='Maintenance Discount For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                $journal->journal_debit=$discount;
                $journal->journal_credit=0;
                $journal->journal_tran_id=$j->last_num+1;
                $journal->journal_transactiondate=date("Y-m-d");
                $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                $journal->journal_currency=1;
                $journal->transaction_type='Maintenance Payment';
                $journal->journal_referenceid=$maintenance_process->id;
                $journal->journal_by_project=$project_by->item_projectid;
                $journal->journal_by=auth()->user()->id;
                $journal->save();
            }
            else{
                $j=JournalModel::select(DB::raw("Max(journal_tran_id) as last_num"))->first();
                $journal=new JournalModel;
                $journal->branch_id=0;
                $journal->journal_parentid=0;
                $journal->journal_type=1;
                $journal->journal_acccode=$bank_list;
                $journal->voucher_type=1;
                $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                $journal->journal_des='Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                $journal->journal_debit=$payment;
                $journal->journal_credit=0;
                $journal->journal_tran_id=$j->last_num+1;
                $journal->journal_transactiondate=date("Y-m-d");
                $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                $journal->journal_currency=1;
                $journal->transaction_type='Maintenance Payment';
                $journal->journal_referenceid=$maintenance_process->id;
                $journal->journal_by_project=$project_by->item_projectid;
                $journal->journal_by=auth()->user()->id;
                $journal->save();

                $jj=JournalModel::select(DB::raw("Max(id) as last_id"))->first();

                $journal=new JournalModel;
                $journal->branch_id=0;
                $journal->journal_parentid=$jj->last_id;
                $journal->journal_type=4;
                $journal->journal_acccode=41000;
                $journal->voucher_type=1;
                $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                $journal->journal_des='Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                $journal->journal_debit=0;
                $journal->journal_credit=$payment;
                $journal->journal_tran_id=$j->last_num+1;
                $journal->journal_transactiondate=date("Y-m-d");
                $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                $journal->journal_currency=1;
                $journal->transaction_type='Maintenance Payment';
                $journal->journal_referenceid=$maintenance_process->id;
                $journal->journal_by_project=$project_by->item_projectid;
                $journal->journal_by=auth()->user()->id;
                $journal->save();
            }
//            MaintenanceProcessModel::where('id', $maintenance_process->id)->update([
//                'penalty_paid'  => 0
//            ]);
//            if ($generatedPenalty > 0 && $option == 2) { //update penalty loanprocess of next step
//                MaintenanceProcessModel::where([['loanprocess_loanid', $maintenance_process->loanprocess_loanid], ['loanprocess_no', $maintenance_process->loanprocess_no + 1]])->increment('penalty_paid', $generatedPenalty);
//            }
//            MaintenanceProcessModel::where('id', $maintenance_process->id)->update([
//                'penalty_paid'  => 0
//            ]);
        }
    }
    public function next_payment_condition($data)
    {
        extract($data);
        $branch_id      = \Branch::branch_id();
        $insert_invoice = $this::get_check_maintenance_paid_invoice(DB::table("nso007_loan")->where("id",$loan_id)->first()->branch_id);
        $project_by     = DB::table('nso007_sale_stock')
            ->join('nso007_loan', 'nso007_loan.loan_saleid', 'nso007_sale_stock.id')
            ->join('nso007_sale_detail_stock', 'nso007_sale_detail_stock.saledetail_saleid', 'nso007_sale_stock.id')
            ->join('nso007_item_stock', 'nso007_item_stock.id', 'nso007_sale_detail_stock.saledetail_itemid')
            ->select(
                'nso007_item_stock.item_name',
                'nso007_item_stock.item_projectid'
            )
            ->where('nso007_loan.id', $loan_id)->first();
        $maintenance_process   = MaintenanceProcessModel::find($id);
        $payment        = $payment;
        $index          = 0;

        if (empty($penalty) || $penalty == 0 || $discount == 0 || empty($discount)) {
            while ($payment > 0 && !empty($maintenance_process)) {

                if ($payment >= $maintenance_process->maintenance_process_owepay) { //incase total amount is greater than amount to be paid
                    MaintenanceProcessModel::where('id', $maintenance_process->id)->update([
                        'maintenance_process_amount_pay'    => 0,
                        'maintenance_process_owepay'        => 0,
                        'maintenance_process_datepaid'      => date('Y-m-d', strtotime($datepayment)),
                        'maintenance_process_by'            => Auth::user()->id,
                        'maintenance_process_activity'      => 1,
                        'maintenance_process_paid'          => 1,
                        'maintenance_process_paid_status'   => 1
                    ]);
                    MaintenanceProcessPaidModel::insert([
                        'maintenance_paid_processid'    => $maintenance_process->id,
                        'maintenance_paid_payment_date' => date('Y-m-d', strtotime($datepayment)),
                        'maintenance_paid_amount'       => $maintenance_process->maintenance_process_amount,
                        'maintenance_paid_total'        => $maintenance_process->maintenance_process_owe,
                        'maintenance_paid_by'           => Auth::user()->id,
                        'maintenance_paid_reference'    => $reference,
                        'maintenance_paid_invoice'      => $insert_invoice,
                        'maintenance_paid_type'         => 1,
                        'maintenance_paid_des'          => 'Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id),
                        'maintenance_paid_remark'       => $remark,
                        'maintenance_paid_bankacc'      => $bank_list

                    ]);
                        $j=JournalModel::select(DB::raw("Max(journal_tran_id) as last_num"))->first();
                        $journal=new JournalModel;
                        $journal->branch_id=0;
                        $journal->journal_parentid=0;
                        $journal->journal_type=1;
                        $journal->journal_acccode=$bank_list;
                        $journal->voucher_type=1;
                        $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                        $journal->journal_des='Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                        $journal->journal_debit=$maintenance_process->maintenance_process_amount;
                        $journal->journal_credit=0;
                        $journal->journal_tran_id=$j->last_num+1;
                        $journal->journal_transactiondate=date("Y-m-d");
                        $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                        $journal->journal_currency=1;
                        $journal->transaction_type='Maintenance Payment';
                        $journal->journal_referenceid=$maintenance_process->id;
                        $journal->journal_by_project=$project_by->item_projectid;
                        $journal->journal_by=auth()->user()->id;
                        $journal->save();

                        $jj=JournalModel::select(DB::raw("Max(id) as last_id"))->first();

                        $journal=new JournalModel;
                        $journal->branch_id=0;
                        $journal->journal_parentid=$jj->last_id;
                        $journal->journal_type=4;
                        $journal->journal_acccode=41000;
                        $journal->voucher_type=1;
                        $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                        $journal->journal_des='Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                        $journal->journal_debit=0;
                        $journal->journal_credit=$maintenance_process->maintenance_process_amount;
                        $journal->journal_tran_id=$j->last_num+1;
                        $journal->journal_transactiondate=date("Y-m-d");
                        $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                        $journal->journal_currency=1;
                        $journal->transaction_type='Maintenance Payment';
                        $journal->journal_referenceid=$maintenance_process->id;
                        $journal->journal_by_project=$project_by->item_projectid;
                        $journal->journal_by=auth()->user()->id;
                        $journal->save();


                } else {

                    MaintenanceProcessModel::where('id', $maintenance_process->id)->update([
                        'maintenance_process_amount_pay'    => DB::raw("maintenance_process_amount_pay-$payment"),
                        'maintenance_process_owepay'        => DB::raw("maintenance_process_owepay-$payment"),
                        'maintenance_process_datepaid'      => date('Y-m-d', strtotime($datepayment)),
                        'maintenance_process_by'            => Auth::user()->id,
                        'maintenance_process_activity'      => 2,
                        'maintenance_process_paid_status'   => 2,
                        'maintenance_process_paid'   => 2

                    ]);
                    MaintenanceProcessPaidModel::insert([
                        'maintenance_paid_processid'    => $maintenance_process->id,
                        'maintenance_paid_payment_date' => date('Y-m-d', strtotime($datepayment)),
                        'maintenance_paid_amount'       => $payment,
                        'maintenance_paid_total'        => $payment,
                        'maintenance_paid_by'           => Auth::user()->id,
                        'maintenance_paid_reference'    => $reference,
                        'maintenance_paid_invoice'      => $insert_invoice,
                        'maintenance_paid_type'         => 1,
                        'maintenance_paid_remark'       => $remark,
                        'maintenance_paid_bankacc'      => $bank_list,
                        'maintenance_paid_des'          => 'Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id)
                    ]);
                    $j=JournalModel::select(DB::raw("Max(journal_tran_id) as last_num"))->first();
                    $journal=new JournalModel;
                    $journal->branch_id=0;
                    $journal->journal_parentid=0;
                    $journal->journal_type=1;
                    $journal->journal_acccode=$bank_list;
                    $journal->voucher_type=1;
                    $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                    $journal->journal_des='Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                    $journal->journal_debit=$payment;
                    $journal->journal_credit=0;
                    $journal->journal_tran_id=$j->last_num+1;
                    $journal->journal_transactiondate=date("Y-m-d");
                    $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                    $journal->journal_currency=1;
                    $journal->transaction_type='Maintenance Payment';
                    $journal->journal_referenceid=$maintenance_process->id;
                    $journal->journal_by_project=$project_by->item_projectid;
                    $journal->journal_by=auth()->user()->id;
                    $journal->save();

                    $jj=JournalModel::select(DB::raw("Max(id) as last_id"))->first();

                    $journal=new JournalModel;
                    $journal->branch_id=0;
                    $journal->journal_parentid=$jj->last_id;
                    $journal->journal_type=4;
                    $journal->journal_acccode=41000;
                    $journal->voucher_type=1;
                    $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
                    $journal->journal_des='Maintenance Payment For '.\Globals::paymentDesByMaintenanceProcessID("", $maintenance_process->id);
                    $journal->journal_debit=0;
                    $journal->journal_credit=$payment;
                    $journal->journal_tran_id=$j->last_num+1;
                    $journal->journal_transactiondate=date("Y-m-d");
                    $journal->journal_paydate=date("Y-m-d", strtotime($datepayment));
                    $journal->journal_currency=1;
                    $journal->transaction_type='Maintenance Payment';
                    $journal->journal_referenceid=$maintenance_process->id;
                    $journal->journal_by_project=$project_by->item_projectid;
                    $journal->journal_by=auth()->user()->id;
                    $journal->save();

                }
                $index++;
                $payment -= $maintenance_process->maintenance_process_owepay;
                $max_status  = DB::table('nso007_maintenance_process')
                    ->select(DB::raw("Max(id) as last_id"),
                        DB::raw("Max(maintenance_process_status_show) as last_status_show"))
                    ->where('maintenance_process_loanid',$loan_id)->first();
                $maintenance_process = MaintenanceProcessModel::where([['maintenance_process_status_show', $max_status->last_status_show], ['maintenance_process_loanid', $maintenance_process->maintenance_process_loanid], ['maintenance_process_no', $maintenance_process->maintenance_process_no + 1]])->first();
            }
        } else {
            echo json_encode($data["message"] = 'error');
        }
    }
    public static function get_check_maintenance_paid_invoice($branch_id)
    {
        $lastinvoice = DB::table('nso007_maintenance_paid as paid')
            ->join('nso007_maintenance_process as process', 'process.id', 'paid.maintenance_paid_processid')
            ->join('nso007_loan as loan', 'loan.id', 'process.maintenance_process_loanid')
            ->where([['loan.branch_id', $branch_id],['paid.maintenance_paid_invoice','LIKE',date('Y')."%"]])->orderBy('paid.id','DESC')->first();
        if(empty($lastinvoice)){
            $invoice_id = 1;
        }else{
            $invoice_id = explode('-',$lastinvoice->maintenance_paid_invoice);
            $invoice_id = (int)$invoice_id[1]+1;
        }
        $invoice = date('Y').'-'.str_pad($invoice_id, 6, "0", STR_PAD_LEFT);
        return $invoice;
    }
    /**
     *  Condition Next Payment
     */


    public function edit($id)
    {
        //
    }

    public function update(Request $request, $id)
    {
        //
    }


    public function destroy($id)
    {
        //
    }
}
