<?php

namespace App\Http\Controllers\Administrator;

use App\Classes\Reschedule;
use App\Classes\Commission;
use App\Classes\AgencyCommission;

use App\JournalAccountingModel;
use App\JournalModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use DataTables;
use Illuminate\Support\Facades\Crypt;
use Session;
use Auth;
use App\ClientModel;
use App\ItemModel;
use App\LoanModel;
use App\LoanProcessModel;
use App\CommissionConditionModel;
use App\LoanPaidModel;
use App\BranchModel;
use App\SaleStockModel;
use App\CommissionModel;
use App\CommissionItemModel;
use App\CommissionItemReportModel;
use App\ClientRelationshipModel;
use App\SaleStockDetailModel;
use App\FundsRegisterModel;
use App\FundsTransactionModel;
use App\BankModel;
use App\AccountChartModel;
use App\AgencyLevelModel;
use App\AppEditPOS;
use App\DepositModel;
use App\Http\Controllers\Agencies\AdminAgency;
use App\User;
use App\AgencyTypeModel;
use App\AgencyGroupModel;
use App\AgencyCloseSaleModel;
use App\SetCommissionCompanyModel;
use App\CommissionAdminReportModel;
use App\CommissionAdminModel;

class ClientPaymentController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:External-Client-Payment-List', ['only' => ['get_index_company']]);
        $this->middleware('permission:Client-Payment-List', ['only' => ['index']]);
        //        $this->middleware('permission:Booking-Report-Collect-Deposit-List', ['only' => ['index']]);
        $this->middleware('permission:External-Client-AddPayment', ['only' => ['create', 'store']]);
    }

    public function index()
    {

        return view('administrator.client-payment.list.index');
    }
    public function get_client_payment_list()
    {

        $client = DB::table('nso007_client')
            ->join('nso007_sale_stock', 'nso007_sale_stock.sale_clientid', 'nso007_client.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')
            ->join('nso007_project_stock', 'nso007_project_stock.id', 'nso007_item_stock.item_projectid')
            ->join('nso007_category_stock', 'nso007_category_stock.id', 'nso007_item_stock.item_categoryid')
            ->select(
                'nso007_category_stock.category_name',
                'nso007_project_stock.project_name',
                'nso007_client.client_fullname',
                'nso007_client.client_gender',
                'nso007_client.client_dob',
                'nso007_client.id',
                'nso007_client.client_phone1',
                'nso007_client.client_address',
                'nso007_client.client_status',
                'nso007_client.client_contract',
                // 'nso007_item_stock.item_name',
                DB::raw("lPAD(nso007_client.id,6,0) AS client_code")
            )
            ->selectRaw('GROUP_CONCAT(DISTINCT nso007_item_stock.item_name) as item_name')
            ->groupBy('nso007_client.id')
            ->where('nso007_client.client_status', 2)
            ->Where('nso007_sale_stock.status_pos_approve_type', '!=', 5)
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            //            ->where('nso007_project_stock.branch_id', \Branch::branch_id())
            ->get();

        return Datatables::of($client)
            ->addIndexColumn()
            ->editColumn('client_gender', function ($client) {
                switch ($client->client_gender) {
                    case '1':
                        return "Male";
                        break;

                    default:
                        return "Female";
                        break;
                }
            })
            ->addColumn('action', function ($client) {
                $url = '';
                if (!empty(\Branch::branch_key())) {
                    $url = (!empty($client->client_contract)) ? '<a class="btn btn-sm btn-outline-success" href="' . route("datatable.index_company_list", Crypt::encrypt($client->id)) . '" title="View"><i class="button_info fa fa-eye"></i></a>' : 'Pending';
                } else {
                    $url = (!empty($client->client_contract)) ? '<a class="btn btn-sm btn-outline-success" href="' . route("client-payment-list.show", Crypt::encrypt($client->id)) . '" title="View"><i class="button_info fa fa-eye"></i></a>' : 'Pending';
                }
                return $url;
            })
            ->rawColumns(['action' => 'action'])
            ->make(true);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    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', '');
        // 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);

        $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-payment.payment.index', compact('data', 'bank_data', 'percentage', 'agents', 'agency', 'condition', 'commission'));
    }

    public function get_client_purchase_list()
    {
        $client_id = Session::get('client_id');
        $data = DB::select("
            SELECT nso007_sale_stock.id,
            nso007_loan.id AS loan_id,
            nso007_loan.loan_amount,
            nso007_loan.loan_cancel_status,
            (nso007_loan.loan_amount-nso007_loan.loan_discount) as salling_price,
            nso007_loan.loan_discount,
            nso007_sale_stock.sale_receive,
            nso007_sale_stock.commission_request,
            nso007_sale_stock.status_pos_approve_type,
            nso007_sale_stock.id as sale_id,
            nso007_loan.loan_percentpay,
            nso007_loan.loan_amountos,
            nso007_loan.loan_status,
            detail.saledetail_itemid,
            GROUP_CONCAT(item.item_house) as item_name,
            nso007_client.id AS client_id,
            project.project_name,
            category.category_name,
            nso007_loan.loan_duration,
            nso007_loan.loan_interest,
            nso007_loan.loan_commission_status,
            nso007_loan.loan_downpayment,
            nso007_loan.discount_commis
            FROM nso007_client
            INNER JOIN nso007_loan ON nso007_loan.loan_clientid = nso007_client.id
            INNER JOIN nso007_sale_stock ON nso007_sale_stock.id = nso007_loan.loan_saleid
            INNER JOIN nso007_sale_detail_stock AS detail ON detail.saledetail_saleid = nso007_sale_stock.id
            INNER JOIN nso007_item_stock AS item ON item.id = detail.saledetail_itemid
            INNER JOIN nso007_project_stock AS project ON project.id = item.item_projectid
            INNER JOIN nso007_category_stock AS category ON category.id = item.item_categoryid
            WHERE nso007_loan.loan_cancel_status !=2 OR nso007_loan.loan_cancel_status IS NULL AND nso007_client.id = $client_id
            GROUP BY nso007_sale_stock.id
        ");
        return Datatables::of($data)
            ->addIndexColumn()
            ->setRowId('loan_id')
            ->addColumn('action', function ($data) {
                $action = '';
                $btn_deposit = '';
                $btn_cancel = '';

                $btn_cancel = '<span class="button_danger btn-circle btn_cancel_payment" style="cursor: pointer;" data-id="' . Crypt::encrypt($data->id) . '" title="Cancel Payment"><i class="fa fa-times" aria-hidden="true"></i></span>';
                if ($data->loan_cancel_status == 1) {
                    $btn_cancel = '<span class="button_danger btn-circle btn_reject_cancel" style="cursor: pointer;" data-id="' . Crypt::encrypt($data->id) . '" title="Reject Cancel Payment">reject</i></span>
                            <span class="button_info btn-circle btn_approve_cancel" style="cursor: pointer;" data-id="' . Crypt::encrypt($data->id) . '" title="Approve Cancel Payment">approve</i></span>';
                }
                if ($data->loan_downpayment - $data->discount_commis > 0) {
                    if ($data->status_pos_approve_type == 6) {
                        $btn_deposit = '<a style="color:white;margin-left:0;" href="#downpayment" type="a" data-id= "' . Crypt::encrypt($data->id) . '" class="button_info btn-circle approve_deposite" title="Approve Downpayment">approve</a>
                <a style="color:white;margin-left:0;" href="#downpayment" type="a" data-id= "' . Crypt::encrypt($data->id) . '" class="button_danger btn-circle reject_deposite" title="Reject Downpayment">reject</a>';
                    } else {
                        if ($data->loan_commission_status == '1') {
                            $btn_deposit = '<a style="color:white;margin-left:0;" href="#downpayment" type="a" data-id= "' . Crypt::encrypt($data->loan_id) . '" class="button_primary btn-circle downpayment" title="Add Downpayment"><i class="fa fa-money"></i></a>';
                        } else {
                            $btn_deposit = '<a style="color:white;margin-left:0;" data-toggle="modal" href="#commission_info" type="a" class="button_primary btn-circle" title="Add Downpayment"><i class="fa fa-money"></i></a>';
                        }
                    }
                } else {
                    $btn_deposit = '<a style="color:white;margin-left:0;" href="#downpayment" type="button" class="button_primary btn-circle" title="Downpayment Done"><i class="fa fa-check"></i></a>';
                }
                if ($data->loan_status == '') {
                    $action = '
                    <a style="color:white;margin-left:0;" href="' . Route("client_payment_reschedule", array(Crypt::encrypt($data->loan_id), Crypt::encrypt($data->id))) . '" type="a" class="button_warning btn-circle"><i class="glyphicon glyphicon-edit" title="Reschedule"></i></a>
                    <a style="color:white;margin-left:0;" href="#payoff" onclick="payoff(this)" data-toggle="modal" class="button_danger btn-circle" title="Pay Off"><i class="glyphicon glyphicon-scissors"></i></a>
                    <a style="color:white;margin-left:0;" href="' . Route("schedule-client-payment.schedule", Crypt::encrypt($data->loan_id)) . '" target="_blank" class="button_primary btn-circle" title="Schedule"><i class="glyphicon glyphicon-list"></i></a>
                    <a style="color:white;margin-left:0;" href="' . Route("contract-client-payment.contract", Crypt::encrypt($data->loan_id)) . '" target="_blank" class="button_info btn-circle" title="Contract"><i class="glyphicon glyphicon-list-alt"></i></a>';
                } elseif ($data->loan_status == 2) {
                    $action = '
                    <a style="color:white;margin-left:0;" href="' . Route("schedule-client-payment.schedule", Crypt::encrypt($data->loan_id)) . '" target="_blank" class="button_primary btn-circle" title="Schedule"><i class="glyphicon glyphicon-list"></i></a>
                    <a style="color:white;margin-left:0;" href="' . Route("contract-client-payment.contract", Crypt::encrypt($data->loan_id)) . '" target="_blank" class="button_info btn-circle" title="Contract"><i class="glyphicon glyphicon-list-alt"></i></a>
                    <a style="color:white;margin-left:0;" href="#" type="a" class="button_success btn-circle" title="Completed"><i class="glyphicon glyphicon-ok"></i></a>';
                }
                if ($data->status_pos_approve_type == 7) {
                    $action = '<div class="dropdown">
                                <button class="btn btn-flat btn-info dropdown-toggle btn-sm" type="button" id="dropdownMenu1" name="action" data-toggle="dropdown">
                                  Actions
                                    <span class="caret"></span>
                                </button>
                                <ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dropdownMenu1">
                                    <li><a style="color:white;margin-left:0;" href="' . route('reschedule-client-payment.show', $data->sale_id) . '" data-toggle="modal" title="View-Reschedule" class="btn-xs"><strong class="text-warning"><span class="fa fa-eye"></span> view reschedule</strong></a></li>
                                     <li><a style="color:white;margin-left:0;" href="#approve-reschedule" onclick="approvedReschedule(' . $data->sale_id . ')" data-toggle="modal" title="Approve Instalment" class="btn-xs"><strong class="text-warning"><span class="glyphicon glyphicon-saved"></span> Approve reschedule</strong></a></li>
                                     <li><a style="color:white;margin-left:0;" onclick="rejectReschedule(' . $data->sale_id . ')" title="Reject Reschedule" class="btn-xs btn"><strong class="text-warning"><span class="fa fa-cut"></span> Reject reschedule</strong></a></li>
                                </ul>
                             </div>';
                    return $action;
                }


                return $action . $btn_deposit . $btn_cancel;
            })
            ->addColumn('details_url', function ($data) {
                if ($data->status_pos_approve_type == 7) return 0;
                return route('datatable.get_client_payment_process', $data->loan_id);
            })
            ->editColumn('salling_price', function ($data) {
                return "$ " . number_format($data->salling_price, 2);
            })
            ->editColumn('loan_percentpay', function ($data) {
                return number_format($data->loan_percentpay, 2) . " %";
            })
            ->rawColumns(['details_url' => 'details_url', 'action' => 'action'])
            ->make(true);
    }


    public function get_index_company($id)
    {
        $client_id = Crypt::decrypt($id);
        $bank_data = AccountChartModel::select('id', 'acc_name')
            ->whereIn('id', [11001, 11002])
            ->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();
        $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);
        $agency = User::select('users.id', DB::raw('CONCAT(users.user_firstname, " ", users.user_lastname) AS agency_name'))
            ->join('nso007_funds', 'nso007_funds.user_id', 'users.id')
            ->where('users.user_status', 2)
            ->pluck('agency_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_img,
            nso007_client.client_phone1,
            nso007_client.client_cardid,
            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-payment.payment.index_company', compact('agency', 'data', 'bank_data', 'percentage', 'agents', 'condition', 'commission'));
    }

    public function get_index_company_list()
    {
        $client_id = Session::get('client_id');
        $data = DB::select("
            SELECT nso007_sale_stock.id,
            nso007_loan.id AS loan_id,
            nso007_loan.loan_amount,
            nso007_loan.loan_cancel_status,
            (nso007_loan.loan_amount-nso007_loan.loan_discount) as salling_price,
            nso007_loan.loan_discount,
            nso007_sale_stock.sale_receive,
            nso007_sale_stock.commission_request,
            nso007_sale_stock.status_pos_approve_type,
            nso007_loan.loan_percentpay,
            nso007_loan.loan_amountos,
            nso007_loan.loan_status,
            detail.saledetail_itemid,
            GROUP_CONCAT(item.item_house) as item_name,
            nso007_client.id AS client_id,
            project.project_name,
            category.category_name,
            nso007_loan.loan_duration,
            nso007_loan.loan_interest,
            nso007_loan.loan_commission_status,
            nso007_loan.loan_downpayment,
            nso007_loan.discount_commis
            FROM nso007_client
            INNER JOIN nso007_loan ON nso007_loan.loan_clientid = nso007_client.id
            INNER JOIN nso007_sale_stock ON nso007_sale_stock.id = nso007_loan.loan_saleid
            INNER JOIN nso007_sale_detail_stock AS detail ON detail.saledetail_saleid = nso007_sale_stock.id
            INNER JOIN nso007_item_stock AS item ON item.id = detail.saledetail_itemid
            INNER JOIN nso007_project_stock AS project ON project.id = item.item_projectid
            INNER JOIN nso007_category_stock AS category ON category.id = item.item_categoryid
            WHERE nso007_loan.loan_cancel_status !=2 OR nso007_loan.loan_cancel_status IS NULL AND nso007_client.id = $client_id
            GROUP BY nso007_sale_stock.id
        ");
        return Datatables::of($data)
            ->addIndexColumn()
            ->setRowId('loan_id')
            ->addColumn('action', function ($data) {
                $btn_commission = '';
                if (!empty(\Branch::branch_key())) {

                    if ($data->loan_commission_status == 0) {
                        if ($data->commission_request == 2) {
                            $btn_request_commission = '<div class="dropdown">
                                <button class="btn btn-flat btn-info dropdown-toggle btn-sm" type="button" id="dropdownMenu1" name="action" data-toggle="dropdown">
                                  Actions
                                    <span class="caret"></span>
                                </button>
                                <ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dropdownMenu1">
                                    <li><a data-toggle="modal" href="#commission_info" class="btn-circle"  title="Pay" ><strong class="text-warning"><span class="glyphicon glyphicon-repeat"></span> Pending</strong></a></li> 
                                    <li><a style="color:white;margin-left:0;" href="#approve-commission" type="a" data-id= "' . Crypt::encrypt($data->id) . '" class="btn-circle btn-approve-commission" title="Approve Commission"><strong class="text-warning"><span class="glyphicon glyphicon-saved"></span> Approve</strong></a></li>
                                    <li><a style="color:white;margin-left:0;" href="#approve-commission" type="a" data-id= "' . Crypt::encrypt($data->id) . '" class="btn-circle btn-reject-commission" title="Reject Commission"><strong class="text-warning"><span class="fa fa-cut"></span> Reject</strong></a></li>
                                </ul>
                             </div>';
                            // $btn_request_commission = '<a data-toggle="modal" href="#commission_info" class="button_warning btn-circle"  title="Pay" >Pending</a> 
                            //                            <a style="color:white;margin-left:0;" href="#approve-commission" type="a" data-id= "' . Crypt::encrypt($data->id) . '" class="button_info btn-circle btn-approve-commission" title="Approve Commission">Approve</a>
                            //                            <a style="color:white;margin-left:0;" href="#approve-commission" type="a" data-id= "' . Crypt::encrypt($data->id) . '" class="button_danger btn-circle btn-reject-commission" title="Reject Commission">reject</a>';
                            $btn_commission = $btn_request_commission;
                        } else {
                            $btn_commission = '<a style="color:white;margin-left:0;" href="#add-commission" type="a" data-id= "' . Crypt::encrypt($data->id) . '" class="button_warning btn-circle btn-add-commission"><i class="fa fa-percent" title="Add Commission"></i></a>';
                        }
                    } else {
                        $btn_commission = '<a style="color:white;margin-left:0;" href="#add-commission" type="a" class="button_success btn-circle" title="Commission Paid"><i class="fa fa-check"></i></a>';
                    }
                }

                return $btn_commission;
            })
            ->addColumn('details_url', function ($data) {
                return route('datatable.get_client_payment_process', $data->loan_id);
            })
            ->editColumn('salling_price', function ($data) {
                return "$ " . number_format($data->salling_price, 2);
            })
            ->editColumn('loan_percentpay', function ($data) {
                return number_format($data->loan_percentpay, 2) . " %";
            })
            ->rawColumns(['details_url' => 'details_url', 'action' => 'action'])
            ->make(true);
    }


    public function get_commission_amount($id)
    {
        $id    = Crypt::decrypt($id);
        $sale_detail = SaleStockDetailModel::where('saledetail_saleid', $id)->get();
        $sale_comm = LoanModel::where('loan_saleid', $id)->first();
        $agency = User::select(DB::raw("CONCAT(user_firstname ,' ',user_lastname) AS agency_name"), 'id', 'agency_type', 'group_id')->where('id', $sale_comm->loan_agentid)->get();
        $close_saleid = User::select(DB::raw("CONCAT(user_firstname ,' ',user_lastname) AS agency_name"), 'id', 'agency_type', 'group_id')->where('id', $sale_comm->loan_close_saleid)->get();
        $agency_type = AgencyTypeModel::where('id', $agency[0]->agency_type)->get();
        $group_type = AgencyGroupModel::where('id', $agency[0]->group_id)->get();
        $close_sale_type = AgencyCloseSaleModel::get();
        $comm_company = SetCommissionCompanyModel::get();

        $agency_id = $agency[0]->id;
        $agency_name = $agency[0]->agency_name;
        $close_sale_id = $close_saleid[0]->id;
        $close_sale_name = $close_saleid[0]->agency_name;

        if ($agency_type[0]->agency_type_name == 'Agent Network') {
            $agency_type_amount_get = $agency_type[0]->agency_type_amount_get;
            $agency_type_condition = $agency_type[0]->agency_type_condition;
            $agency_type_percentage = $agency_type[0]->agency_type_percentage;
        } else {
            $agency_type_amount_get = $group_type[0]->agency_group_amount_get;
            $agency_type_condition = $group_type[0]->agency_group_condition;
            $agency_type_percentage = $group_type[0]->agency_group_percentage;
        }
        $agency_type_id = $agency_type[0]->id;
        $agency_type_name = $agency_type[0]->agency_type_name;

        $commission_amount = 0;
        foreach ($sale_detail as $detail) {
            $item = ItemModel::find($detail->saledetail_itemid);
            $commission = $item->commission_amount;
            if ($commission == 0) {
                $commission = floatval($item->item_price) * floatval($item->commission) / 100;
            }
            $commission_amount += $commission;
        }
        $total_comm1 = $commission_amount;
        $total_comm = (($total_comm1 * $agency_type_amount_get) / 100) - $sale_comm->discount_commis;

        $close_sale = ($commission_amount * $close_sale_type[0]->agency_close_sale_amount_get) / 100;
        $close_sale_condi = $close_sale_type[0]->agency_close_sale_condition;
        $close_sale_commis = $close_sale_type[0]->agency_close_sale_percentage;

        $company_amount = ($commission_amount * $comm_company[0]->agency_company_amount_get) / 100;
        $company_condi = $comm_company[0]->agency_company_condition;
        $company_commis = $comm_company[0]->agency_company_percentage;

        $data = array(
            'total_comm' => $total_comm,
            'agency_id' => $agency_id,
            'agency_type_id' => $agency_type_id,
            'close_sale_id' => $close_sale_id,
            'close_sale_name' => $close_sale_name,
            'agency_type_name' => $agency_type_name,
            'agency_type_amount_get' => $agency_type_amount_get,
            'agency_type_condition' => $agency_type_condition,
            'agency_type_percentage' => $agency_type_percentage,
            'company_amount' => $company_amount,
            'company_condi' => $company_condi,
            'company_commis' => $company_commis,
            'close_sale' => $close_sale,
            'close_sale_condi' => $close_sale_condi,
            'close_sale_commis' => $close_sale_commis,
            'agency_name' => $agency_name
        );

        echo json_encode($data);
    }
    //update comission here
    public function add_agent_commission(Request $request)
    {
        $sale_id                = $request->sale_id;
        $sale_id                = Crypt::decrypt($sale_id);
        $commission             = $request->commission;
        $agent_id               = $request->agent_id;
        $user_id                = $request->user_id;
        $agent_type             = $request->agent_type;
        $agency_type_id         = $request->agency_type_id;

        $agency_id_close_sale   = $request->agency_id_close_sale;
        $commission_close_sale  = $request->commission_close_sale;

        $agency_condition       = $request->agency_type_condition;
        $agency_commission      = $request->agency_type_percentage;

        $close_sale_condi       = $request->close_sale_condi;
        $close_sale_commis      = $request->close_sale_commis;

        $company_amount         = $request->company_amount;
        $company_condi          = $request->company_condi;
        $company_commis         = $request->company_commis;

        DB::table('nso007_request_commission')->insert([
            'user_id'           => $user_id,
            'agent_id'          => $agent_id,
            'commission'        => $company_amount,
            'agent_type'        => $agency_type_id,
            'agent_commission'  => $company_commis,
            'agent_condition'   => $company_condi,
            'agent_status'      => 'Company',
            'sale_id'           => $sale_id
        ]);
        DB::table('nso007_request_commission')->insert([
            'user_id'           => $user_id,
            'agent_id'          => $agent_id,
            'commission'        => $commission,
            'agent_type'        => $agency_type_id,
            'agent_commission'  => $agency_commission,
            'agent_condition'   => $agency_condition,
            'agent_status'      => 'Sale',
            'sale_id'           => $sale_id
        ]);
        if (!empty($agency_id_close_sale)) {
            DB::table('nso007_request_commission')->insert([
                'user_id'           => $user_id,
                'agent_id'          => $agency_id_close_sale,
                'commission'        => $commission_close_sale,
                'agent_type'        => $agency_type_id,
                'agent_commission'  => $close_sale_commis,
                'agent_condition'   => $close_sale_condi,
                'agent_status'      => 'Close Sale',
                'sale_id'           => $sale_id
            ]);
        }

        DB::table('nso007_sale_stock')->where('id', $sale_id)->update(
            [
                'commission_request' => 2
            ]
        );
        \LogActivity::addToLog('Add Commission Requested Successfully !');
        return back()->with('success', 'Commission Requested Successfully');
    }

    //   approve commission
    public function approve_commission(Request $request)
    {
        // dd($request->all());
        $company_agency = DB::table('users')->where('company_agent', 1)->first();
        // dd($company_agency);

        $sale_id        = $request->sale_id;
        $sale_id        = Crypt::decrypt($sale_id);
        $item_id        = '';
        $item_cost      = 0;
        $item_price     = 0;
        $sale           = SaleStockModel::find($sale_id);

        $sale_detail    = DB::table('nso007_sale_detail_stock as detail')
            ->join('nso007_item_stock as stock', 'stock.id', 'detail.saledetail_itemid')
            ->select('stock.*')
            ->where('detail.saledetail_saleid', $sale_id)->get();
        $commission_amount = 0;

        foreach ($sale_detail as $detail){
            $commission = $detail->commission_amount;

            if ($commission == 0) {
                $commission = floatval($detail->item_price) * floatval($detail->commission) / 100;
            }

            $commission_amount  += $commission;
            $item_id            .= $detail->id . ",";
            $item_cost          += $detail->item_cost;
            $item_price         += $detail->item_price;
        }

        $comm_request           = DB::table('nso007_request_commission')->where('sale_id', $sale_id)->where('agent_status', '<>', 'Company')->get();
        $comm_request_company   = DB::table('nso007_request_commission')->where('sale_id', $sale_id)->where('agent_status', 'Company')->get();

        $comm_cond              = DB::table('nso007_commission_condition')->where('status', 2)->get();
        $condition              = [];
        $commission             = [];

        foreach ($comm_cond as $comm) {

            array_push($condition, $comm->condition);
            array_push($commission, $comm->commission);
        }

        $condition  = implode('|', $condition);
        $commission = implode('|', $commission);
        //  insert commission list



        foreach ($comm_request as $request_comm) {
            DB::table('nso007_agency_commission')->insert([

                'sale_id'           => $sale_id,
                'agency_id'         => $request_comm->agent_id ? $request_comm->agent_id : '',
                'agency_type'       => $request_comm->agent_type ? $request_comm->agent_type : '',
                'client_id'         => $sale->sale_clientid,
                'item_id'           => $item_id,
                'item_cost'         => $item_cost,
                'item_price'        => $item_price,
                'commission'        => $request_comm->commission ? $request_comm->commission : '',
                'status'            => 1,
                'agency_status'     => $request_comm->agent_status ? $request_comm->agent_status : '',
                'condition'         => $request_comm->agent_condition ? $request_comm->agent_condition : '',
                'commis_condition'  => $request_comm->agent_commission ? $request_comm->agent_commission : ''
            ]);
        }
        $closesale_id       = CommissionModel::select('id')->where('sale_id', $sale_id)->where('agency_status', 'Close Sale')->first();
        $closesale_id_comm = CommissionModel::where('id', $closesale_id->id)->first();

        $commission_id = CommissionModel::select('id')->where('sale_id', $sale_id)->where('agency_status', 'Sale')->first();
        $commission_agency = CommissionModel::where('id', $commission_id->id)->first();
        $item_stock = ItemModel::where('id', $commission_agency->item_id)->first();
        $items_price = ($sale->sale_amount - $sale->sale_discount);


        DB::table('nso007_admin_commission')->insert([

            'sale_id'           => $sale_id,
            'agent_id'          => $comm_request_company[0]->agent_id,
            'agent_type'       => $comm_request_company[0]->agent_type,
            'client_id'         => $sale->sale_clientid,
            'item_id'           => $item_id,
            'item_cost'         => $item_cost,
            'item_price'        => $item_price,
            'commission'        => $comm_request_company[0]->commission,
            'commission_amount' => $comm_request_company[0]->commission,
            'condition'         => $comm_request_company[0]->agent_condition,
            'commis_condition'  => $comm_request_company[0]->agent_commission
        ]);
        $company_commission      = $this->calculate_approve_commission_group($comm_request_company[0]->commission, $items_price, $sale->sale_receive, $comm_request_company[0]->commission,  $comm_request_company[0]->agent_commission, $comm_request_company[0]->agent_condition);
        //           check if amount equal to 0
        if ($company_commission['balance'] > 0) {
            $this->increment_admin_commission_receive($sale_id, $company_commission['balance']);
        }


        DB::table('nso007_agency_commission_list')->insert([

            'commission_id' => $closesale_id->id,
            'com_list_sale_id' => $sale_id,
            'agency_id'     => $closesale_id_comm->agency_id,
            'commission'    => $closesale_id_comm->commission,
            'condition'     => $closesale_id_comm->condition,
            'commis_condition'     => $closesale_id_comm->commis_condition,
            'amount'        => $closesale_id_comm->commission
        ]);
        //          find agency fund account
        $last_commission_level1 = CommissionItemModel::max('id');
        $account_number_level1  = $this->find_agency_account_number($closesale_id_comm->agency_id);
        //          calculate commission
        $closesale_commission      = $this->calculate_approve_commission_group($commission_agency->commission, $items_price, $sale->sale_receive, $closesale_id_comm->commission,  $closesale_id_comm->commis_condition, $closesale_id_comm->condition);
        //           check if amount equal to 0
        if ($closesale_commission['balance'] > 0) {
            $this->put_commission_to_report($item_stock->id, $closesale_commission['balance']);
            $this->increment_funds_balance($closesale_id_comm->agency_id, $closesale_commission['balance'], $item_stock->item_name, $account_number_level1);
            $this->increment_commission_receive($closesale_id_comm->agency_id, $closesale_commission['balance'], $last_commission_level1);
        }


        //        network type
        if ($commission_agency->agency_type == 1) {
            $commission_level = AgencyLevelModel::orderBy('id', 'DESC')->get();
            //dd($commission_level);
            //    insert commission network level 1
            DB::table('nso007_agency_commission_list')->insert([

                'commission_id' => $commission_id->id,
                'com_list_sale_id' => $sale_id,
                'agency_id'     => $commission_agency->agency_id,
                'agency_level'  =>   1,
                'commission'    => $commission_level[0]->commission_level,
                'condition'     => $commission_agency->condition,
                'commis_condition' => $commission_agency->commis_condition,
                'amount'        => ($commission_agency->commission * $commission_level[0]->commission_level) / 100
            ]);
            //          find agency fund account
            $last_commission_level1 = CommissionItemModel::max('id');
            $account_number_level1  = $this->find_agency_account_number($commission_agency->agency_id);
            //          calculate commission
            $commission_level1      = $this->calculate_approve_commission($commission_agency->commission, $items_price, $sale->sale_receive, $commission_level[0]->commission_level, $commission_agency->commis_condition, $commission_agency->condition);
            //           check if amount equal to 0
            if ($commission_level1['balance'] > 0) {
                $this->put_commission_to_report($item_stock->id, $commission_level1['balance']);
                $this->increment_funds_balance($commission_agency->agency_id, $commission_level1['balance'], $item_stock->item_name, $account_number_level1);
                $this->increment_commission_receive($commission_agency->agency_id, $commission_level1['balance'], $last_commission_level1);
            }
            $i = 2;
            $commiss_level2 = 0;
            $deactive_id = null;
            $parent_id_deactive = null;
            foreach ($commission_level as $comm_level) {

                if ($comm_level->id < $commission_level[0]->id) {
                    $max_commission = CommissionItemModel::where('commission_id', $commission_id->id)->max('id');
                    $commission_item = CommissionItemModel::where('id', $max_commission)->first();
                    if ($commission_item->agency_level > 1) {
                        $parent_idd = $commission_item->agency_id;
                    } else {
                        $parent_idd = $commission_agency->agency_id;
                    }

                    $network_level = User::where('id', $parent_idd)->first();

                    $user_level_log2 = User::where('id', $network_level->parent_id)->first();

                    //  check agency has parent or not
                    if (isset($network_level) && $network_level->parent_id == null) {
                        $commiss_level2 += $comm_level->commission_level;
                    } else if (isset($network_level) && $network_level->parent_id != null && $user_level_log2->user_activity == 1) {

                        DB::table('nso007_agency_commission_list')->insert([
                            'commission_id' => $commission_id->id,
                            'com_list_sale_id' => $sale_id,
                            'agency_id'     => $network_level->parent_id,
                            'agency_level'  =>   $i,
                            'commission'    => $comm_level->commission_level,
                            'condition'     => $commission_agency->condition,
                            'commis_condition'     => $commission_agency->commis_condition,
                            'amount'        => ($commission_agency->commission * $comm_level->commission_level) / 100,
                        ]);
                        $last_commission_level3 = CommissionItemModel::max('id');
                        $account_number_level3  = $this->find_agency_account_number($network_level->parent_id);
                        $commission_level3      = $this->calculate_approve_commission($commission_agency->commission, $items_price, $sale->sale_receive, $comm_level->commission_level, $commission_agency->commis_condition, $commission_agency->condition);
                        if ($commission_level3['balance'] > 0) {
                            $this->put_commission_to_report($item_stock->id, $commission_level3['balance']);
                            $this->increment_funds_balance($network_level->parent_id, $commission_level3['balance'], $item_stock->item_name, $account_number_level3);
                            $this->increment_commission_receive($network_level->parent_id, $commission_level3['balance'], $last_commission_level3);
                        }
                    } else if ($user_level_log2->user_activity != 1) {
                        $network_level = User::where('id', $user_level_log2->parent_id)->first();
                        $deactive_id = $network_level->user_activity;
                        $parent_id_deactive = $network_level->parent_id;
                        if ($deactive_id != 1) {
                            while ($deactive_id != 1) {
                                $network_level11 = User::where('id', $parent_id_deactive)->first();
                                $deactive_id = $network_level11->user_activity;
                                $parent_id_deactive = $network_level11->parent_id;
                                if ($deactive_id == 1) {
                                    DB::table('nso007_agency_commission_list')->insert([
                                        'commission_id' => $commission_id->id,
                                        'com_list_sale_id' => $sale_id,
                                        'agency_id'     => $network_level11->id,
                                        'agency_level'  =>   $i,
                                        'commission'    => $comm_level->commission_level,
                                        'condition'     => $commission_agency->condition,
                                        'commis_condition' => $commission_agency->commis_condition,
                                        'amount'        => ($commission_agency->commission * $comm_level->commission_level) / 100,
                                    ]);
                                    $last_commission_level3 = CommissionItemModel::max('id');
                                    $account_number_level3  = $this->find_agency_account_number($network_level11->id);
                                    $commission_level3      = $this->calculate_approve_commission($commission_agency->commission, $items_price, $sale->sale_receive, $comm_level->commission_level, $commission_agency->commis_condition, $commission_agency->condition);
                                    if ($commission_level3['balance'] > 0) {
                                        $this->put_commission_to_report($item_stock->id, $commission_level3['balance']);
                                        $this->increment_funds_balance($network_level11->id, $commission_level3['balance'], $item_stock->item_name, $account_number_level3);
                                        $this->increment_commission_receive($network_level11->id, $commission_level3['balance'], $last_commission_level3);
                                    }
                                }
                            }
                        } else {
                            DB::table('nso007_agency_commission_list')->insert([
                                'commission_id' => $commission_id->id,
                                'com_list_sale_id' => $sale_id,
                                'agency_id'     => $network_level->id,
                                'agency_level'  =>   $i,
                                'commission'    => $comm_level->commission_level,
                                'condition'     => $commission_agency->condition,
                                'commis_condition'     => $commission_agency->commis_condition,
                                'amount'        => ($commission_agency->commission * $comm_level->commission_level) / 100,
                            ]);
                            $last_commission_level3 = CommissionItemModel::max('id');
                            $account_number_level3  = $this->find_agency_account_number($network_level->id);
                            $commission_level3      = $this->calculate_approve_commission($commission_agency->commission, $items_price, $sale->sale_receive, $comm_level->commission_level, $commission_agency->commis_condition, $commission_agency->condition);
                            if ($commission_level3['balance'] > 0) {
                                $this->put_commission_to_report($item_stock->id, $commission_level3['balance']);
                                $this->increment_funds_balance($network_level->id, $commission_level3['balance'], $item_stock->item_name, $account_number_level3);
                                $this->increment_commission_receive($network_level->id, $commission_level3['balance'], $last_commission_level3);
                            }
                        }
                    }
                    //                    else{
                    //                        $commiss_level2 += $comm_level->commission_level;
                    //                    }
                    $i++;
                }
            }

            //            if ($commiss_level2!=0){
            //                DB::table('nso007_agency_commission_list')->insert([
            //                    'commission_id' => $commission_id->id,
            //                    'agency_id'     => $company_agency->id,
            //                    'agency_level'  => $i,
            //                    'commission'    => $commiss_level2,
            //                    'condition'     => $commission_agency->condition,
            //                    'amount'        => ($commission_agency->commission * $commiss_level2) / 100
            //                ]);
            //                $last_commission_level2 = CommissionItemModel::max('id');
            //                $account_number_level2  = $this->find_agency_account_number($company_agency->id);
            //                $commission_level2      = $this->calculate_approve_commission($commission_agency->commission,$items_price, $sale->sale_receive, $commiss_level2,$commission_agency->commis_condition, $item_stock->condition);
            //                if ($commission_level2['balance'] > 0) {
            //                    $this->put_commission_to_report($item_stock->id, $commission_level2['balance']);
            //                    $this->increment_funds_balance($company_agency->id, $commission_level2['balance'], $item_stock->item_name, $account_number_level2);
            //                    $this->increment_commission_receive($company_agency->id, $commission_level2['balance'], $last_commission_level2);
            //                }
            //            }

        } else {

            DB::table('nso007_agency_commission_list')->insert([

                'commission_id' => $commission_id->id,
                'com_list_sale_id' => $sale_id,
                'agency_id' => $commission_agency->agency_id,
                'agency_level' => 1,
                'commission' => $commission_agency->commission,
                'condition' => $commission_agency->condition,
                'commis_condition' => $commission_agency->commis_condition,
                'amount' => $commission_agency->commission
            ]);
            //          find agency fund account
            $last_commission_level1 = CommissionItemModel::max('id');
            $account_number_level1 = $this->find_agency_account_number($commission_agency->agency_id);
            //          calculate commission
            $commission_level1 = $this->calculate_approve_commission_group($commission_agency->commission, $items_price, $sale->sale_receive, $commission_agency->commission,  $commission_agency->commis_condition, $commission_agency->condition);
            //           check if amount equal to 0
            if ($commission_level1['balance'] > 0) {
                $this->put_commission_to_report($item_stock->id, $commission_level1['balance']);
                $this->increment_funds_balance($commission_agency->agency_id, $commission_level1['balance'], $item_stock->item_name, $account_number_level1);
                $this->increment_commission_receive($commission_agency->agency_id, $commission_level1['balance'], $last_commission_level1);
            }


            //  check agency has parent or not
            //            if (isset($network_level) && $network_level->parent_id == null) {
            //
            //
            ////                $commiss_level2 = ($commission_level[1]->commission_level) + ($commission_level[2]->commission_level) + ($commission_level[3]->commission_level);
            ////
            ////                DB::table('nso007_agency_commission_list')->insert([
            ////                    'commission_id' => $commission_id,
            ////                    'agency_id'     => $company_agency->id,
            ////                    'agency_level'  => 2,
            ////                    'commission'    => $commiss_level2,
            ////                    'condition'     => $item_stock->condition,
            ////                    'amount'        => $commission_agency->commission,
            ////                ]);
            ////
            ////                $account_number_level2  = $this->find_agency_account_number($company_agency->id);
            ////                $commission_level2      = $this->calculate_approve_commission($item_stock->item_price, $sale->sale_receive, 2, $commiss_level2, $item_stock->condition);
            ////
            ////                if (!empty($commission_level2)) {
            ////                    $this->put_commission_to_report($item_stock->id, $commission_level2);
            ////                    $this->increment_funds_balance($company_agency->id, $commission_level2, $item_stock->item_name, $account_number_level2);
            ////                    $this->increment_commission_receive($company_agency->id, $commission_level2, $commission_id);
            ////                }
            //            } else

            $network_level = User::where('id', $commission_agency->agency_id)->first();

            $agency = User::select(DB::raw("CONCAT(user_firstname ,' ',user_lastname) AS agency_name"), 'id', 'agency_type', 'group_id', 'parent_id')->where('id', $network_level->parent_id)->get();

            $group_type = AgencyGroupModel::where('id', $agency[0]->group_id)->get();
            $agency_type_amount_get = $group_type[0]->agency_group_amount_get;
            $agency_type_condition = $group_type[0]->agency_group_condition;
            $agency_type_percentage = $group_type[0]->agency_group_percentage;
            $get_comm_l2 = $commission_amount * $agency_type_amount_get / 100;
            if (isset($network_level) && $agency[0]->id != null) {

                DB::table('nso007_agency_commission_list')->insert([

                    'commission_id' => $commission_id->id,
                    'com_list_sale_id' => $sale_id,
                    'agency_id' => $agency[0]->id,
                    'agency_level' => 2,
                    'commission' => $get_comm_l2,
                    'condition' => $agency_type_condition,
                    'commis_condition' => $agency_type_percentage,
                    'amount' => $get_comm_l2,
                ]);
                $last_commission_level2 = CommissionItemModel::max('id');
                $account_number_level3 = $this->find_agency_account_number($agency[0]->id);
                $commission_level3 = $this->calculate_approve_commission_group($get_comm_l2, $items_price, $sale->sale_receive, $get_comm_l2, $agency_type_percentage, $agency_type_condition);

                if ($commission_level3['balance'] > 0) {

                    $this->put_commission_to_report($item_stock->id, $commission_level3['balance']);
                    $this->increment_funds_balance($agency[0]->id, $commission_level3['balance'], $item_stock->item_name, $account_number_level3);
                    $this->increment_commission_receive($agency[0]->id, $commission_level3['balance'], $last_commission_level2);
                }

                //$user_level_3 = User::where('id', $network_level->parent_id)->first();

                $agency3 = User::select(DB::raw("CONCAT(user_firstname ,' ',user_lastname) AS agency_name"), 'id', 'agency_type', 'group_id', 'parent_id')->where('id', $agency[0]->parent_id)->get();

                $group_type3 = AgencyGroupModel::where('id', $agency3[0]->group_id)->get();
                $agency_type_amount_get3 = $group_type3[0]->agency_group_amount_get;
                $agency_type_condition3 = $group_type3[0]->agency_group_condition;
                $agency_type_percentage3 = $group_type3[0]->agency_group_percentage;
                $get_comm_l3 = $commission_amount * $agency_type_amount_get3 / 100;
                if ($agency3[0]->id != 0) {

                    DB::table('nso007_agency_commission_list')->insert([
                        'commission_id' => $commission_id->id,
                        'com_list_sale_id' => $sale_id,
                        'agency_id' => $agency3[0]->id,
                        'agency_level' => 3,
                        'commission' => $get_comm_l3,
                        'condition' => $agency_type_condition3,
                        'commis_condition' => $agency_type_percentage3,
                        'amount' => $get_comm_l3,
                    ]);
                    $last_commission_level3 = CommissionItemModel::max('id');
                    $account_number_level4 = $this->find_agency_account_number($agency3[0]->id);

                    $commission_level4 = $this->calculate_approve_commission_group($get_comm_l3, $items_price, $sale->sale_receive,  $get_comm_l3, $agency_type_percentage3, $agency_type_condition3);

                    if ($commission_level4['balance'] > 0) {

                        $this->put_commission_to_report($item_stock->id, $commission_level4['balance']);
                        $this->increment_funds_balance($agency3[0]->id, $commission_level4['balance'], $item_stock->item_name, $account_number_level4);
                        $this->increment_commission_receive($agency3[0]->id, $commission_level4['balance'], $last_commission_level3);
                    }

                    //$user_level_4 = User::where('id', $user_level_3->id)->first();
                    if ($agency3[0]->parent_id != 0) {
                        $agency4 = User::select(DB::raw("CONCAT(user_firstname ,' ',user_lastname) AS agency_name"), 'id', 'agency_type', 'group_id', 'parent_id')->where('id', $agency3[0]->parent_id)->get();
                        $group_type4 = AgencyGroupModel::where('id', $agency4[0]->group_id)->get();
                        $agency_type_amount_get4 = $group_type4[0]->agency_group_amount_get;
                        $agency_type_condition4 = $group_type4[0]->agency_group_condition;
                        $agency_type_percentage4 = $group_type4[0]->agency_group_percentage;
                        $get_comm_l4 = $commission_amount * $agency_type_amount_get4 / 100;
                        if ($agency4[0]->id != 0) {

                            DB::table('nso007_agency_commission_list')->insert([
                                'commission_id' => $commission_id->id,
                                'com_list_sale_id' => $sale_id,
                                'agency_id' => $agency4[0]->id,
                                'agency_level' => 4,
                                'commission' => $get_comm_l4,
                                'condition' => $agency_type_condition4,
                                'commis_condition' => $agency_type_percentage4,
                                'amount' => $get_comm_l4
                            ]);
                            $last_commission_level4 = CommissionItemModel::max('id');
                            $account_number_level5 = $this->find_agency_account_number($agency4[0]->id);
                            $commission_level5 = $this->calculate_approve_commission_group($get_comm_l4, $items_price, $sale->sale_receive, $get_comm_l4, $agency_type_percentage4, $agency_type_condition4);

                            if ($commission_level5['balance'] > 0) {

                                $this->put_commission_to_report($item_stock->id, $commission_level5['balance']);
                                $this->increment_funds_balance($agency4[0]->id, $commission_level5['balance'], $item_stock->item_name, $account_number_level5);
                                $this->increment_commission_receive($agency4[0]->id, $commission_level5['balance'], $last_commission_level4);
                            }
                        }
                    }
                }
                //                else {
                //
                //                    $commiss_admin = ($commission_level[2]->commission_level) + ($commission_level[3]->commission_level);
                //
                //                    DB::table('nso007_agency_commission_list')->insert([
                //                        'commission_id' => $commission_id,
                //                        'agency_id' => $company_agency->id,
                //                        'agency_level' => 3,
                //                        'commission' => $commiss_admin,
                //                        'condition' => $item_stock->condition,
                //                        'amount' => $commission_agency->commission,
                //                    ]);
                //
                //                    $account_number_level3 = $this->find_agency_account_number($company_agency->id);
                //                    $commission_level3 = $this->calculate_approve_commission($item_stock->item_price, $sale->sale_receive, 3, $commiss_admin, $item_stock->condition);
                //
                //                    if (!empty($commission_level3)) {
                //
                //                        $this->put_commission_to_report($item_stock->id, $commission_level3);
                //                        $this->increment_funds_balance($user_level_3->id, $commission_level3, $item_stock->item_name, $account_number_level3);
                //                        $this->increment_commission_receive($user_level_3->id, $commission_level3, $commission_id);
                //                    }
                //                }

            }
        }
        DB::table('nso007_sale_stock')->where('id', $sale_id)->update([
            'commission_request' => 3
        ]);
        DB::table('nso007_loan')->where('loan_saleid', $sale_id)->update([
            'loan_commission_status' => 1
        ]);
        DB::table('nso007_request_commission')->where('sale_id', $sale_id)->delete();
        return back()->with('success', 'Requested Commission was successfully approved');
    }

    public function increment_admin_commission_receive($id, $commission)
    {

        CommissionAdminModel::where('sale_id', $id)->increment('commission_received', $commission);

        $commission_data = CommissionAdminModel::where('sale_id', $id)->select('id')->get();

        $commission_id = $commission_data[0]->id;
        $data = array(
            'commission_id'     => $commission_id,
            'commission_amount' => $commission
        );
        CommissionAdminReportModel::insert($data);
    }

    public function check_commission($percentage, $commission_amount, $condit, $commis)
    {
        //dd($percentage.'/'.$commission_amount.'/'.$condit.'/'.$commis);
        $result = ['status' => false, 'balance' => 0];
        $condition_commission = [];
        $condition  = explode('|', $condit);
        $commission = explode('|', $commis);
        //push array to array
        foreach ($condition as $key => $condi) {
            $array1 = [$condi, $commission[$key]];
            //dd($array1);
            array_push($condition_commission, $array1);
        }
        // dd($condition_commission);

        $smallest_array_value   = floatval($condition_commission[0][0]);

        $smallest_array         = $condition_commission[0];
        // dd($condition_commission[0][0][0]);
        $set_of_smallest_array  = [];
        array_push($set_of_smallest_array, $condition_commission[0]);
        // dd($set_of_smallest_array);
        //define an array to catch smallest set of condition
        // array_push($set_of_smallest_array,$condition_commission[0][0]);

        foreach ($condition_commission as $condi_commi) {

            if (floatval($condi_commi[0]) < $smallest_array_value) {
                $smallest_array_value = floatval($condi_commi[0]);
                $smallest_array = $condi_commi;
            }

            if (floatval($condi_commi[0]) <= $percentage) {
                array_push($set_of_smallest_array, $condi_commi);
            }
        }

        // dd($smallest_array);
        if ($percentage >= floatval($smallest_array[0])) {
            // dd(floatval($smallest_array[0]));
            $result['status'] = true;

            //check available amount
            $biggest_smallest_array_value   = $set_of_smallest_array[0][0];

            $biggest_smallest_array         = $set_of_smallest_array[0];

            // dd($biggest_smallest_array);

            foreach ($set_of_smallest_array as $small_set) {

                if ($small_set[0] >= floatval($biggest_smallest_array_value)) {
                    $biggest_smallest_array = [];
                    $biggest_smallest_array = $small_set;
                }
            }

            //check avialable commission amount
            $balance_condition  = floatval($biggest_smallest_array[0]);
            $balance_commission = floatval($biggest_smallest_array[1]);
            $max_condition      = floatval(max($condition));

            if ($balance_commission == 100) {

                $balance = $commission_amount;
            } else {
                $balance = ($commission_amount * $balance_commission) / 100;
            }
            $result['balance'] = $balance;
        }
        // dd($balance);
        return $result;
    }
    public function check_commission_payment($percentage, $commission_amount, $condit, $commis)
    {
        //dd($percentage.'/'.$commission_amount.'/'.$condit.'/'.$commis);
        $result = ['status' => false, 'balance' => 0];
        $condition_commission = [];
        $condition  = explode('|', $condit);
        $commission = explode('|', $commis);
        //push array to array
        foreach ($condition as $key => $condi) {
            $array1 = [$condi, $commission[$key]];
            //dd($array1);
            array_push($condition_commission, $array1);
        }
        // dd($condition_commission);

        $smallest_array_value   = floatval($condition_commission[0][0]);

        $smallest_array         = $condition_commission[0];
        // dd($condition_commission[0][0][0]);
        $set_of_smallest_array  = [];
        array_push($set_of_smallest_array, $condition_commission[0]);
        // dd($set_of_smallest_array);
        //define an array to catch smallest set of condition
        // array_push($set_of_smallest_array,$condition_commission[0][0]);

        foreach ($condition_commission as $condi_commi) {

            if (floatval($condi_commi[0]) < $smallest_array_value) {
                $smallest_array_value   = $condi_commi[0];
                $smallest_array         = $condi_commi;
            }

            if (floatval($condi_commi[0]) <= $percentage) {
                array_push($set_of_smallest_array, $condi_commi);
            }
        }

        // dd($smallest_array);
        if ($percentage >= floatval($smallest_array[0])) {
            // dd(floatval($smallest_array[0]));
            $result['status'] = true;

            //check available amount
            $biggest_smallest_array_value   = $set_of_smallest_array[0][0];

            $biggest_smallest_array         = $set_of_smallest_array[0];

            // dd($biggest_smallest_array);

            foreach ($set_of_smallest_array as $small_set) {

                if ($small_set[0] >= floatval($biggest_smallest_array_value)) {
                    $biggest_smallest_array_value = $small_set[0];
                    $biggest_smallest_array = [];
                    $biggest_smallest_array = $small_set;
                }
            }

            //check avialable commission amount
            $balance_condition  = floatval($biggest_smallest_array[0]);
            $balance_commission = floatval($biggest_smallest_array[1]);
            $max_condition      = floatval(max($condition));

            if ($balance_commission == 100) {
                $balance = $commission_amount;
            } else {
                $balance = ($commission_amount * $balance_commission) / 100;
            }
            $result['balance'] = $balance;
        }

        return $result;
    }
    public function check_commission_payment_company($percentage, $commission_amount, $condit, $commis)
    {
        //dd($percentage.'/'.$commission_amount.'/'.$condit.'/'.$commis);
        $result = ['status' => false, 'balance' => 0];
        $condition_commission = [];
        $condition  = explode('|', $condit);
        $commission = explode('|', $commis);
        // dd($condition,$commission);
        //push array to array
        foreach ($condition as $key => $condi) {
            $array1 = [$condi, $commission[$key]];
            //dd($array1);
            array_push($condition_commission, $array1);
        }
        // dd($condition_commission);

        $smallest_array_value   = floatval($condition_commission[0][0]);

        $smallest_array         = $condition_commission[0];
        // dd($condition_commission[0][0][0]);
        $set_of_smallest_array  = [];
        // array_push($set_of_smallest_array, $condition_commission[0]);
        // dd($set_of_smallest_array);
        //define an array to catch smallest set of condition
        // array_push($set_of_smallest_array,$condition_commission[0][0]);

        foreach ($condition_commission as $condi_commi) {

            if (floatval($condi_commi[0]) <= $smallest_array_value) {
                $smallest_array_value   = $condi_commi[0];
                $smallest_array         = $condi_commi;
            }

            if (floatval($condi_commi[0]) <= floatval($percentage)) {
                array_push($set_of_smallest_array, $condi_commi);
            }
        }

        // dd($percentage,$condition_commission,$set_of_smallest_array);
        if ($percentage >= floatval($smallest_array[0])) {
            // dd(floatval($smallest_array[0]));
            $result['status'] = true;

            //check available amount
            $biggest_smallest_array_value   = $set_of_smallest_array[0][0];

            $biggest_smallest_array         = $set_of_smallest_array[0];

            // dd($biggest_smallest_array);

            foreach ($set_of_smallest_array as $small_set) {
                if ($small_set[0] >= floatval($biggest_smallest_array_value)) {
                    $biggest_smallest_array_value = $small_set[0];
                    $biggest_smallest_array = [];
                    $biggest_smallest_array = $small_set;
                }
            }

            //check avialable commission amount
            $balance_condition  = floatval($biggest_smallest_array[0]);
            $balance_commission = floatval($biggest_smallest_array[1]);
            $max_condition      = floatval(max($condition));
            if ($balance_commission == 100) {
                $balance = $commission_amount;
            } else {
                $balance = ($commission_amount * $balance_commission) / 100;
            }
            $result['balance'] = $balance;
        }

        return $result;
    }
    public function reject_commission(Request $request)
    {
        $sale_id    = $request->sale_id;
        $sale_id    = Crypt::decrypt($sale_id);
        DB::table('nso007_sale_stock')->where('id', $sale_id)->update([
            'commission_request' => 1
        ]);
        DB::table('nso007_request_commission')->where('sale_id', $sale_id)->delete();
        return back()->with('success', 'Requested Commission was rejected');
    }
    public function get_downpayment($id)
    {
        $decrypt_id = Crypt::decrypt($id);
        // dd($decrypt_id);
        $loan = LoanModel::find($decrypt_id);
        // dd($loan);
        echo \json_encode($loan);
    }
    public function approve_deposite($id)
    {
        $sale_id        = Crypt::decrypt($id);
        $pre_deposite   = AppEditPOS::where('app_sale_id', $sale_id)->first();
        $status_num = 1;
        $deposit = DepositModel::where('deposit_saleid', $sale_id)->first();
        if ($deposit) {
            $status_num = $deposit->status_num + 1;
        }
        $sale_stock = SaleStockModel::find($sale_id);
        $item_cost = $sale_stock->sale_amount;
        $payment_percentage = floatval($pre_deposite->app_payamount) * 100 / floatval($item_cost);
        DB::table('nso007_loan')->where('loan_saleid', $sale_id)
            ->update([
                'loan_downpayment' => DB::raw("loan_downpayment-$pre_deposite->app_payamount"),
                'loan_percentpay' => DB::raw("loan_percentpay+$payment_percentage")
            ]);
        // ->decrement('loan_downpayment',$pre_deposite->app_payamount)->increment('loan_percentpay',floatval($payment_percentage));
        DB::table('nso007_sale_stock')->where('id', $sale_id)->update([
            'status_pos_approve_type' => 0
        ]);
        DB::table('nso007_deposit')->insert(
            [
                'deposit_saleid'    => $sale_id,
                'deposit_date'      => $pre_deposite->app_date,
                'deposit_amount'    => $pre_deposite->app_payamount,
                'status_num'        => $status_num,
                'date_contract'     => $pre_deposite->app_date_contract
            ]
        );
        DB::table('nso007_approve_pos_edit')->where('app_sale_id', $sale_id)->delete();
        $commission = CommissionModel::where('sale_id', $sale_id)->first();
        $item_stock = ItemModel::where('id', $commission->item_id)->first();
        $commission_list = CommissionItemModel::where('commission_id', $commission->id)->get();

        if ($commission_list != null) {
            foreach ($commission_list as $val) {
                $commission_pay = $this->calculate_payment_commission($commission->commission, $item_cost, $sale_stock->sale_receive, $pre_deposite->app_payamount, $val->commission, $item_stock->condition);
                $agency_acc = $this->find_agency_account_number($val->agency_id);

                if (!empty($commission_pay)) {
                    $this->put_commission_to_report($item_stock->id, $commission_pay);
                    $this->increment_funds_balance($val->agency_id, $commission_pay, $item_stock->item_name, $agency_acc);
                    $this->increment_commission_receive($val->agency_id, $commission_pay, $val->id);
                }
            }
        }

        \LogActivity::addToLog('Approve Deposit on Downpayment successfully!');
        return back()->with('success', 'Deposite was successfully approved');
    }
    public function reject_deposite($id)
    {
        $sale_id        = Crypt::decrypt($id);
        DB::table('nso007_sale_stock')->where('id', $sale_id)->update([
            'status_pos_approve_type' => 0
        ]);

        DB::table('nso007_approve_pos_edit')->where('app_sale_id', $sale_id)->delete();
        \LogActivity::addToLog('Reject Deposit on Downpayment successfully!');
        return back()->with('success', 'Deposite was successfully rejected');
    }
    public function get_commission()
    {
        $commissions = AgencyLevelModel::all();
        $div = '';
        foreach ($commissions as $key => $commis) {
            $div .= '<label class="control-label col-md-5">' . $commis->agency_level . '</label>
                     <div class="col-md-7">
                        <input type="text" name="commission_level[]" class="form-control" value="' . $commis->commission_level . '" readonly/>
                     </div>
                    ';
        }
        return $div;
    }
    public function get_commission_condition(Request $request)
    {
        $commission = CommissionConditionModel::where('id', $request->id)->select('id', 'condition', 'commission')->get();

        return json_encode($commission);
    }
    public function get_client_payment_process($id)
    {
        // dd($id);
        // $clientbooking = DB::table('nso007_loan_process as process')
        // ->join('nso007_loan as loan','loan.id','process.loanprocess_loanid')
        // ->select()->where('process.loanprocess_loanid',$id)->get();
        $clientbooking = DB::select("
            SELECT 
                loanprocess_no,
                loanprocess_datepayment,
                nso007_loan_process.id,
                nso007_loan.id as loanid,
                loanprocess_paid,
                nso007_loan_process.updated_at,
                loanprocess_interest AS loanprocess_interest,
                loanprocess_principle AS loanprocess_principle,
                loanprocess_accprinciple AS loanprocess_accprinciple,
                loanprocess_amountpaid AS loanprocess_amountpaid,
                loanprocess_amountcredit AS loanprocess_amountcredit,
                loanprocess_accinterest AS loanprocess_accinterest,
                loanprocess_owe AS loanprocess_owe,
                loanprocess_owepay AS loanprocess_owepay,
                loanprocess_principleos AS loanprocess_principleos,
                nso007_loan.loan_commission_status AS commission_paid
            FROM nso007_loan_process
            INNER JOIN nso007_loan ON nso007_loan_process.loanprocess_loanid = nso007_loan.id
            
            WHERE nso007_loan.id = $id AND nso007_loan_process.loanprocess_des IS NULL
            ORDER BY nso007_loan_process.id ASC
        ");
        return Datatables::of($clientbooking)
            ->addIndexColumn()
            ->setRowId('id')
            ->editColumn('loanprocess_datepayment', function ($clientbooking) {
                return date('Y-m-d', strtotime($clientbooking->loanprocess_datepayment));
            })
            ->addColumn('status', function ($clientbooking) {
                $status = '';
                $btn_delete = '';
                $invoice_pending = '';
                $check_available_delete = LoanProcessModel::where('id', ($clientbooking->id + 1))->WhereNotNull('loanprocess_paid')->first();
                // dd($check_available_delete);
                $step_end = LoanModel::where('id', $clientbooking->loanid)->first();

                $loan_paid = LoanPaidModel::where('loanpaid_processid', $clientbooking->id)->get();
                if ($check_available_delete == null && $clientbooking->loanprocess_paid != null && $step_end['loan_status'] == null) {
                    $btn_delete = '<span class="btn btn-xs btn-outline-danger" title="Delete Payment" data-id="' . Crypt::encrypt($clientbooking->id) . '"><i class="fa fa-trash"></i></span>';
                    if ($clientbooking->loanprocess_paid == 2) {
                        foreach ($loan_paid as $paid) {
                            $invoice_pending .= '<a target="_blank" href="' . route('get_client_purchase_prince_invooice', $paid->id) . '" type="button" class="btn btn-xs btn-outline-success"  title="Print Invoice" ><i class="fa fa-print"></i></a> ';
                        }
                    }
                }
                $find = LoanProcessModel::where('id', ($clientbooking->id - 1))->first();
                if ($find != null) {
                    if ($find->loanprocess_paid == 1 && $find->loanprocess_approve == 1 && $clientbooking->loanprocess_paid != 1) {
                        if ($clientbooking->commission_paid == '1') {
                            $status = '<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';
                        } else {
                            $status = '<a data-toggle="modal" href="#commission_info" class="btn btn-xs btn-outline-primary"  title="Pay" ><i class="fa fa-check-circle"></i></a> Pending';
                        }
                    } else if ($find->loanprocess_paid == 1 && $clientbooking->loanprocess_paid == 1) {
                        foreach ($loan_paid as $key => $paid) {
                            $status .= '<a target="_blank" href="' . route('get_client_purchase_prince_invooice', $paid->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 H:i:s​​ A', strtotime($paid->created_at));
                        }
                    } else if ($find->loanprocess_paid == 1 && $clientbooking->loanprocess_paid == 2) {
                        if ($clientbooking->commission_paid == '1') {
                            $status = '<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';
                        } else {
                            $status = '<a data-toggle="modal" href="#commission_info" class="btn btn-xs btn-outline-primary"  title="Pay" ><i class="fa fa-check-circle"></i></a> Pending';
                        }
                    } else if ($find->loanprocess_paid == null && $clientbooking->loanprocess_paid == 1) {
                        foreach ($loan_paid as $key => $paid) {
                            $status .= '<a target="_blank" href="' . route('get_client_purchase_prince_invooice', $paid->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 H:i:s​​ A', strtotime($paid->created_at));
                        }
                    } else {
                        $status = '<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 {
                    if ($clientbooking->loanprocess_paid == 1) {
                        foreach ($loan_paid as $key => $paid) {
                            $status .= '<a target="_blank" href="' . route('get_client_purchase_prince_invooice', $paid->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 H:i:s​​ A', strtotime($paid->created_at));
                        }
                    } else if ($clientbooking->loanprocess_paid == 2) {
                        if ($clientbooking->commission_paid == '1') {
                            $status = '<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';
                        } else {
                            $status = '<a data-toggle="modal" href="#commission_info" class="btn btn-xs btn-outline-primary"  title="Pay" ><i class="fa fa-check-circle"></i></a> Pending';
                        }
                    }
                }
                return $btn_delete . $invoice_pending . $status;
            })
            ->addColumn('loanprocess_principle', function ($clientbooking) {
                return '$' . number_format($clientbooking->loanprocess_principle, 2);
            })
            ->addColumn('loanprocess_owe', function ($clientbooking) {
                return '$' . number_format($clientbooking->loanprocess_owe, 2);
            })
            ->addColumn('loanprocess_principleos', function ($clientbooking) {
                return '$' . number_format($clientbooking->loanprocess_principleos, 2);
            })
            ->addColumn('loanprocess_interest', function ($clientbooking) {
                return '$' . number_format($clientbooking->loanprocess_interest, 2);
            })
            ->rawColumns(['status' => 'status'])
            ->make(true);
    }

    public function client_purchase_list_print_invoice($id)
    {

        $print_step = DB::table('nso007_loan_paid')
            ->join('nso007_loan_process', 'nso007_loan_paid.loanpaid_processid', 'nso007_loan_process.id')
            ->join('nso007_loan', 'nso007_loan.id', 'nso007_loan_process.loanprocess_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_project_stock', 'nso007_project_stock.id', 'nso007_item_stock.item_projectid')
            ->join('nso007_client', 'nso007_client.id', 'nso007_loan.loan_clientid')
            ->select(
                'nso007_loan_process.loanprocess_no',
                'nso007_loan_process.loanprocess_datepayment',
                'nso007_project_stock.project_name',
                'nso007_item_stock.item_name',
                'nso007_item_stock.item_house',
                'nso007_client.client_fullname',
                'nso007_loan_paid.loanpaid_total',
                'nso007_loan_paid.loanpaid_createdate as paid_date',
                'nso007_loan_process.loanprocess_owe',
                'nso007_item_stock.item_house'
            )
            ->where('nso007_loan_paid.id', $id)
            ->first();
        // dd($print_step);
        $branch = BranchModel::where('id', \Branch::branch_id())->first();
        // echo json_encode($branch);exit();
        return view('administrator.client-payment.payment.invoice-payment-step', compact('print_step', 'branch'));
    }

    /**
     *  Ajax get payment process
     */
    public function ajax_get_payment_process($id)
    {
        $data['loan_process'] = LoanProcessModel::select(
            'id',
            'loanprocess_loanid',
            'loanprocess_interestpay',
            'loanprocess_principlepay',
            'loanprocess_owepay',
            'loanprocess_datepayment',
            'penalty_paid'
        )->find($id);

        $penalty = LoanProcessModel::select('loanprocess_owepay AS loan_pay', DB::raw('TIMESTAMPDIFF(DAY,loanprocess_datepayment,"' . date('Y-m-d') . '") AS day_late'))
            ->where([
                ['id', $data['loan_process']->id],
                ['loanprocess_datepayment', '<', date('Y-d-m')], ['loanprocess_paid', null]
            ])
            ->groupBy('id')
            ->first();

        $data['penalty']    = 0;
        $total_day          = 0;
        //sum all penalty from late payment on loan process
        if ($penalty && $penalty->day_late > 5) {
            $total_day = $penalty->day_late - 5;
            $data['penalty'] = ($penalty->loan_pay * 0.05 * $total_day) / 30;
        }
        //check if current loan process has left penalty from previous payment
        if ($data['loan_process']->penalty_paid && $data['loan_process']->penalty_paid > 0) {
            $data['penalty'] += $data['loan_process']->penalty_paid;
        }
        echo json_encode($data);
    }
    /**
     *  Submit Payment
     */
    public function payment(Request $request)
    {
        // dd($request->all());
        $pid        = $request->pid;
        $principle  = $request->principle;
        $interest   = $request->interest;
        $payment    = $request->payment;
        $pay        = $request->pay;
        $condition  = $request->condition;
        $penalty    = $request->penalty;
        $invoice    = $request->invoice;
        $date       = $request->date;
        $remark     = $request->remark;
        $loan_id    = $request->loan_id;
        $bank_list  = $request->bank_list;
        $extra_amount    = $request->extra_amount;
        $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,
            'invoice'       => $invoice,
            'principle'     => $principle,
            'interest'      => $interest,
            'remark'        => $remark,
            'loan_id'       => $loan_id,
            'do_date'       => $do_date,
            'bank_list'     => $bank_list,
            'extra_amount'  => $extra_amount,
            'fee_charge'  => $request->fee_charge,
            'option'        => $option
        );
        // dd($data);
        // dd($condition);
        if ($condition == 1) {
            $this->none_payment_condition($data);
            $data['message'] = "success";
            echo json_encode($data);
        } elseif ($condition == 2) {
            $this->next_payment_condition($data);
            $data['message'] = "success";
            echo json_encode($data);
        }
    }
    /**
     *  Condition None Payment
     */
    public function none_payment_condition($data)
    {
        $branch_id              = \Branch::branch_id();
        $obj_commission         = new Commission;
        $agency_get_commission  = new AgencyCommission;
        extract($data);
        $payment_amount         = $payment;

        $principle_payment      = $pay - $interest;
        $sale_id                = $agency_get_commission->get_saleid_by_loanid($loan_id);
        $sale_stock              = SaleStockModel::find($sale_id);
        $item_cost              = $sale_stock->sale_amount - $sale_stock->sale_discount;
        $agency_type = DB::select("SELECT agency_type
                                FROM nso007_agency_commission 
                                WHERE sale_id=$sale_id");
        $load_payment_percent   = 100 * floatval($principle) / $item_cost;

        if ($agency_type[0]->agency_type == 1) {
            $this->put_commission_payment($id, $principle_payment, $loan_id);
        } else {
            $this->put_commission_payment_group($id, $principle_payment, $loan_id);
        }

        $amount             = $this->get_loan_paid_amount($loan_id);
        $amount_loan_cost   = $amount->loan_amount;
        $amount_due         = $amount->loan_amountos;
        $amount_paid        = $amount_loan_cost - $amount->loan_discount - $amount_due;

        $comm_request_company = CommissionAdminModel::where('sale_id', $sale_id)->get();
        // dd($comm_request_company[0]->condition,$comm_request_company[0]->commis_condition);
        $commission_pay = $this->calculate_payment_commission_company($comm_request_company[0]->commission, $item_cost, $amount_paid, $principle_payment, $comm_request_company[0]->commission, $comm_request_company[0]->condition, $comm_request_company[0]->commis_condition);
        //dd($comm_request_company[0]->commission.'__'.$item_cost.'__'.$amount_paid.'__'.$principle_payment.'__'.$comm_request_company[0]->commission.'__'.$comm_request_company[0]->condition.'__'.$comm_request_company[0]->commis_condition);
        //dd($comm_request_company[0]->commission.'//'.$commission_pay['balance'].'//'.$comm_request_company[0]->commission_received);
        $commis_pust = number_format($commission_pay['balance'] - $comm_request_company[0]->commission_received, 4);

        //           check if amount equal to 0
        if ($commis_pust > 0) {
            $this->increment_admin_commission_receive($sale_id, $commis_pust);
        }


        // $item_code              = $obj_commission->get_item_code_by_saleid($sale_id);
        // dd([$item_code, $payment_amount]);
        // $obj_commission->set_commission_external_client_payment($item_code, $payment_amount);
        // dd();
        if (!empty($extra_amount)) {
            $t_mount = $payment - ($principle + $interest);
            while ($t_mount > 0) {
                $m_id = LoanProcessModel::where('loanprocess_loanid', $loan_id)->max('id');
                $owepay = LoanProcessModel::find($m_id);

                if ($t_mount == $owepay->loanprocess_owepay) {
                    $reschedule = new Reschedule;
                    $reschedule->delete_payment($m_id);
                    $t_mount = 0;
                } else if ($t_mount < $owepay->loanprocess_owepay) {
                    LoanProcessModel::where('id', $m_id)->decrement('loanprocess_owe', $t_mount);
                    LoanProcessModel::where('id', $m_id)->decrement('loanprocess_owepay', $t_mount);
                    $t_mount = 0;
                } else if ($t_mount > $owepay->loanprocess_owepay) {
                    $t_mount = $t_mount - $owepay->loanprocess_owepay;

                    $reschedule = new Reschedule;
                    $reschedule->delete_payment($m_id);
                }
            }
        }

        if ($pay == $payment || !empty($extra_amount)) {
            $data = array(
                'loanprocess_interestpay'   => 0,
                'loanprocess_principlepay'  => 0,
                'loanprocess_owepay'        => 0,
                'loanprocess_datepaid'      => $do_date,
                'loanprocess_by'            => $by,
                'loanprocess_invoice'       => $invoice,
                'loanprocess_paid'          => 1,
                'loanprocess_activity'      => 1,
                'loanprocess_note'          => $remark,
            );
            LoanProcessModel::where('id', $id)->update($data);

            LoanModel::where('id', $loan_id)->decrement('loan_amountos', $principle);
            LoanModel::where('id', $loan_id)->increment('loan_percentpay', $load_payment_percent);

            $data = array(
                'loanpaid_processid'    => $id,
                'loanpaid_payment'      => date('Y-m-d', strtotime($datepayment)),
                'loanpaid_interest'     => $interest,
                'loanpaid_principle'    => $principle,
                'loanpaid_penalty'      => $penalty,
                'loanpaid_total'        => $payment,
                'loanpaid_by'           => $by,
                'loanpaid_invoice'      => $invoice,
                'loanpaid_type'         => 1,
                'loanpaid_remark'       => $remark,
                'loanpaid_createdate'   => $do_date,
                'loandpaid_bankacc' => $bank_list,
                'loanpaid_penalty_option' => $option
            );
            LoanPaidModel::insert($data);

            $this->set_status_loan_payment_completed($loan_id);
            $des = $this->set_payment_description($id);

            $journal = new JournalAccountingModel();

            $journal->journal_parentid          = 0;
            $journal->journal_acccode           = $bank_list;
            $journal->journal_type              = 12;
            $journal->journal_debit             = $payment;
            $journal->journal_transactiondate   = $do_date;
            $journal->journal_paydate           = date('Y-m-d', strtotime($datepayment));
            $journal->journal_des               = ($des . " (Payment)");
            $journal->journal_by                = $by;
            $journal->journal_currency          = 1;
            $journal->journal_referenceid       = $id;
            $journal->branch_id                 = $branch_id;
            $journal->save();

            $journal_id = $journal->id;

            //            $data1 = array(
            //                'journal_parentid'          => $journal_id,
            //                'journal_acccode'           => 11000,
            //                'journal_type'              => 12,
            //                'journal_credit'            => $payment,
            //                'journal_transactiondate'   => $do_date,
            //                'journal_paydate'           => date('Y-m-d', strtotime($datepayment)),
            //                'journal_des'               => ($des . " (Payment)"),
            //                'journal_by'                => $by,
            //                'journal_currency'          => 1,
            //                'journal_referenceid'       => $id,
            //                'branch_id'                 => $branch_id
            //            );
            //            JournalModel::insert($data1);

            if ($interest != 0) {

                $data3 = array(

                    'journal_parentid'          => $journal_id,
                    'journal_acccode'           => $bank_list,
                    'journal_type'              => 40,
                    'journal_credit'            => $interest,
                    'journal_transactiondate'   => $do_date,
                    'journal_paydate'           => date('Y-m-d', strtotime($datepayment)),
                    'journal_des'               => ($des . " (Interest)"),
                    'journal_by'                => $by,
                    'journal_currency'          => 1,
                    'journal_referenceid'       => $id,
                    'branch_id'       => $branch_id
                );
                JournalAccountingModel::insert($data3);
            }
            if (!empty($fee_charge)) {
                $SaleInfo=SaleStockDetailModel::join("nso007_item_stock","nso007_item_stock.id","nso007_sale_detail_stock.saledetail_itemid")->join("nso007_project_stock","nso007_item_stock.item_projectid","nso007_project_stock.id")->join("nso007_category_stock","nso007_category_stock.id","nso007_item_stock.item_categoryid")->where('saledetail_saleid', $sale_id)->select("nso007_item_stock.*","nso007_category_stock.*","nso007_project_stock.project_name","nso007_project_stock.id as pro_id")->first();

                $j=JournalAccountingModel::select(DB::raw("Max(journal_tran_id) as last_num"))->first();
                $Digit=9;
                $increas = $j->last_num+1;
                (string)$increas;
                while(strlen($increas) < $Digit){
                    $increas = "0".$increas;
                }
                $inv_voucher='V-'.$increas;

                $journal=new JournalAccountingModel;
                $journal->branch_id=1;
                $journal->journal_parentid=0;
                $journal->journal_type=5;
                $journal->journal_acccode=11001;
                $journal->voucher_type=2;
                $journal->voucher_ref=$inv_voucher;
                $journal->journal_des="Fee Charge";
                $journal->journal_debit=$fee_charge;
                $journal->journal_credit=0;
                $journal->journal_tran_id=$j->last_num+1;
                $journal->journal_transactiondate=$do_date;
                $journal->journal_paydate=date('Y-m-d', strtotime($datepayment));
                $journal->journal_currency=1;
                $journal->journal_referenceid=$id;
                $journal->pay_for=$SaleInfo->pro_id;
                $journal->journal_by=$by;
                $journal->save();



            }


            if (!empty($penalty) && $penalty > 0) {
                //
                if ($option == 1) {
                    $data_penalty = array(
                        'journal_parentid'          => $journal_id,
                        'journal_acccode'           => $bank_list,
                        'journal_type'              => 16,
                        'journal_debit'             => $penalty,
                        'journal_transactiondate'   => $do_date,
                        'journal_paydate'           => date('Y-m-d', strtotime($datepayment)),
                        'journal_des'               => ($des . " (Penalty)"),
                        'journal_by'                => $by,
                        'journal_currency'          => 1,
                        'journal_referenceid'       => $id
                    );
                    JournalAccountingModel::insert($data_penalty);
                    DB::table('nso007_loan_process')->where('id', $id)->update([
                        'penalty_paid' => 0
                    ]);
                } else if ($option == 2) {
                    DB::table('nso007_loan_process')->where('id', $id)->update([
                        'penalty_paid' => 0
                    ]);
                    DB::table('nso007_loan_process')->where('id', $id + 1)->update([
                        'penalty_paid' => $penalty
                    ]);
                }
            }
        } else if ($payment < $pay) {

            $data = array(
                'loanprocess_interestpay'   => 0,
                'loanprocess_datepaid'      => $do_date,
                'loanprocess_by'            => $by,
                'loanprocess_invoice'       => $invoice,
                'loanprocess_paid'          => 2,
                'loanprocess_activity'      => 1,
                'loanprocess_note'          => $remark
            );
            LoanProcessModel::where('id', $id)->update($data);
            LoanProcessModel::where('id', $id)->decrement('loanprocess_principlepay', $payment);
            LoanProcessModel::where('id', $id)->decrement('loanprocess_owepay', $payment);
            LoanModel::where('id', $loan_id)->decrement('loan_amountos', $principle);
            LoanModel::where('id', $loan_id)->increment('loan_percentpay', $load_payment_percent);

            $data = array(
                'loanpaid_processid'    => $id,
                'loanpaid_payment'      => date('Y-m-d', strtotime($datepayment)),
                'loanpaid_interest'     => $interest,
                'loanpaid_principle'    => $principle,
                'loanpaid_penalty'      => $penalty,
                'loanpaid_total'        => $payment,
                'loanpaid_by'           => $by,
                'loanpaid_invoice'      => $invoice,
                'loanpaid_type'         => 1,
                'loanpaid_remark'       => $remark,
                'loanpaid_createdate'   => $do_date,
                'loandpaid_bankacc' => $bank_list,
                'loanpaid_penalty_option' => $option
            );
            LoanPaidModel::insert($data);
            $this->set_status_loan_payment_completed($loan_id);

            $des = $this->set_payment_description($id);

            if (!empty($fee_charge)) {
                $SaleInfo=SaleStockDetailModel::join("nso007_item_stock","nso007_item_stock.id","nso007_sale_detail_stock.saledetail_itemid")->join("nso007_project_stock","nso007_item_stock.item_projectid","nso007_project_stock.id")->join("nso007_category_stock","nso007_category_stock.id","nso007_item_stock.item_categoryid")->where('saledetail_saleid', $sale_id)->select("nso007_item_stock.*","nso007_category_stock.*","nso007_project_stock.project_name","nso007_project_stock.id as pro_id")->first();

                $j=JournalAccountingModel::select(DB::raw("Max(journal_tran_id) as last_num"))->first();
                $Digit=9;
                $increas = $j->last_num+1;
                (string)$increas;
                while(strlen($increas) < $Digit){
                    $increas = "0".$increas;
                }
                $inv_voucher='V-'.$increas;

                $journal=new JournalAccountingModel;
                $journal->branch_id=1;
                $journal->journal_parentid=0;
                $journal->journal_type=5;
                $journal->journal_acccode=11001;
                $journal->voucher_type=2;
                $journal->voucher_ref=$inv_voucher;
                $journal->journal_des="Fee Charge";
                $journal->journal_debit=$fee_charge;
                $journal->journal_credit=0;
                $journal->journal_tran_id=$j->last_num+1;
                $journal->journal_transactiondate=$do_date;
                $journal->journal_paydate=date('Y-m-d', strtotime($datepayment));
                $journal->journal_currency=1;
                $journal->journal_referenceid=$id;
                $journal->pay_for=$SaleInfo->pro_id;
                $journal->journal_by=$by;
                $journal->save();


            }

            $journal = new JournalAccountingModel;

            $journal->journal_parentid          = 0;
            $journal->journal_acccode           = $bank_list;
            $journal->journal_type              = 12;
            $journal->journal_debit             = $payment;
            $journal->journal_transactiondate   = $do_date;
            $journal->journal_paydate           = date('Y-m-d', strtotime($datepayment));
            $journal->journal_des               = ($des . " (Payment)");
            $journal->journal_by                = $by;
            $journal->journal_currency          = 1;
            $journal->journal_referenceid       = $id;
            $journal->branch_id                 = $branch_id;
            $journal->save();

            $journal_id = $journal->id;

            //            $data1 = array(
            //                'journal_parentid'          => $journal_id,
            //                'journal_acccode'           => 11000,
            //                'journal_type'              => 12,
            //                'journal_credit'            => $payment,
            //                'journal_transactiondate'   => $do_date,
            //                'journal_paydate'           => date('Y-m-d', strtotime($datepayment)),
            //                'journal_des'               => ($des . " (Payment)"),
            //                'journal_by'                => $by,
            //                'journal_currency'          => 1,
            //                'journal_referenceid'       => $id,
            //                'branch_id'       => $branch_id
            //            );
            //            JournalModel::insert($data1);

            if ($interest != 0) {
                $data3 = array(
                    'journal_parentid'          => $journal_id,
                    'journal_acccode'           => $bank_list,
                    'journal_type'              => 40,
                    'journal_credit'            => $interest,
                    'journal_transactiondate'   => $do_date,
                    'journal_paydate'           => date('Y-m-d', strtotime($datepayment)),
                    'journal_des'               => ($des . " (Interest)"),
                    'journal_by'                => $by,
                    'journal_currency'          => 1,
                    'journal_referenceid'       => $id,
                    'branch_id'                 => $branch_id
                );
                JournalAccountingModel::insert($data3);
            }
            if (!empty($penalty) && $penalty > 0) {
                if ($option == 1) {
                    $j_penalty = new JournalAccountingModel();
                    $j_penalty->journal_parentid         = 0;
                    $j_penalty->journal_acccode          = $bank_list;
                    $j_penalty->journal_type             = 16;
                    $j_penalty->journal_credit           = $penalty;
                    $j_penalty->journal_transactiondate  = $do_date;
                    $j_penalty->journal_paydate          = date('Y-m-d', strtotime($datepayment));
                    $j_penalty->journal_des              = ($des . " (Penalty)");
                    $j_penalty->journal_by               = $by;
                    $j_penalty->journal_currency         = 1;
                    $j_penalty->journal_referenceid      = $id;
                    $j_penalty->save();
                    //                    $penalty_id = $j_penalty->id;
                    //                    $data_penalty = array(
                    //                        'journal_parentid'          => $penalty_id,
                    //                        'journal_acccode'           => $bank_list,
                    //                        'journal_type'              => 40,
                    //                        'journal_debit'             => $penalty,
                    //                        'journal_transactiondate'   => $do_date,
                    //                        'journal_paydate'           => date('Y-m-d', strtotime($datepayment)),
                    //                        'journal_des'               => ($des . " (Penalty)"),
                    //                        'journal_by'                => $by,
                    //                        'journal_currency'          => 1,
                    //                        'journal_referenceid'       => $id
                    //                    );
                    //                    JournalModel::insert($data_penalty);
                    DB::table('nso007_loan_process')->where('id', $id)->update([
                        'penalty_paid' => 0
                    ]);
                } else {
                    DB::table('nso007_loan_process')->where('id', $id)->update([
                        'penalty_paid' => 0
                    ]);
                    DB::table('nso007_loan_process')->where('id', $id + 1)->update([
                        'penalty_paid' => $penalty
                    ]);
                }
            }
        }
    }

    /**
     *  Condition Next Payment
     */
    public function next_payment_condition($data)
    {
        extract($data);
        $branch_id    = \Branch::branch_id();
        $des = $this->set_payment_description($id);
        // dd($data);
        $check_penalty  = false;
        $final_amount       = 0;
        $first_id           = $id;
        $loan            = LoanModel::find($loan_id);
        $sale_id         = $loan->loan_saleid;
        $sale_stock      = SaleStockModel::find($sale_id);
        $item_cost       = $sale_stock->sale_amount - $sale_stock->sale_discount;
        $penalty_paid    = null;
        $payment         = floatval($payment);
        $agency_type = DB::select("SELECT agency_type
                                FROM nso007_agency_commission 
                                WHERE sale_id=$sale_id");
        if ($agency_type[0]->agency_type == 1) {
            $this->put_commission_payment($id, $principle_payment, $loan_id);
        }
        while (floatval($payment) > 0) {
            $loan_process = DB::table('nso007_loan_process')
                ->where([['id', $id], ['loanprocess_loanid', $loan_id]])
                ->first();

            if (!empty($loan_process)) {

                $principle = $loan_process->loanprocess_principlepay;
                $interest  = $loan_process->loanprocess_interestpay;

                $needed_payment = $loan_process->loanprocess_owepay;
                $needed_payment = floatval($needed_payment);

                $agency_type = DB::select("SELECT agency_type
                                FROM nso007_agency_commission 
                                WHERE sale_id=$sale_id");
                if ($agency_type[0]->agency_type == 2) {
                    $this->put_commission_payment($id, $principle, $loan_id);
                }

                if (floatval($payment) >= floatval($needed_payment)) {
                    $payment -= $needed_payment;
                    DB::table('nso007_loan_process')->where([['id', $id], ['loanprocess_loanid', $loan_id]])->update([
                        'loanprocess_activity'      => 1,
                        'loanprocess_datepaid'      => $do_date,
                        'loanprocess_by'            => $by,
                        'loanprocess_owepay'        => 0,
                        'loanprocess_paid'          => 1,
                        'loanprocess_invoice'       => $invoice,
                        'loanprocess_note'          => $remark,
                        'loanprocess_interestpay'   => 0,
                        'loanprocess_principlepay'  => 0,
                        'penalty_paid'              => $penalty_paid
                    ]);

                    DB::table('nso007_loan_paid')->insert([
                        'loanpaid_processid'    => $id,
                        'loanpaid_payment'      => date('Y-m-d', strtotime($datepayment)),
                        'loanpaid_interest'     => $interest,
                        'loanpaid_principle'    => $principle,
                        'loanpaid_penalty'      => $penalty,
                        'loanpaid_total'        => $needed_payment,
                        'loanpaid_by'           => $by,
                        'loanpaid_invoice'      => $invoice,
                        'loanpaid_type'         => 1,
                        'loanpaid_remark'       => $remark,
                        'loanpaid_createdate'   => $do_date,
                        'loandpaid_bankacc' => $bank_list,
                        'loanpaid_penalty_option' => $option
                    ]);
                    //update percent pay

                    $loan_payment_percent   = 100 * floatval($principle) / $item_cost;
                    DB::table('nso007_loan')->update([
                        'loan_percentpay' => DB::raw("loan_percentpay+$loan_payment_percent")
                    ]);
                    //journal
                    DB::table('nso007_journal_accounting')
                        ->insert([
                            'branch_id'             => $branch_id,
                            'journal_parentid'      => 0,
                            'journal_type'          => 12,
                            'journal_acccode'       => $bank_list,
                            'journal_des'           => ($des . " (Payment)"),
                            'journal_debit'         => $needed_payment,
                            'journal_credit'        => 0,
                            'journal_paydate'       => date('Y-m-d'),
                            'journal_currency'      => 1,
                            'journal_referenceid'   => $id,
                            'journal_by'            => $by
                        ]);
                    if (!empty($fee_charge)) {
                        $SaleInfo=SaleStockDetailModel::join("nso007_item_stock","nso007_item_stock.id","nso007_sale_detail_stock.saledetail_itemid")->join("nso007_project_stock","nso007_item_stock.item_projectid","nso007_project_stock.id")->join("nso007_category_stock","nso007_category_stock.id","nso007_item_stock.item_categoryid")->where('saledetail_saleid', $sale_id)->select("nso007_item_stock.*","nso007_category_stock.*","nso007_project_stock.project_name","nso007_project_stock.id as pro_id")->first();

                        $j=JournalAccountingModel::select(DB::raw("Max(journal_tran_id) as last_num"))->first();
                        $Digit=9;
                        $increas = $j->last_num+1;
                        (string)$increas;
                        while(strlen($increas) < $Digit){
                            $increas = "0".$increas;
                        }
                        $inv_voucher='V-'.$increas;

                        $journal=new JournalAccountingModel;
                        $journal->branch_id=1;
                        $journal->journal_parentid=0;
                        $journal->journal_type=5;
                        $journal->journal_acccode=11001;
                        $journal->voucher_type=2;
                        $journal->voucher_ref=$inv_voucher;
                        $journal->journal_des="Fee Charge";
                        $journal->journal_debit=$fee_charge;
                        $journal->journal_credit=0;
                        $journal->journal_tran_id=$j->last_num+1;
                        $journal->journal_transactiondate=$do_date;
                        $journal->journal_paydate=date('Y-m-d', strtotime($datepayment));
                        $journal->journal_currency=1;
                        $journal->journal_referenceid=$id;
                        $journal->pay_for=$SaleInfo->pro_id;
                        $journal->journal_by=$by;
                        $journal->save();


                    }

                    //                    $parent_id = JournalModel::max('id');
                    //
                    //                    DB::table('nso007_journal')
                    //                        ->insert([
                    //                            'branch_id'             => $branch_id,
                    //                            'journal_parentid'      => $parent_id,
                    //                            'journal_type'          => 12,
                    //                            'journal_acccode'       => 41000,
                    //                            'journal_des'           => $des,
                    //                            'journal_debit'         => 0,
                    //                            'journal_credit'        => $principle,
                    //                            'journal_paydate'       => date('Y-m-d'),
                    //                            'journal_currency'      => 1,
                    //                            'journal_referenceid'   => $id,
                    //                            'journal_by'            => $by
                    //                        ]);
                    //
                    //                    DB::table('nso007_journal')
                    //                        ->insert([
                    //                            'branch_id'             => $branch_id,
                    //                            'journal_parentid'      => $parent_id,
                    //                            'journal_type'          => 12,
                    //                            'journal_acccode'       => 41004,
                    //                            'journal_des'           => $des,
                    //                            'journal_debit'         => 0,
                    //                            'journal_credit'        => $interest,
                    //                            'journal_paydate'       => date('Y-m-d'),
                    //                            'journal_currency'      => 1,
                    //                            'journal_referenceid'   => $id,
                    //                            'journal_by'            => $by
                    //                        ]);
                } else {

                    DB::table('nso007_loan_process')->where([['id', $id], ['loanprocess_loanid', $loan_id]])
                        ->update([
                            'loanprocess_activity'      => 2,
                            'loanprocess_datepaid'      => $do_date,
                            'loanprocess_by'            => $by,
                            'loanprocess_owepay'        => DB::raw("loanprocess_owepay-$payment"),
                            'loanprocess_paid'          => 2,
                            'loanprocess_invoice'       => $invoice,
                            'loanprocess_note'          => $remark,
                            'loanprocess_principlepay'  => DB::raw("loanprocess_principlepay-$payment")
                        ]);

                    DB::table('nso007_loan_paid')->insert([
                        'loanpaid_processid'    => $id,
                        'loanpaid_payment'      => date('Y-m-d', strtotime($datepayment)),
                        'loanpaid_interest'     => $interest,
                        'loanpaid_principle'    => $principle,
                        'loanpaid_penalty'      => $penalty,
                        'loanpaid_total'        => $payment,
                        'loanpaid_by'           => $by,
                        'loanpaid_invoice'      => $invoice,
                        'loanpaid_type'         => 1,
                        'loanpaid_remark'       => $remark,
                        'loanpaid_createdate'   => $do_date,
                        'loandpaid_bankacc' => $bank_list,
                        'loanpaid_penalty_option' => $option
                    ]);

                    //update percent pay
                    $loan_payment_percent   = 100 * floatval($payment) / $item_cost;

                    DB::table('nso007_loan')->update([
                        'loan_percentpay' => DB::raw("loan_percentpay+$loan_payment_percent")
                    ]);
                    //journal
                    //                    DB::table('nso007_journal')
                    //                        ->insert([
                    //                            'branch_id'             => $branch_id,
                    //                            'journal_parentid'      => 0,
                    //                            'journal_type'          => 12,
                    //                            'journal_acccode'       => 11001,
                    //                            'journal_des'           => $des,
                    //                            'journal_debit'         => $payment,
                    //                            'journal_credit'        => 0,
                    //                            'journal_paydate'       => date('Y-m-d'),
                    //                            'journal_currency'      => 1,
                    //                            'journal_referenceid'   => $id,
                    //                            'journal_by'            => $by
                    //                        ]);
                    //
                    //                    $parent_id = JournalModel::max('id');
                    //
                    //                    DB::table('nso007_journal')
                    //                        ->insert([
                    //                            'branch_id'             => $branch_id,
                    //                            'journal_parentid'      => $parent_id,
                    //                            'journal_type'          => 12,
                    //                            'journal_acccode'       => 11003,
                    //                            'journal_des'           => $des,
                    //                            'journal_debit'         => 0,
                    //                            'journal_credit'        => $payment,
                    //                            'journal_paydate'       => date('Y-m-d'),
                    //                            'journal_currency'      => 1,
                    //                            'journal_referenceid'   => $id,
                    //                            'journal_by'            => $by
                    //                        ]);
                    $payment = 0;
                    //check if check if has penalty payment and it is needed to be paid at this step
                    if ($penalty && $penalty > 0) {
                        if ($option == 1) {
                            //
                            DB::table('nso007_journal_accounting')->insert([
                                'branch_id'         => $branch_id,
                                'journal_parentid'  => 0,
                                'journal_type'      => 16,
                                'journal_acccode'   => $bank_list,
                                'voucher_type'      => 1,
                                'journal_debit'     => 0,
                                'journal_credit'    => $penalty,
                                'journal_transactiondate'   => date('Y-m-d H:i:s A'),
                                'journal_paydate'       => date('Y-m-d', strtotime($datepayment)),
                                'journal_referenceid'   => $first_id,
                                'journal_by' => $by,
                                'journal_des' => ($des . " (Penalty)")
                            ]);
                            //                            $max_journal_id = JournalModel::max('id');
                            //                            DB::table('nso007_journal')->insert([
                            //                                'branch_id'         => $branch_id,
                            //                                'journal_parentid'  => $max_journal_id,
                            //                                'journal_type'      => 40,
                            //                                'journal_acccode'   => 11001,
                            //                                'voucher_type'      => 1,
                            //                                'journal_debit'     => $penalty,
                            //                                'journal_credit'    => 0,
                            //                                'journal_transactiondate'   => date('Y-m-d H:i:s A'),
                            //                                'journal_paydate'       => date('Y-m-d', strtotime($datepayment)),
                            //                                'journal_referenceid'   => $first_id,
                            //                                'journal_by'        => $by,
                            //                                'journal_des'       => ($des . " (Penalty)")
                            //                            ]);
                        } else if ($option == 2) {
                            DB::table('nso007_loan_process')->where('id', $first_id)
                                ->update([
                                    'penalty_paid' => null
                                ]);
                            DB::table('nso007_loan_process')->where('id', $id)
                                ->update([
                                    'penalty_paid' => $penalty
                                ]);
                        }
                        $check_penalty = true;
                    }
                }

                $id++;
            }
            if ($payment <= 0) {
                break;
            }
        }

        //check if has penalty payment
        if ($check_penalty == false) {
            if ($option == 1) {

                DB::table('nso007_journal_accounting')->insert([
                    'branch_id'         => $branch_id,
                    'journal_parentid'  => 0,
                    'journal_type'      => 16,
                    'journal_acccode'   => $bank_list,
                    'voucher_type'      => 1,
                    'journal_debit'     => 0,
                    'journal_credit'    => $penalty,
                    'journal_transactiondate'   => date('Y-m-d H:i:s A'),
                    'journal_paydate'       => date('Y-m-d', strtotime($datepayment)),
                    'journal_referenceid'   => $id,
                    'journal_by' => $by,
                    'journal_des' => ($des . " (Penalty)")
                ]);

                //                $max_journal_id = JournalModel::max('id');
                //
                //                DB::table('nso007_journal')->insert([
                //                    'branch_id'         => $branch_id,
                //                    'journal_parentid'  => $max_journal_id,
                //                    'journal_type'      => 40,
                //                    'journal_acccode'   => 11001,
                //                    'voucher_type'      => 1,
                //                    'journal_debit'     => $penalty,
                //                    'journal_credit'    => 0,
                //                    'journal_transactiondate'   => date('Y-m-d H:i:s A'),
                //                    'journal_paydate'       => date('Y-m-d', strtotime($datepayment)),
                //                    'journal_referenceid'   => $id,
                //                    'journal_by'        => $by,
                //                    'journal_des'       => ($des . " (Penalty)")
                //                ]);

            } else if ($option == 2) {
                DB::table('nso007_loan_process')->where('id', $first_id)
                    ->update([
                        'penalty_paid' => null
                    ]);
                DB::table('nso007_loan_process')->where('id', $id)
                    ->update([
                        'penalty_paid' => $penalty
                    ]);
            }
        }
    }
    /**
     *  Update status loan completed
     */
    public function set_status_loan_payment_completed($id)
    {
        $amount_os = LoanModel::select('loan_amountos')->find($id);
        if (empty($amount_os->loan_amountos) || $amount_os->loan_amountos == 0 || $amount_os->loan_amountos < 0) {
            LoanModel::where('id', $id)->update(['loan_status' => 2, 'loan_enddate' => date('Y-m-d')]);
        }
    }
    /**
     *  Create description for payment
     */
    public function set_payment_description($id)
    {
        $data = DB::select("
            SELECT
            item.item_name AS item_des, 
            item.item_house AS item_code,
            lprocess.loanprocess_no AS lpro_des,
            project.project_name AS project_code,
            item_group.item_group_name AS group_name,
            item_zone.item_zone_name AS zone_name
            FROM nso007_loan_process AS lprocess
            LEFT JOIN nso007_loan AS loan ON lprocess.loanprocess_loanid = loan.id
            LEFT JOIN nso007_sale_detail_stock AS stock ON loan.loan_saleid = stock.saledetail_saleid
            LEFT JOIN nso007_item_stock AS item ON stock.saledetail_itemid = item.id
            LEFT JOIN nso007_project_stock AS project ON item.item_projectid = project.id
            LEFT JOIN nso007_item_group AS item_group ON item.item_groupid = item_group.id
            LEFT JOIN nso007_item_zone AS item_zone ON item.item_zone_id = item_zone.id
            WHERE lprocess.id = $id
        ");
        $description = $data[0]->project_code . "-" . $data[0]->group_name . "-" . $data[0]->zone_name . "(" . $data[0]->item_code . ")" . ', Step: ' . $data[0]->lpro_des;
        return $description;
    }
    /**
     *  Put commission when making payment
     */
    public function put_commission_payment($proccess_id, $process_payment, $loan_id)
    {
        $obj_agency_commis  = new AgencyCommission;
        // MENG PAY
        $amount_payment     = $process_payment;
        $loan_process_id    = $proccess_id;
        $amount             = $this->get_loan_paid_amount($loan_id);
        // MENG COST
        $amount_loan_cost   = $amount->loan_amount;
        $amount_due         = $amount->loan_amountos;
        // MENG PAID
        $amount_paid        = $amount_loan_cost - $amount->loan_discount - $amount_due;
        // MENG PAID + PAYMENT
        $sum_paid_payment   = $amount_paid + $amount_payment;

        $paid_amount_percent = ($amount_paid * 100 / $amount_loan_cost); //paid %

        $amount_payment_percentage = ($amount_payment * 100 / $amount_loan_cost); //pay %

        $sum_percentage = $paid_amount_percent + $amount_payment_percentage; //sum pay and paid

        $laon_id_1 = $loan_id;
        $data = LoanModel::where('id', $laon_id_1)->first();

        $sale_stock = SaleStockModel::where('id', $data->loan_saleid)->first();
        $items_price = ($sale_stock->sale_amount - $sale_stock->sale_discount);
        //        $sale_amount = $sale_stock->sale_amount;
        //        $agency_id = $sale_stock->agency_id;
        $commission = CommissionModel::where('sale_id', $sale_stock->id)->where('agency_status', 'Sale')->first();
        $item_stock = ItemModel::where('id', $commission->item_id)->first();

        $commission_list = CommissionItemModel::where('com_list_sale_id', $commission->sale_id)->get();
        if ($commission_list != null) {
            foreach ($commission_list as $val) {
                $commission_pay = $this->calculate_payment_commission($commission->commission, $items_price, $amount_paid, $amount_payment, $val->amount, $commission->commis_condition, $commission->condition);
                $agency_acc = $this->find_agency_account_number($val->agency_id);
                $commis_pust = number_format($commission_pay['balance'] - $val->receive, 4);

                if ($commis_pust > 0) {
                    $this->put_commission_to_report($item_stock->id, $commis_pust);
                    $this->increment_funds_balance($val->agency_id, $commis_pust, $item_stock->item_name, $agency_acc);
                    $this->increment_commission_receive($val->agency_id, $commis_pust, $val->id);
                }
            }
        }
    }
    /**
     *  Put commission when making payment
     */
    public function put_commission_payment_group($proccess_id, $process_payment, $loan_id)
    {
        $obj_agency_commis  = new AgencyCommission;
        // MENG PAY
        $amount_payment     = $process_payment;
        $loan_process_id    = $proccess_id;
        $amount             = $this->get_loan_paid_amount($loan_id);
        // MENG COST
        $amount_loan_cost   = $amount->loan_amount;
        $amount_due         = $amount->loan_amountos;
        // MENG PAID
        $amount_paid        = $amount_loan_cost - $amount->loan_discount - $amount_due;
        // MENG PAID + PAYMENT
        $sum_paid_payment   = $amount_paid + $amount_payment;

        $paid_amount_percent = ($amount_paid * 100 / $amount_loan_cost); //paid %

        $amount_payment_percentage = ($amount_payment * 100 / $amount_loan_cost); //pay %

        $sum_percentage = $paid_amount_percent + $amount_payment_percentage; //sum pay and paid

        $laon_id_1 = $loan_id;
        $data = LoanModel::where('id', $laon_id_1)->first();

        $sale_stock = SaleStockModel::where('id', $data->loan_saleid)->first();
        $items_price = ($sale_stock->sale_amount - $sale_stock->sale_discount);
        //        $sale_amount = $sale_stock->sale_amount;
        //        $agency_id = $sale_stock->agency_id;
        $commission = CommissionModel::where('sale_id', $sale_stock->id)->where('agency_status', 'Sale')->first();
        $item_stock = ItemModel::where('id', $commission->item_id)->first();

        $commission_list = CommissionItemModel::where('com_list_sale_id', $commission->sale_id)->get();
        if ($commission_list != null) {
            foreach ($commission_list as $val) {
                $commission_pay = $this->calculate_payment_commission($commission->commission, $items_price, $amount_paid, $amount_payment, $val->amount, $val->commis_condition, $val->condition);
                $agency_acc = $this->find_agency_account_number($val->agency_id);
                $commis_pust = number_format($commission_pay['balance'] - $val->receive, 4);

                if ($commis_pust > 0) {
                    $this->put_commission_to_report($item_stock->id, $commis_pust);
                    $this->increment_funds_balance($val->agency_id, $commis_pust, $item_stock->item_name, $agency_acc);
                    $this->increment_commission_receive($val->agency_id, $commis_pust, $val->id);
                }
            }
        }
    }

    public function put_commission_when_making_payment($process_id, $process_payment, $loan_id)
    {
        $obj_agency_commis  = new AgencyCommission;
        // MENG PAY
        $amount_payment     = $process_payment;
        $loan_process_id    = $process_id;
        $amount             = $this->get_loan_paid_amount($loan_id);
        // MENG COST
        $amount_loan_cost   = $amount->loan_amount;
        $amount_due         = $amount->loan_amountos;
        // MENG PAID
        $amount_paid        = $amount_loan_cost - $amount->loan_discount - $amount_due;

        // MENG PAID + PAYMENT
        $sum_paid_payment   = $amount_paid + $amount_payment;

        $paid_amount_percent = ($amount_paid * 100 / $amount_loan_cost); //paid %

        $amount_payment_percentage = ($amount_payment * 100 / $amount_loan_cost); //pay %

        $sum_percentage = $paid_amount_percent + $amount_payment_percentage; //sum pay and paid

        $laon_id_1 = $loan_id;

        $data_2 = DB::select("SELECT loan_saleid FROM nso007_loan WHERE id = $laon_id_1");
        $sale_id_1 = $data_2[0]->loan_saleid;

        $data_3 = DB::select("SELECT sale_amount, agency_id FROM nso007_sale_stock WHERE id = $sale_id_1");
        $sale_amount_1      = $data_3[0]->sale_amount;
        $agency_id_1        = $data_3[0]->agency_id;

        $data_4 = DB::select("SELECT id FROM nso007_agency_commission WHERE sale_id = $sale_id_1");
        $commission_id = $data_4[0]->id;

        $data_5 = DB::select("SELECT saledetail_itemid FROM nso007_sale_detail_stock WHERE saledetail_saleid = $sale_id_1");
        $item_id = $data_5[0]->saledetail_itemid;

        $data_6 = DB::select("SELECT item_name FROM nso007_item_stock WHERE id = $item_id");
        $item_name = $data_6[0]->item_name;

        $get_parent = DB::select("
            SELECT
            level1.id AS level_1_id,
            level2.id AS level_2_id,
            level3.id AS level_3_id,
            level4.id AS level_4_id,
            level5.id AS level_5_id,
            level6.id AS level_6_id
            
            FROM users level1
            
            LEFT JOIN users level2 ON level1.parent_id = level2.id
            LEFT JOIN users level3 ON level2.parent_id = level3.id
            LEFT JOIN users level4 ON level3.parent_id = level4.id
            LEFT JOIN users level5 ON level4.parent_id = level5.id
            LEFT JOIN users level6 ON level5.parent_id = level6.id
            WHERE level1.id = $agency_id_1
        ");

        $parent = [];

        empty($get_parent[0]->level_1_id) ?: $parent['parent_lvl_1_id'] = $get_parent[0]->level_1_id;
        empty($get_parent[0]->level_2_id) ?: $parent['parent_lvl_2_id'] = $get_parent[0]->level_2_id;
        empty($get_parent[0]->level_3_id) ?: $parent['parent_lvl_3_id'] = $get_parent[0]->level_3_id;
        empty($get_parent[0]->level_4_id) ?: $parent['parent_lvl_4_id'] = $get_parent[0]->level_4_id;
        empty($get_parent[0]->level_5_id) ?: $parent['parent_lvl_5_id'] = $get_parent[0]->level_5_id;
        empty($get_parent[0]->level_6_id) ?: $parent['parent_lvl_6_id'] = $get_parent[0]->level_6_id;

        $count_parent = count($parent);

        if ($count_parent == 6) {

            $lvl1__id = $parent['parent_lvl_1_id'];
            $lvl2__id = $parent['parent_lvl_2_id'];
            $lvl3__id = $parent['parent_lvl_3_id'];
            $lvl4__id = $parent['parent_lvl_4_id'];
            $lvl5__id = $parent['parent_lvl_5_id'];
            $lvl6__id = $parent['parent_lvl_6_id'];

            $lvl1_item_id       = $this->get_id_commission_list($lvl1__id, $commission_id);
            $lvl1_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl1_item_id);
            $lvl1_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl1_item_id);

            $lvl2_item_id       = $this->get_id_commission_list($lvl2__id, $commission_id);
            $lvl2_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl2_item_id);
            $lvl2_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl2_item_id);

            $lvl3_item_id       = $this->get_id_commission_list($lvl3__id, $commission_id);
            $lvl3_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl3_item_id);
            $lvl3_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl3_item_id);

            $lvl4_item_id       = $this->get_id_commission_list($lvl4__id, $commission_id);
            $lvl4_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl4_item_id);
            $lvl4_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl4_item_id);

            $lvl5_item_id       = $this->get_id_commission_list($lvl5__id, $commission_id);
            $lvl5_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl5_item_id);
            $lvl5_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl5_item_id);

            $lvl6_item_id       = $this->get_id_commission_list($lvl6__id, $commission_id);
            $lvl6_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl6_item_id);
            $lvl6_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl6_item_id);

            $commission_level1 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 1, $lvl1_commission, $lvl1_condition);
            $commission_level2 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 2, $lvl2_commission, $lvl2_condition);
            $commission_level3 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 3, $lvl3_commission, $lvl3_condition);
            $commission_level4 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 4, $lvl4_commission, $lvl4_condition);
            $commission_level5 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 5, $lvl5_commission, $lvl5_condition);
            $commission_level6 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 6, $lvl6_commission, $lvl6_condition);

            $lvl1_account_number = $this->get_funds_account_number($lvl1__id);
            $lvl2_account_number = $this->get_funds_account_number($lvl2__id);
            $lvl3_account_number = $this->get_funds_account_number($lvl3__id);
            $lvl4_account_number = $this->get_funds_account_number($lvl4__id);
            $lvl5_account_number = $this->get_funds_account_number($lvl5__id);
            $lvl6_account_number = $this->get_funds_account_number($lvl6__id);

            $lvl1 = $this->put_commission_to_report($lvl1_item_id, $commission_level1);
            if (!empty($commission_level1)) {
                $this->increment_funds_balance($lvl1__id, $commission_level1, $item_name, $lvl1_account_number);
                $this->increment_commission_receive($lvl1__id, $commission_level1, $commission_id);
            }

            $lvl2 = $this->put_commission_to_report($lvl2_item_id, $commission_level2);
            if (!empty($commission_level2)) {
                $this->increment_funds_balance($lvl2__id, $commission_level2, $item_name, $lvl2_account_number);
                $this->increment_commission_receive($lvl2__id, $commission_level2, $commission_id);
            }

            $lvl3 = $this->put_commission_to_report($lvl3_item_id, $commission_level3);
            if (!empty($commission_level3)) {
                $this->increment_funds_balance($lvl3__id, $commission_level3, $item_name, $lvl3_account_number);
                $this->increment_commission_receive($lvl3__id, $commission_level3, $commission_id);
            }

            $lvl4 = $this->put_commission_to_report($lvl4_item_id, $commission_level4);
            if (!empty($commission_level4)) {
                $this->increment_funds_balance($lvl4__id, $commission_level4, $item_name, $lvl4_account_number);
                $this->increment_commission_receive($lvl4__id, $commission_level4, $commission_id);
            }

            $lvl5 = $this->put_commission_to_report($lvl5_item_id, $commission_level5);
            if (!empty($commission_level5)) {
                $this->increment_funds_balance($lvl5__id, $commission_level5, $item_name, $lvl5_account_number);
                $this->increment_commission_receive($lvl5__id, $commission_level5, $commission_id);
            }

            $lvl6 = $this->put_commission_to_report($lvl6_item_id, $commission_level6);
            if (!empty($commission_level6)) {
                $this->increment_funds_balance($lvl6__id, $commission_level6, $item_name, $lvl6_account_number);
                $this->increment_commission_receive($lvl6__id, $commission_level6, $commission_id);
            }
        } elseif ($count_parent == 5) {
            $lvl1__id = $parent['parent_lvl_1_id'];
            $lvl2__id = $parent['parent_lvl_2_id'];
            $lvl3__id = $parent['parent_lvl_3_id'];
            $lvl4__id = $parent['parent_lvl_4_id'];
            $lvl5__id = $parent['parent_lvl_5_id'];

            $lvl1_item_id       = $this->get_id_commission_list($lvl1__id, $commission_id);
            $lvl1_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl1_item_id);
            $lvl1_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl1_item_id);

            $lvl2_item_id       = $this->get_id_commission_list($lvl2__id, $commission_id);
            $lvl2_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl2_item_id);
            $lvl2_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl2_item_id);

            $lvl3_item_id       = $this->get_id_commission_list($lvl3__id, $commission_id);
            $lvl3_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl3_item_id);
            $lvl3_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl3_item_id);

            $lvl4_item_id       = $this->get_id_commission_list($lvl4__id, $commission_id);
            $lvl4_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl4_item_id);
            $lvl4_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl4_item_id);

            $lvl5_item_id       = $this->get_id_commission_list($lvl5__id, $commission_id);
            $lvl5_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl5_item_id);
            $lvl5_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl5_item_id);

            $commission_level1 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 1, $lvl1_commission, $lvl1_condition);
            $commission_level2 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 2, $lvl2_commission, $lvl2_condition);
            $commission_level3 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 3, $lvl3_commission, $lvl3_condition);
            $commission_level4 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 4, $lvl4_commission, $lvl4_condition);
            $commission_level5 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 5, $lvl5_commission, $lvl5_condition);

            $lvl1_account_number = $this->get_funds_account_number($lvl1__id);
            $lvl2_account_number = $this->get_funds_account_number($lvl2__id);
            $lvl3_account_number = $this->get_funds_account_number($lvl3__id);
            $lvl4_account_number = $this->get_funds_account_number($lvl4__id);
            $lvl5_account_number = $this->get_funds_account_number($lvl5__id);

            $lvl1 = $this->put_commission_to_report($lvl1_item_id, $commission_level1);
            if (!empty($commission_level1)) {
                $this->increment_funds_balance($lvl1__id, $commission_level1, $item_name, $lvl1_account_number);
                $this->increment_commission_receive($lvl1__id, $commission_level1, $commission_id);
            }

            $lvl2 = $this->put_commission_to_report($lvl2_item_id, $commission_level2);
            if (!empty($commission_level2)) {
                $this->increment_funds_balance($lvl2__id, $commission_level2, $item_name, $lvl2_account_number);
                $this->increment_commission_receive($lvl2__id, $commission_level2, $commission_id);
            }

            $lvl3 = $this->put_commission_to_report($lvl3_item_id, $commission_level3);
            if (!empty($commission_level3)) {
                $this->increment_funds_balance($lvl3__id, $commission_level3, $item_name, $lvl3_account_number);
                $this->increment_commission_receive($lvl3__id, $commission_level3, $commission_id);
            }

            $lvl4 = $this->put_commission_to_report($lvl4_item_id, $commission_level4);
            if (!empty($commission_level4)) {
                $this->increment_funds_balance($lvl4__id, $commission_level4, $item_name, $lvl4_account_number);
                $this->increment_commission_receive($lvl4__id, $commission_level4, $commission_id);
            }

            $lvl5 = $this->put_commission_to_report($lvl5_item_id, $commission_level5);
            if (!empty($commission_level5)) {
                $this->increment_funds_balance($lvl5__id, $commission_level5, $item_name, $lvl5_account_number);
                $this->increment_commission_receive($lvl5__id, $commission_level5, $commission_id);
            }
        } elseif ($count_parent == 4) {
            $lvl1__id = $parent['parent_lvl_1_id'];
            $lvl2__id = $parent['parent_lvl_2_id'];
            $lvl3__id = $parent['parent_lvl_3_id'];
            $lvl4__id = $parent['parent_lvl_4_id'];

            $lvl1_item_id       = $this->get_id_commission_list($lvl1__id, $commission_id);
            $lvl1_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl1_item_id);
            $lvl1_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl1_item_id);

            $lvl2_item_id       = $this->get_id_commission_list($lvl2__id, $commission_id);
            $lvl2_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl2_item_id);
            $lvl2_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl2_item_id);

            $lvl3_item_id       = $this->get_id_commission_list($lvl3__id, $commission_id);
            $lvl3_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl3_item_id);
            $lvl3_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl3_item_id);

            $lvl4_item_id       = $this->get_id_commission_list($lvl4__id, $commission_id);
            $lvl4_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl4_item_id);
            $lvl4_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl4_item_id);

            $commission_level1 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 1, $lvl1_commission, $lvl1_condition);
            $commission_level2 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 2, $lvl2_commission, $lvl2_condition);
            $commission_level3 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 3, $lvl3_commission, $lvl3_condition);
            $commission_level4 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 4, $lvl4_commission, $lvl4_condition);

            $lvl1_account_number = $this->get_funds_account_number($lvl1__id);
            $lvl2_account_number = $this->get_funds_account_number($lvl2__id);
            $lvl3_account_number = $this->get_funds_account_number($lvl3__id);
            $lvl4_account_number = $this->get_funds_account_number($lvl4__id);

            $lvl1 = $this->put_commission_to_report($lvl1_item_id, $commission_level1);
            if (!empty($commission_level1)) {
                $this->increment_funds_balance($lvl1__id, $commission_level1, $item_name, $lvl1_account_number);
                $this->increment_commission_receive($lvl1__id, $commission_level1, $commission_id);
            }

            $lvl2 = $this->put_commission_to_report($lvl2_item_id, $commission_level2);
            if (!empty($commission_level2)) {
                $this->increment_funds_balance($lvl2__id, $commission_level2, $item_name, $lvl2_account_number);
                $this->increment_commission_receive($lvl2__id, $commission_level2, $commission_id);
            }

            $lvl3 = $this->put_commission_to_report($lvl3_item_id, $commission_level3);
            if (!empty($commission_level3)) {
                $this->increment_funds_balance($lvl3__id, $commission_level3, $item_name, $lvl3_account_number);
                $this->increment_commission_receive($lvl3__id, $commission_level3, $commission_id);
            }

            $lvl4 = $this->put_commission_to_report($lvl4_item_id, $commission_level4);
            if (!empty($commission_level4)) {
                $this->increment_funds_balance($lvl4__id, $commission_level4, $item_name, $lvl4_account_number);
                $this->increment_commission_receive($lvl4__id, $commission_level4, $commission_id);
            }
        } elseif ($count_parent == 3) {
            $lvl1__id = $parent['parent_lvl_1_id'];
            $lvl2__id = $parent['parent_lvl_2_id'];
            $lvl3__id = $parent['parent_lvl_3_id'];

            $lvl1_item_id       = $this->get_id_commission_list($lvl1__id, $commission_id);
            $lvl1_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl1_item_id);
            $lvl1_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl1_item_id);

            $lvl2_item_id       = $this->get_id_commission_list($lvl2__id, $commission_id);
            $lvl2_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl2_item_id);
            $lvl2_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl2_item_id);

            $lvl3_item_id       = $this->get_id_commission_list($lvl3__id, $commission_id);
            $lvl3_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl3_item_id);
            $lvl3_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl3_item_id);

            $commission_level1 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 1, $lvl1_commission, $lvl1_condition);
            $commission_level2 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 2, $lvl2_commission, $lvl2_condition);
            $commission_level3 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 3, $lvl3_commission, $lvl3_condition);

            $lvl1_account_number = $this->get_funds_account_number($lvl1__id);
            $lvl2_account_number = $this->get_funds_account_number($lvl2__id);
            $lvl3_account_number = $this->get_funds_account_number($lvl3__id);

            $lvl1 = $this->put_commission_to_report($lvl1_item_id, $commission_level1);
            if (!empty($commission_level1)) {
                $this->increment_funds_balance($lvl1__id, $commission_level1, $item_name, $lvl1_account_number);
                $this->increment_commission_receive($lvl1__id, $commission_level1, $commission_id);
            }

            $lvl2 = $this->put_commission_to_report($lvl2_item_id, $commission_level2);
            if (!empty($commission_level2)) {
                $this->increment_funds_balance($lvl2__id, $commission_level2, $item_name, $lvl2_account_number);
                $this->increment_commission_receive($lvl2__id, $commission_level2, $commission_id);
            }

            $lvl3 = $this->put_commission_to_report($lvl3_item_id, $commission_level3);
            if (!empty($commission_level3)) {
                $this->increment_funds_balance($lvl3__id, $commission_level3, $item_name, $lvl3_account_number);
                $this->increment_commission_receive($lvl3__id, $commission_level3, $commission_id);
            }
        } elseif ($count_parent == 2) {
            $lvl1__id = $parent['parent_lvl_1_id'];
            $lvl2__id = $parent['parent_lvl_2_id'];

            $lvl1_item_id       = $this->get_id_commission_list($lvl1__id, $commission_id);
            $lvl1_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl1_item_id);
            $lvl1_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl1_item_id);

            $lvl2_item_id       = $this->get_id_commission_list($lvl2__id, $commission_id);
            $lvl2_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl2_item_id);
            $lvl2_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl2_item_id);

            $commission_level1 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 1, $lvl1_commission, $lvl1_condition);
            $commission_level2 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 2, $lvl2_commission, $lvl2_condition);

            $lvl1_account_number = $this->get_funds_account_number($lvl1__id);
            $lvl2_account_number = $this->get_funds_account_number($lvl2__id);

            $lvl1 = $this->put_commission_to_report($lvl1_item_id, $commission_level1);
            if (!empty($commission_level1)) {
                $this->increment_funds_balance($lvl1__id, $commission_level1, $item_name, $lvl1_account_number);
                $this->increment_commission_receive($lvl1__id, $commission_level1, $commission_id);
            }

            $lvl2 = $this->put_commission_to_report($lvl2_item_id, $commission_level2);
            if (!empty($commission_level2)) {
                $this->increment_funds_balance($lvl2__id, $commission_level2, $item_name, $lvl2_account_number);
                $this->increment_commission_receive($lvl2__id, $commission_level2, $commission_id);
            }
        } elseif ($count_parent == 1) {
            $lvl1__id = $parent['parent_lvl_1_id'];

            $lvl1_item_id       = $this->get_id_commission_list($lvl1__id, $commission_id);
            $lvl1_commission    = $obj_agency_commis->get_commission_in_commission_list($lvl1_item_id);
            $lvl1_condition     = $obj_agency_commis->get_condition_in_commission_list($lvl1_item_id);

            $commission_level1 = $this->calculate_commission_payment($amount_loan_cost, $amount_paid, $amount_payment, 1, $lvl1_commission, $lvl1_condition);

            $lvl1_account_number = $this->get_funds_account_number($lvl1__id);

            $lvl1 = $this->put_commission_to_report($lvl1_item_id, $commission_level1);
            if (!empty($commission_level1)) {
                $this->increment_funds_balance($lvl1__id, $commission_level1, $item_name, $lvl1_account_number);
                $this->increment_commission_receive($lvl1__id, $commission_level1, $commission_id);
            }
        }
    }
    /**
     *  Get loan paid
     */
    public function get_loan_paid_amount($loan_id)
    {
        $data = LoanModel::select('loan_amount', 'loan_discount', 'loan_amountos')->find($loan_id);
        return $data;
    }
    /**
     *  Calculate commission
     */
    public function calculate_commission_payment($cost, $paid, $payment, $level, $commission, $condition)
    {
        $lvl_no = $level;
        $get_deposit_amount = 0;
        $condition_commission   = $cost * $condition / 100;

        if ($lvl_no == 1) {
            $get_commission         = $cost * $commission / 100;
        } elseif ($lvl_no == 2) {
            $get_commission         = $cost * 0.1 / 100;
        } elseif ($lvl_no == 3) {
            $get_commission         = $cost * 0.1 / 100;
        } elseif ($lvl_no == 4) {
            $get_commission         = $cost * 0.1 / 100;
        } elseif ($lvl_no == 5) {
            $get_commission         = $cost * 0.1 / 100;
        } elseif ($lvl_no == 6) {
            $get_commission         = $cost * 0.1 / 100;
        }
        if ($paid < $condition_commission) {
            if (($paid + $payment) <= $condition_commission) {
                $get_deposit = $payment / $condition_commission;
                $get_deposit_amount = $get_commission * $get_deposit;
            } elseif (($paid + $payment) > $condition_commission) {
                $get_deposit = ($condition_commission - $paid) / $condition_commission;
                $get_deposit_amount = $get_commission * $get_deposit;
            }
        }
        return $get_deposit_amount;
    }
    /**
     *  Get funds account number
     */
    public function get_funds_account_number($agency_id)
    {
        $data = DB::select("SELECT account_number FROM nso007_funds WHERE user_id = $agency_id");
        $account_number = $data[0]->account_number;
        return $account_number;
    }
    /**
     *  Get ID commission list
     */
    public function get_id_commission_list($agency_id, $commission_id)
    {
        $data = DB::select("SELECT id FROM nso007_agency_commission_list WHERE agency_id = $agency_id
            AND commission_id = $commission_id");
        $id = $data[0]->id;
        return $id;
    }
    /**
     *  Put commission to report
     */
    public function put_commission_to_report($lvl1_item_id, $commission_level1)
    {
        $data = array(
            'commission_item_id' => $lvl1_item_id,
            'amount' => $commission_level1
        );
        CommissionItemReportModel::insert($data);
    }
    /**
     *  Increment balance funds
     */
    public function increment_funds_balance($agency_id, $commission_amount, $item_name, $account_number)
    {
        $agency_commission = new AgencyCommission;
        $agency_mix = $agency_commission->get_agency_info_in_getcommission($item_name);
        FundsRegisterModel::where('user_id', $agency_id)->increment('balance', $commission_amount);
        FundsRegisterModel::where('user_id', $agency_id)->increment('received​_balance', $commission_amount);
        $balance = FundsRegisterModel::where('user_id', $agency_id)->first()->balance;
        $revenue = new FundsTransactionModel;
        $revenue->operation_type    = 3;
        $revenue->account_number    = $account_number;
        $revenue->amount            = $commission_amount;
        $revenue->balance           = $balance;
        $revenue->request_date      = date('Y-m-d H:i:s A');
        $revenue->remark            = "Get commission from " . $agency_mix . "/" . $item_name;
        $revenue->user_log          = Auth::user()->id;
        $revenue->status            = 1;
        $revenue->save();
    }
    /**
     *  Increment commision agency recieve
     */
    public function increment_commission_receive($agency_id, $commission_amount, $commissionid)
    {
        CommissionItemModel::where('id', $commissionid)
            ->where('agency_id', $agency_id)
            ->increment('receive', $commission_amount);
    }

    /**
     *  Get loan record by id
     */
    public function get_loan_info_record($id)
    {
        $data = LoanModel::find($id);
        return $data;
    }
    /**
     *  Pay Off
     */
    public function client_payment_payoff(Request $request)
    {
        $obj_commission = new Commission;
        $agency_get_commission = new AgencyCommission;
        $loanID     = $request->payoff_loan_id;
        $sale_id    = $agency_get_commission->get_saleid_by_loanid($loanID);
        $reschedule = new Reschedule;
        $reschedule->delete_schedule_payment($loanID);
        $reschedule->client_payment_completed($loanID);

        $des = 'installment: ' . $loanID . ' (pay off)';

        $total_principle    = $request->payoff_amount;
        $total_interest     = 0;
        $total_owe          = $total_principle;

        $data = array(
            'journal_parentid'          => 0,
            'journal_type'              => 11,
            'journal_acccode'           => 10000,
            'journal_des'               => $des,
            'journal_debit'             => $total_owe,
            'journal_transactiondate'   => date('Y-m-d H:i:s A'),
            'journal_paydate'           => date('Y-m-d'),
            'journal_currency'          => 1,
            'journal_referenceid'       => $loanID,
            'journal_by'                => Auth::user()->id,
            'journal_invoice'           => $request->payoff_invoice,
        );
        JournalModel::insert($data);

        $insert_id = JournalModel::orderBy('id', 'desc')->first()->id;

        $data1 = array(
            'journal_parentid'          => $insert_id,
            'journal_type'              => 11,
            'journal_acccode'           => 11000,
            'journal_des'               => $des,
            'journal_credit'            => $total_principle,
            'journal_transactiondate'   => date('Y-m-d H:i:s A'),
            'journal_paydate'           => date('Y-m-d'),
            'journal_currency'          => 1,
            'journal_referenceid'       => $loanID,
            'journal_by'                => Auth::user()->id,
            'journal_invoice'           => $request->payoff_invoice,
        );
        JournalModel::insert($data1);

        $data2 = array(
            'journal_parentid'          => $insert_id,
            'journal_type'              => 11,
            'journal_acccode'           => 40001,
            'journal_des'               => $des,
            'journal_credit'            => $total_interest,
            'journal_transactiondate'   => date('Y-m-d H:i:s A'),
            'journal_paydate'           => date('Y-m-d'),
            'journal_currency'          => 1,
            'journal_referenceid'       => $loanID,
            'journal_by'                => Auth::user()->id,
            'journal_invoice'           => $request->payoff_invoice,
        );
        JournalModel::insert($data2);
        $agency_get_commission->agency_commission_external_project($total_principle, $sale_id);
        $obj_commission->increment_sale_payment_client_external($sale_id, $total_principle);

        \LogActivity::addToLog('Pay Off successfully!');

        return redirect()->route('client-payment-list.index')
            ->with('success', 'Payment paid off successfully!');
    }


    public function calculate_approve_commission($cost, $item, $paid, $commission, $commis_condition, $condition)
    {
        //        $get_deposit_amount = 0;
        //        $condition_commission   = $item * $condition / 100;
        $get_commission         = $cost * $commission / 100;
        $get_paid_per = ($paid * 100) / $item;
        $condition_commission   = $this->check_commission($get_paid_per, $get_commission, $condition, $commis_condition);
        //        if ($paid <= $condition_commission) {
        //            $get_deposit = $paid / $condition_commission;
        //            $get_deposit_amount = $get_commission * $get_deposit;
        //        } elseif ($paid > $condition_commission) {
        //            $get_deposit = ($condition_commission - $paid) / $condition_commission;
        //            $get_deposit_amount = $get_commission * $get_deposit;
        //        }
        return $condition_commission;
    }

    public function calculate_approve_commission_group($cost, $item, $paid, $commission, $commis_condition, $condition)
    {
        //        $get_deposit_amount = 0;
        //        $condition_commission   = $item * $condition / 100;
        $get_commission         = $cost * $commission / 100;
        $get_paid_per = ($paid * 100) / $item;
        $condition_commission   = $this->check_commission($get_paid_per, $commission, $condition, $commis_condition);
        //        if ($paid <= $condition_commission) {
        //            $get_deposit = $paid / $condition_commission;
        //            $get_deposit_amount = $get_commission * $get_deposit;
        //        } elseif ($paid > $condition_commission) {
        //            $get_deposit = ($condition_commission - $paid) / $condition_commission;
        //            $get_deposit_amount = $get_commission * $get_deposit;
        //        }
        return $condition_commission;
    }
    public function calculate_approve_commission_group1($cost, $item, $paid, $commission, $commis_condition, $condition)
    {
        //        $get_deposit_amount = 0;
        //        $condition_commission   = $item * $condition / 100;
        $get_commission         = $cost * $commission / 100;
        $get_paid_per = ($paid * 100) / $item;
        $condition_commission   = $this->check_commission($get_paid_per, $commission, $condition, $commis_condition);
        //        if ($paid <= $condition_commission) {
        //            $get_deposit = $paid / $condition_commission;
        //            $get_deposit_amount = $get_commission * $get_deposit;
        //        } elseif ($paid > $condition_commission) {
        //            $get_deposit = ($condition_commission - $paid) / $condition_commission;
        //            $get_deposit_amount = $get_commission * $get_deposit;
        //        }
        return $condition_commission;
    }
    public function calculate_approve_commission_group2($cost, $item, $paid, $commission, $commis_condition, $condition)
    {
        //        $get_deposit_amount = 0;
        //        $condition_commission   = $item * $condition / 100;
        $get_commission         = $cost * $commission / 100;
        $get_paid_per = ($paid * 100) / $item;
        $condition_commission   = $this->check_commission($get_paid_per, $commission, $condition, $commis_condition);
        //        if ($paid <= $condition_commission) {
        //            $get_deposit = $paid / $condition_commission;
        //            $get_deposit_amount = $get_commission * $get_deposit;
        //        } elseif ($paid > $condition_commission) {
        //            $get_deposit = ($condition_commission - $paid) / $condition_commission;
        //            $get_deposit_amount = $get_commission * $get_deposit;
        //        }
        return $condition_commission;
    }

    public function calculate_approve_commission_group3($cost, $item, $paid, $commission, $commis_condition, $condition)
    {
        //        $get_deposit_amount = 0;
        //        $condition_commission   = $item * $condition / 100;
        $get_commission         = $cost * $commission / 100;
        $get_paid_per = ($paid * 100) / $item;
        $condition_commission   = $this->check_commission($get_paid_per, $commission, $condition, $commis_condition);
        //        if ($paid <= $condition_commission) {
        //            $get_deposit = $paid / $condition_commission;
        //            $get_deposit_amount = $get_commission * $get_deposit;
        //        } elseif ($paid > $condition_commission) {
        //            $get_deposit = ($condition_commission - $paid) / $condition_commission;
        //            $get_deposit_amount = $get_commission * $get_deposit;
        //        }
        return $condition_commission;
    }
    public function calculate_approve_commission_group4($cost, $item, $paid, $commission, $commis_condition, $condition)
    {
        //        $get_deposit_amount = 0;
        //        $condition_commission   = $item * $condition / 100;
        $get_commission         = $cost * $commission / 100;
        $get_paid_per = ($paid * 100) / $item;
        $condition_commission   = $this->check_commission($get_paid_per, $commission, $condition, $commis_condition);
        //        if ($paid <= $condition_commission) {
        //            $get_deposit = $paid / $condition_commission;
        //            $get_deposit_amount = $get_commission * $get_deposit;
        //        } elseif ($paid > $condition_commission) {
        //            $get_deposit = ($condition_commission - $paid) / $condition_commission;
        //            $get_deposit_amount = $get_commission * $get_deposit;
        //        }
        return $condition_commission;
    }

    public function calculate_payment_commission($cost, $item, $paid, $payment, $commission, $commis_condition, $condition)
    {
        //        $get_deposit_amount = 0;
        //        $condition_commission   = $item * $condition / 100;
        $get_paid_per = (($paid + $payment) * 100) / $item;
        $condition_commission   = $this->check_commission_payment($get_paid_per, $commission, $condition, $commis_condition);
        //        if ($paid < $condition_commission) {
        //            if (($paid + $payment) <= $condition_commission) {
        //                $get_deposit = $payment / $condition_commission;
        //                $get_deposit_amount = $get_commission * $get_deposit;
        //            } elseif (($paid + $payment) > $condition_commission) {
        //                $get_deposit = ($condition_commission - $paid) / $condition_commission;
        //                $get_deposit_amount = $get_commission * $get_deposit;
        //            }
        //        }
        return $condition_commission;
    }


    public function calculate_payment_commission_company($cost, $item, $paid, $payment, $commission, $condition, $commis_condition)
    {
        //        $get_deposit_amount = 0;
        //        $condition_commission   = $item * $condition / 100;
        $get_paid_per = (($paid + $payment) * 100) / $item;
        $condition_commission   = $this->check_commission_payment_company($get_paid_per, $commission, $condition, $commis_condition);
        //        if ($paid < $condition_commission) {
        //            if (($paid + $payment) <= $condition_commission) {
        //                $get_deposit = $payment / $condition_commission;
        //                $get_deposit_amount = $get_commission * $get_deposit;
        //            } elseif (($paid + $payment) > $condition_commission) {
        //                $get_deposit = ($condition_commission - $paid) / $condition_commission;
        //                $get_deposit_amount = $get_commission * $get_deposit;
        //            }
        //        }
        return $condition_commission;
    }

    public function find_agency_account_number($agency_id)
    {
        $data = FundsRegisterModel::where('user_id', $agency_id)->first();
        return $data->account_number;
    }
    public function request_cancel($id)
    {
        $id = Crypt::decrypt($id);
        DB::table('nso007_loan')->where('id', $id)->update([
            'loan_cancel_status' => 1
        ]);
        return back()->with('success', 'Your Request to cancel this payment is being processing!');
    }
    public function reject_cancel($id)
    {
        $id = Crypt::decrypt($id);
        DB::table('nso007_loan')->where('id', $id)->update([
            'loan_cancel_status' => null
        ]);
        return back()->with('success', 'Cancel Payment Was Rejected');
    }
    public function approve_cancel($id)
    {
        $id = Crypt::decrypt($id);
        DB::table('nso007_loan')->where('id', $id)->update([
            'loan_cancel_status' => 2
        ]);
        $loan = LoanModel::find($id);
        $sale_id        = $loan->loan_saleid;

        $sale_detail    = SaleStockDetailModel::where('saledetail_saleid', $sale_id)->get();
        foreach ($sale_detail as $detail) {
            DB::table('nso007_item_stock')->where('id', $detail->saledetail_itemid)->update([
                'item_stockstatus' => 1, 'item_salestatus' => 0, 'available' => 1
            ]);
        }

        //delete loan process

        DB::table('nso007_loan_process')
            ->where('loanprocess_loanid', $id)
            ->whereNull('loanprocess_paid')->delete();
        $loan_process = DB::table('nso007_loan_process')->where('loanprocess_loanid', $id)->get();


        \LogActivity::addToLog('Approve Cancel Client Payment');
        return back()->with('success', 'Cancel Payment was Successfully Approved');
    }
    public function delete_loan_process($id)
    {
        $id = Crypt::decrypt($id);

        $loan_process = LoanProcessModel::find($id);
        $paid_amount = $loan_process->loanprocess_owe - $loan_process->loanprocess_owepay;
        DB::table('nso007_loan_process')->where('id', $id)
            ->update([
                'loanprocess_activity'      => null,
                'loanprocess_paid'          => null,
                'loanprocess_datepaid'      => null,
                'loanprocess_by'            => null,
                'loanprocess_interestpay'   => ($loan_process->loanprocess_interest - $loan_process->loanprocess_interestpay),
                'loanprocess_principlepay'  => ($loan_process->loanprocess_principle - $loan_process->loanprocess_principlepay),
                'loanprocess_owepay'        => ($loan_process->loanprocess_owe - $loan_process->loanprocess_owepay)
            ]);
        DB::table('nso007_loan_process')->where('id', $id + 1)
            ->update([
                'penalty_paid'      => 0,
            ]);
        DB::table('nso007_loan_paid')->where('loanpaid_processid', $id)->delete();

        $loan       = LoanModel::find($loan_process->loanprocess_loanid);
        $item_cost  = $loan->loan_amount - $loan->loan_discount;
        $percentage = (100 * $paid_amount) / $item_cost;

        //update loan percentage
        DB::table('nso007_loan')->where('id', $loan->id)->update([
            'loan_percentpay' => DB::raw("loan_percentpay-$percentage")
        ]);

        //delete payment from journal
        DB::table('nso007_journal')->where([['journal_referenceid', $id], ['journal_type', 12]])->delete();
        //delete penalty and interest from journal
        DB::table('nso007_journal')->where([['journal_referenceid', $id], ['journal_type', 40]])->whereIn('journal_acccode', [40002, 11001, 40000])->delete();
        \LogActivity::addToLog('Delete Client Payment on loan Process!');
        return back()->with('success', 'Payment Successfully Deleted');
    }

    public function client_payment_index()
    {
        return view('administrator.client-payment.payment.payment-pending');
    }
    public function client_payment_pending()
    {
        $paid_pending = LoanPaidModel::join('nso007_loan_process', 'nso007_loan_process.id', 'nso007_loan_paid.loanpaid_processid')
            ->join('nso007_loan', 'nso007_loan.id', 'nso007_loan_process.loanprocess_loanid')
            ->join('nso007_sale_stock', 'nso007_sale_stock.id', 'nso007_loan.loan_saleid')
            ->join('nso007_client', 'nso007_client.id', 'nso007_sale_stock.sale_clientid')
            ->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_project_stock', 'nso007_project_stock.id', 'nso007_item_stock.item_projectid')
            ->select(
                'nso007_loan_paid.id as paid_id',
                'nso007_loan_paid.loanpaid_approved',
                'nso007_loan_paid.loanpaid_principle',
                'nso007_loan_paid.loanpaid_total',
                'nso007_loan_paid.created_at',
                'nso007_project_stock.project_name',
                'nso007_item_stock.item_house',
                'nso007_client.client_fullname'
            )
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })->where('nso007_loan_paid.loanpaid_approved', null)->get();
        return Datatables::of($paid_pending)
            ->addIndexColumn()
            //            ->addColumn('status',function ($paid_pending){
            //                if($paid_pending->loanpaid_approved == null)
            //                {
            //                    $btn_action='<a href="#" onclick="approve_payment('.$paid_pending->paid_id.')" title="Approve" class="btn btn-primary btn-xs">Approve</a>';
            //                    return  $btn_action;
            //                }
            //            })
            ->addColumn('loanpaid_principle', function ($paid_pending) {
                return '$ ' . number_format($paid_pending->loanpaid_principle, 2);
            })
            ->addColumn('loanpaid_total', function ($paid_pending) {
                return '$ ' . number_format($paid_pending->loanpaid_total, 2);
            })
            ->addColumn('created_at', function ($paid_pending) {
                return date('Y-m-d', strtotime($paid_pending->created_at));
            })
            ->addColumn('check_id', function ($paid_pending) {
                return '<label class="checkbox-list">
                          <input type="checkbox" class="checkbox" data-id="' . $paid_pending->paid_id . '">
                          <span class="checkmark"></span>
                    </label>';
            })
            ->rawColumns(['check_id' => 'check_id'])->make(true);
    }
    //  get payment
    //    public function get_payment_pending_ajax(Request $request)
    //    {
    //        foreach($request->paid_id as $key => $value)
    //        {
    //            $paid_pending = LoanPaidModel::join('nso007_loan_process','nso007_loan_process.id','nso007_loan_paid.loanpaid_processid')
    //                ->join('nso007_loan','nso007_loan.id','nso007_loan_process.loanprocess_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_project_stock','nso007_project_stock.id','nso007_item_stock.item_projectid')
    //                ->select('nso007_loan_process.id as process_id','nso007_loan_paid.id as paid_id','nso007_loan_paid.loanpaid_approved','nso007_loan_paid.loanpaid_principle',
    //                    'nso007_loan_paid.loanpaid_total','nso007_loan_paid.created_at',
    //                    'nso007_loan_paid.loandpaid_bankacc','nso007_loan_paid.loanpaid_penalty','nso007_project_stock.branch_id'
    //                    ,'nso007_loan_paid.loanpaid_penalty_option as option'
    //                )
    //                ->where('nso007_loan_paid.id',$value)->get();
    //        }
    //        echo json_encode($paid_pending);
    //    }

    public function add_journal_payment($process_id, $bank_list, $payment, $datepayment, $branch_id, $penalty, $do_date)
    {
        $des = $this->set_payment_description($process_id);
        $by = auth()->user()->id;
        $journal = new JournalAccountingModel();
        $journal->journal_parentid          = 0;
        $journal->journal_acccode           = $bank_list;
        $journal->journal_type              = 12;
        $journal->journal_debit             = $payment;
        $journal->journal_transactiondate   = $do_date;
        $journal->journal_paydate           = date('Y-m-d', strtotime($datepayment));
        $journal->journal_des               = ($des . " (Payment)");
        $journal->journal_by                = $by;
        $journal->journal_currency          = 1;
        $journal->journal_referenceid       = $process_id;
        $journal->branch_id                 = $branch_id;
        $journal->save();
        $parent_id = JournalAccountingModel::max('id');
        $data_penalty = array(
            'journal_parentid'          => $parent_id,
            'journal_acccode'           => $bank_list,
            'journal_type'              => 16,
            'journal_debit'             => $penalty,
            'journal_transactiondate'   => $do_date,
            'journal_paydate'           => date('Y-m-d', strtotime($datepayment)),
            'journal_des'               => ($des . " (Penalty)"),
            'journal_by'                => $by,
            'journal_currency'          => 1,
            'journal_referenceid'       => $process_id
        );
        JournalModel::insert($data_penalty);
    }
    public function add_journal_payment_without_penalty($process_id, $bank_list, $payment, $datepayment, $branch_id, $do_date)
    {
        $des = $this->set_payment_description($process_id);
        $by = auth()->user()->id;
        $journal = new JournalModel();
        $journal->journal_parentid          = 0;
        $journal->journal_acccode           = $bank_list;
        $journal->journal_type              = 12;
        $journal->journal_debit             = $payment;
        $journal->journal_transactiondate   = $do_date;
        $journal->journal_paydate           = date('Y-m-d', strtotime($datepayment));
        $journal->journal_des               = ($des . " (Payment)");
        $journal->journal_by                = $by;
        $journal->journal_currency          = 1;
        $journal->journal_referenceid       = $process_id;
        $journal->branch_id                 = $branch_id;
        $journal->save();
    }
    public function add_journal_with_interest($process_id, $bank_list, $interest, $datepayment, $branch_id, $do_date)
    {
        $des = $this->set_payment_description($process_id);
        $data3 = array(

            'journal_parentid'          => 0,
            'journal_acccode'           => $bank_list,
            'journal_type'              => 40,
            'journal_credit'            => $interest,
            'journal_transactiondate'   => $do_date,
            'journal_paydate'           => date('Y-m-d', strtotime($datepayment)),
            'journal_des'               => ($des . " (Interest)"),
            'journal_by'                => auth()->user()->id,
            'journal_currency'          => 1,
            'journal_referenceid'       => $process_id,
            'branch_id'       => $branch_id
        );
        JournalModel::insert($data3);
    }
    //  approve client payment
    public function approve_client_payment(Request $request)
    {
        foreach ($request->paid_id as $key => $value) {
            $paid_pending = LoanPaidModel::join('nso007_loan_process', 'nso007_loan_process.id', 'nso007_loan_paid.loanpaid_processid')
                ->join('nso007_loan', 'nso007_loan.id', 'nso007_loan_process.loanprocess_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_project_stock', 'nso007_project_stock.id', 'nso007_item_stock.item_projectid')
                ->select(
                    'nso007_loan_process.id as process_id',
                    'nso007_loan_paid.id as paid_id',
                    'nso007_loan_paid.loanpaid_approved',
                    'nso007_loan_paid.loanpaid_principle',
                    'nso007_loan_paid.loanpaid_total',
                    'nso007_loan_paid.created_at',
                    'nso007_loan_paid.loandpaid_bankacc',
                    'nso007_loan_paid.loanpaid_penalty',
                    'nso007_project_stock.branch_id',
                    'nso007_loan_paid.loanpaid_penalty_option as option',
                    'nso007_loan_paid.loanpaid_interest as interest'
                )
                ->where('nso007_loan_paid.id', $value)->get();
            if ($paid_pending != null) {
                foreach ($paid_pending as $paid) {
                    $paid_id = $paid->paid_id;
                    $process_id = $paid->process_id;
                    $payment = $paid->loanpaid_total;
                    $bank_list = $paid->loandpaid_bankacc;
                    $datepayment = $paid->created_at;
                    $branch_id = $paid->branch_id;
                    $do_date = date('Y-m-d H:i:s A');
                    $option = $paid->option;
                    $penalty = $paid->loanpaid_penalty;
                    $interest = $paid->interest;
                    // if($interest != 0)
                    // {
                    //     $this->add_journal_with_interest($process_id,$bank_list,$interest,$datepayment,$branch_id,$do_date);
                    // }
                    if (!empty($penalty) && $penalty > 0) {
                        if ($option == 1) {
                            // $this->add_journal_payment($process_id,$bank_list,$payment,$datepayment,$branch_id,$penalty,$do_date);
                            DB::table('nso007_loan_process')->where('id', $process_id)->update([
                                'penalty_paid' => 0
                            ]);
                        } else if ($option == 2) {
                            DB::table('nso007_loan_process')->where('id', $process_id)->update([
                                'penalty_paid' => 0
                            ]);
                            DB::table('nso007_loan_process')->where('id', $process_id + 1)->update([
                                'penalty_paid' => $penalty
                            ]);
                        }
                    } else {
                        // $this->add_journal_payment_without_penalty($process_id,$bank_list,$payment,$datepayment,$branch_id,$do_date);
                    }
                    LoanPaidModel::where('id', $paid_id)->update(['loanpaid_approved' => 1]);
                    LoanProcessModel::where('id', $process_id)->update(['loanprocess_approve' => 1]);
                }
            }
        }
        return response()->json(['success' => true]);
    }
}
