<?php

namespace App\Http\Controllers\Agencies;
use App\Classes\Commission;
use App\Classes\AgencyCommission;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Auth;
use App\SaleStockModel;
use App\ExternalClientPaymentModel;
use App\SaleStockDetailModel;
use App\ClientModel;
use App\ItemModel;
use App\FundsRegisterModel;
use App\FundsTransactionModel;
use App\DepositModel;
use App\CommissionModel;
use App\CommissionItemModel;
use App\CommissionAdminModel;
use DB;
use DataTables;
use Phanna\Converter\KhmerDatetime;
use Illuminate\Support\Facades\Crypt;
class BookingController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    // function __construct()
    // {
    //      $this->middleware('permission:position-list');
    //      $this->middleware('permission:position-create', ['only' => ['create','store']]);
    //      $this->middleware('permission:position-edit', ['only' => ['edit','update']]);
    //      $this->middleware('permission:position-delete', ['only' => ['destroy']]);
    // }
    
    public function index()
    {
       
        return view('agencies.booking.index');
    }
    public function datatable_get_booking(){

        $log_id = Auth::user()->id;
        $clientbooking = DB::select("SELECT 
        nso007_client.id,
        nso007_client.client_fullname,
        nso007_client.client_phone1,
        nso007_client.client_address,
        nso007_sale_stock.sale_date,
        nso007_sale_stock.sale_deposit,
        nso007_sale_stock.sale_discount,
        nso007_sale_stock.sale_amount,
        nso007_sale_stock.sale_receive,
        nso007_sale_stock.sale_datecontract,
        nso007_sale_detail_stock.saledetail_price,
        GROUP_CONCAT(nso007_item_stock.item_name) as item_name,
        nso007_item_stock.item_stockstatus,
        nso007_item_stock.item_salestatus,
        nso007_item_stock.item_price,
        nso007_category_stock.category_name,
        nso007_project_stock.project_name
        FROM `nso007_client` 
        INNER JOIN nso007_sale_stock ON nso007_sale_stock.sale_clientid = nso007_client.id
        INNER JOIN nso007_sale_detail_stock ON nso007_sale_detail_stock.saledetail_saleid = nso007_sale_stock.id
        INNER JOIN nso007_item_stock ON nso007_item_stock.id = nso007_sale_detail_stock.saledetail_itemid
        INNER JOIN nso007_category_stock ON nso007_category_stock.id = nso007_item_stock.item_categoryid 
        INNER JOIN nso007_project_stock ON nso007_project_stock.id =nso007_item_stock.item_projectid
        WHERE  nso007_sale_stock.agency_id = '$log_id'
        AND nso007_item_stock.item_stockstatus = 1
        AND nso007_item_stock.item_salestatus = 2 
        GROUP BY nso007_sale_stock.id
        ORDER BY nso007_client.id desc");
        return  Datatables::of($clientbooking)
            ->addIndexColumn()
            ->addColumn('sale_receive', function($clientbooking) {
                return '$'.number_format($clientbooking->sale_receive,2);    
            })
            ->addColumn('sale_price', function($clientbooking) {
                return '$'.number_format(($clientbooking->sale_amount-$clientbooking->sale_discount),2);    
            })
            ->addColumn('remain_amount', function($clientbooking) {
                return '$'.number_format(($clientbooking->item_price)- ($clientbooking->sale_receive),2);  
            })
            ->addColumn('sale_date', function($clientbooking) {
                return date('d-m-Y', strtotime($clientbooking->sale_date));
            })
            ->addColumn('contract_date', function($clientbooking) {
                return date('d-m-Y', strtotime($clientbooking->sale_datecontract));
            })
            ->addColumn('status', function($clientbooking) {
                $status = '<strong class="text-warning">Booking</strong>';
                return $status;
            })
        
            ->editColumn('action', function ($clientbooking) {
                return '<a href="'.Route("booking.show",Crypt::encrypt($clientbooking->id)).'" class="fa fa-print"></a>';
            })
            ->rawColumns(['status' => 'status','action' => 'action', 'contract_date' => 'contract_date'])
            ->make(true);
    }
    public function datatable_get__detail_booking($id){

        $clientbooking = DB::select("SELECT 
                                        loanprocess_no,
                                        loanprocess_datepayment,
                                        nso007_loan_process.id,
                                        loanprocess_paid,
                                        nso007_loan_process.updated_at,
                                        loanprocess_datepaid,
                                        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
                                        FROM nso007_loan_process
                                        INNER JOIN nso007_loan ON nso007_loan_process.loanprocess_loanid = nso007_loan.id
                                        
                                        WHERE nso007_loan.loan_clientid = $id AND nso007_loan_process.loanprocess_des IS NULL
            ");

        return Datatables::of($clientbooking)
                            ->addIndexColumn()
                             ->addColumn('status', function($clientbooking) {
                                $paid = '';
                                if($clientbooking->loanprocess_paid==1){                                                   
                                    $paid = '<a target="_blank" href="" class="btn btn-xs btn-outline-success"  title="Print Invoice" ><i class="fa fa-check"></i></a>Paid: '.date('d-m-Y H:i:s​​ A',strtotime($clientbooking->updated_at));
                                }else if($clientbooking->loanprocess_paid==2){
                                    $paid = '<a target="_blank" href="" class="btn btn-xs btn-outline-success"  title="Print Invoice" ><i class="fa fa-spinner"></i></a>Pedding';
                                }else{
                                    $paid = '<a target="_blank" href="" class="btn btn-xs btn-outline-success"  title="Print Invoice" ><i class="fa fa-spinner"></i></a>Pedding';
                                }
                                return $paid;
                            })
                            ->addColumn('loanprocess_datepayment',function($clientbooking){
                                return date('d-m-Y',strtotime($clientbooking->loanprocess_datepayment));
                            })
                            ->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);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
                'sale_receive'      => 'required|numeric|min:500',
                'client_phone1'     => 'required',
                'client_address'    => 'required',
                'client_fullname'   => 'required',
                'client_gender'     => 'required',
        ]);
        // Commission when booking external
        $obj_commission         = new Commission;
        $obj_agency_commission  = new AgencyCommission;
        $client_address         = $request->client_address;
        $date_today             = date('Y-m-d');
        $date                   = strtotime($date_today);
        $date                   = strtotime("+6 day", $date);
        $date_next_seven_day    = date('Y-m-d', $date);

        $user_id        = Auth::user()->id;
        $get_funds      = FundsRegisterModel::where('user_id', $user_id)->get();
        $check_account  = count($get_funds);

        $get_comm_condition = DB::select("
            SELECT com_rate.agency_type, com_rate.commission_rate, com_rate.commission_condition
            FROM nso007_agency_commission_rate com_rate
            LEFT JOIN users on users.agency_type = com_rate.agency_type
            WHERE users.id = $user_id");

        $get_commission_rate        = $get_comm_condition[0]->commission_rate;
        $get_commission_condition   = $get_comm_condition[0]->commission_condition;

        $get_payment_item  = DB::select("
            SELECT item_stock.item_name
            FROM nso007_item_stock item_stock
            WHERE item_stock.id = $request->saledetail_itemid");
        
        if($check_account <= 0){
            return redirect()->route('funds-register.create');
        }else {
            // $balance = isset($get_funds[0]->balance);
            // $account_number = isset($get_funds[0]->account_number);
            $balance                    = $get_funds[0]->balance;
            $account_number             = $get_funds[0]->account_number;

            $client                     = new ClientModel();
            $salestock                  = new SaleStockModel();
            $externaldeposit            = new ExternalClientPaymentModel();
            $salestockdetail            = new SaleStockDetailModel();
            $transaction                = new FundsTransactionModel;
            $nso007_deposit             = new DepositModel;
            $nso007_agency_commission   = new CommissionModel;
            $commission_item            = new CommissionItemModel;
            $commission_item_lvl2       = new CommissionItemModel;
            $commission_item_lvl3       = new CommissionItemModel;
            $commission_item_lvl4       = new CommissionItemModel;
            $commission_item_lvl5       = new CommissionItemModel;
            $commission_item_lvl6       = new CommissionItemModel;

            

            $own_amount_item    = $request->saledetail_price;
            $deposit            = $request->sale_receive;
            $project_type       = $request->project_type;
            $item_code          = $request->sale_item_code;
            $debit_item_amount  = $own_amount_item - $deposit;
            $sale_remark        = "Sale Deposit: ".$item_code;
            $sale_type          = ($project_type == 2)?2:1;

            if ($balance >= 500 && $deposit >= 500 && $deposit <= $balance){
                 DB::beginTransaction();
                    try{
                        // Decrease Funds Balance
                        FundsRegisterModel::where('user_id', $user_id)->decrement('balance', $deposit);
                        $get_funds_balance = FundsRegisterModel::where('user_id', $user_id)->get();
                        
                        $amount_balance = $get_funds_balance[0]->balance;
                        // Insert Funds Transaction For Payment
                        $transaction->operation_type  = 2;
                        $transaction->account_number  = $account_number;
                        $transaction->amount          = $deposit;
                        $transaction->balance         = $amount_balance;
                        $transaction->remark          = $sale_remark;
                        $transaction->user_log        = $user_id;
                        $transaction->status          = 1;
                        $transaction->request_date    = date('Y-m-d H:i:s A');
                        $transaction->save();
                    DB::commit();
                    }catch(\Exception $e){
                        DB::rollback();
                        return redirect()->route('booking.index')->with('danger','Booking error !');
                    }
                    
                    
                
               
                    // Insert Client
                    $client->client_fullname        = $request->client_fullname;
                    $client->client_phone1          = $request->client_phone1;
                    $client->client_address         = $client_address;
                    $client->client_userid          = $user_id;
                    $client->client_status          = 1;
                    $client->client_gender          = $request->client_gender;
                    $client->save();
                    
                    $client_last_id = ClientModel::max('id');

                    $salestock->sale_clientid               = $client_last_id;
                    $salestock->agency_id                   = $user_id;
                    $salestock->sale_type                   = 2;
                    $salestock->sale_discount               = 0;
                    $salestock->sale_date                   = date("Y-m-d");
                    $salestock->sale_amount                 = $request->saledetail_price;
                    $salestock->sale_datecontract           = $date_next_seven_day;
                    $salestock->sale_receive                = $request->sale_receive;
                    $salestock->sale_remain                 = $debit_item_amount;
                    $salestock->sale_status                 = $sale_type;
                    $salestock->admin_commission            = $request->project_commission;
                    $salestock->admin_commission_condition  = $request->project_condition;
                    $salestock->agency_commission           = $get_commission_rate;
                    $salestock->agency_commission_condition = $get_commission_condition;
                    $salestock->save();
                    
                    $sale_stock_last_id = SaleStockModel::max('id');
                 
                    $item_commission    = $obj_commission->get_external_item_commission_in_salestock($sale_stock_last_id);
                    $item_condition     = $obj_commission->get_external_item_condition_in_salestock($sale_stock_last_id);
                    $agency_commission  = $obj_commission->get_item_commission_in_salestock($sale_stock_last_id);
                    $agency_condition   = $obj_commission->get_item_condition_in_salestock($sale_stock_last_id);

                    if ($sale_type == 2) {
                        $this->set_commission_booking_external($sale_stock_last_id, $item_commission, $item_condition);
                    }
                    $salestockdetail->saledetail_saleid     = $sale_stock_last_id;
                    $salestockdetail->saledetail_price      = $request->saledetail_price;
                    $salestockdetail->saledetail_itemid     = $request->saledetail_itemid;
                    $salestockdetail->save();
                    
                    $update_status = array(
                        'item_salestatus' => 2,
                        'available' => 0,
                    );
                    ItemModel::where('id',$request->saledetail_itemid)->update($update_status);
                    
                    
                    // insert to nso007_deposit

                    $nso007_deposit->deposit_saleid     =   $sale_stock_last_id;
                    $nso007_deposit->deposit_date       =   $date_today;
                    $nso007_deposit->deposit_amount     =   $deposit;
                    $nso007_deposit->status_num         =   1;
                    $nso007_deposit->save();
                    

                    //insert deposit to external client payment
                    $externaldeposit->sale_id           =   $sale_stock_last_id;
                    $externaldeposit->payment_no        =   1;
                    $externaldeposit->payment_amount    =   $request->sale_receive;
                    $externaldeposit->payment_item      =   $get_payment_item[0]->item_name;
                    $externaldeposit->payment_date      =   date("Y-m-d H:i:s");
                    $externaldeposit->user_log          =   $user_id;
                    $externaldeposit->status            =   1;
                    $externaldeposit->save();
                    

                    // Commission
                    $nso007_agency_commission->sale_id      =   $sale_stock_last_id;
                    $nso007_agency_commission->agency_id    =   $user_id;
                    $nso007_agency_commission->client_id    =   $client_last_id;
                    $nso007_agency_commission->item_id      =   $request->saledetail_itemid;
                    $nso007_agency_commission->item_cost    =   $request->saledetail_price;
                    $nso007_agency_commission->commission   =   $agency_commission;
                    $nso007_agency_commission->condition    =   $agency_condition;
                    $nso007_agency_commission->save();
                    
                    $commission_last_id = CommissionModel::max('id');
                
                    $commission = CommissionModel::where('id', $commission_last_id)->get();
                    $agency_id  = $commission[0]->agency_id;
                    // Property First Price
                    $sale_price = $request->saledetail_price;

                    $find_parent = DB::select("
                        SELECT
                        level1.id AS level_1_id,
                        level1.parent_id AS parent_id,

                        level2.id AS level_2_id,
                        level2.parent_id  AS level_2_parent,

                        level3.id AS level_3_id,
                        level3.parent_id  AS level_3_parent,

                        level4.id AS level_4_id,
                        level4.parent_id  AS level_4_parent,

                        level5.id AS level_5_id,
                        level5.parent_id  AS level_5_parent,

                        level6.id AS level_6_id,
                        level6.parent_id  AS level_6_parent                
                        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
                    ");

                    $parent = [];

                    empty($find_parent[0]->level_1_id) ?: $parent['lvl_parent_1'] = $find_parent[0]->level_1_id;
                    empty($find_parent[0]->level_2_id) ?: $parent['lvl_parent_2'] = $find_parent[0]->level_2_id;
                    empty($find_parent[0]->level_3_id) ?: $parent['lvl_parent_3'] = $find_parent[0]->level_3_id;
                    empty($find_parent[0]->level_4_id) ?: $parent['lvl_parent_4'] = $find_parent[0]->level_4_id;
                    empty($find_parent[0]->level_5_id) ?: $parent['lvl_parent_5'] = $find_parent[0]->level_5_id;
                    empty($find_parent[0]->level_6_id) ?: $parent['lvl_parent_6'] = $find_parent[0]->level_6_id;

                    $count_parent = count($parent);

                    if ($count_parent == 1) {
                    // Level 1
                        $commission_item->commission_id = $commission_last_id;
                        $commission_item->agency_id     = $agency_id;
                        $commission_item->agency_level  = 1;
                        $commission_item->commission    = $agency_commission;
                        $commission_item->condition     = $agency_condition;
                        $commission_item->amount        = ($sale_price * $agency_commission / 100);
                        $commission_item->save();
                        
                    } elseif ($count_parent == 2) {
                    // Level 1
                        $commission_item->commission_id = $commission_last_id;
                        $commission_item->agency_id     = $agency_id;
                        $commission_item->agency_level  = 1;
                        $commission_item->commission    = $agency_commission;
                        $commission_item->condition     = $agency_condition;
                        $commission_item->amount        = ($sale_price * $agency_commission / 100);
                        $commission_item->save();
                        

                        $agency_1 = User::where('id', $agency_id)->get();

                        $agency_lvl2 = $agency_1[0]->parent_id;
                    // Level 2
                        $commission_item_lvl2->commission_id = $commission_last_id;
                        $commission_item_lvl2->agency_id     = $agency_lvl2;
                        $commission_item_lvl2->agency_level  = 2;
                        $commission_item_lvl2->commission    = 0.1;
                        $commission_item_lvl2->condition     = $agency_condition;
                        $commission_item_lvl2->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl2->save();
                        
                    } elseif ($count_parent == 3) {
                    // Level 1
                        $commission_item->commission_id = $commission_last_id;
                        $commission_item->agency_id     = $agency_id;
                        $commission_item->agency_level  = 1;
                        $commission_item->commission    = $agency_commission;
                        $commission_item->condition     = $agency_condition;
                        $commission_item->amount        = ($sale_price * $agency_commission / 100);
                        $commission_item->save();
                        

                        $agency_1 = User::where('id', $agency_id)->get();

                        $agency_lvl2 = $agency_1[0]->parent_id;
                    // Level 2
                        $commission_item_lvl2->commission_id = $commission_last_id;
                        $commission_item_lvl2->agency_id     = $agency_lvl2;
                        $commission_item_lvl2->agency_level  = 2;
                        $commission_item_lvl2->commission    = 0.1;
                        $commission_item_lvl2->condition     = $agency_condition;
                        $commission_item_lvl2->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl2->save();

                        $find_lvl_2 = CommissionItemModel::where('agency_level',2)
                        ->where('commission_id', $commission_last_id)
                        ->get();

                        $agency_2 = User::where('id', $find_lvl_2[0]->agency_id)->get();

                        $agency_lvl3 = $agency_2[0]->parent_id;
                    // Level 3
                        $commission_item_lvl3->commission_id = $commission_last_id;
                        $commission_item_lvl3->agency_id     = $agency_lvl3;
                        $commission_item_lvl3->agency_level  = 3;
                        $commission_item_lvl3->commission    = 0.1;
                        $commission_item_lvl3->condition     = $agency_condition;
                        $commission_item_lvl3->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl3->save();
                        
                    } elseif ($count_parent == 4) {
                    // Level 1
                        $commission_item->commission_id = $commission_last_id;
                        $commission_item->agency_id     = $agency_id;
                        $commission_item->agency_level  = 1;
                        $commission_item->commission    = $agency_commission;
                        $commission_item->condition     = $agency_condition;
                        $commission_item->amount        = ($sale_price * $agency_commission / 100);
                        $commission_item->save();
                        

                        $agency_1 = User::where('id', $agency_id)->get();

                        $agency_lvl2 = $agency_1[0]->parent_id;
                    // Level 2
                        $commission_item_lvl2->commission_id = $commission_last_id;
                        $commission_item_lvl2->agency_id     = $agency_lvl2;
                        $commission_item_lvl2->agency_level  = 2;
                        $commission_item_lvl2->commission    = 0.1;
                        $commission_item_lvl2->condition     = $agency_condition;
                        $commission_item_lvl2->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl2->save();
                        

                        $find_lvl_2 = CommissionItemModel::where('agency_level',2)
                        ->where('commission_id', $commission_last_id)
                        ->get();

                        $agency_2 = User::where('id', $find_lvl_2[0]->agency_id)->get();

                        $agency_lvl3 = $agency_2[0]->parent_id;
                    // Level 3
                        $commission_item_lvl3->commission_id = $commission_last_id;
                        $commission_item_lvl3->agency_id     = $agency_lvl3;
                        $commission_item_lvl3->agency_level  = 3;
                        $commission_item_lvl3->commission    = 0.1;
                        $commission_item_lvl3->condition     = $agency_condition;
                        $commission_item_lvl3->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl3->save();

                        $find_lvl_3 = CommissionItemModel::where('agency_level',3)
                        ->where('commission_id', $commission_last_id)
                        ->get();
                        $agency_3 = User::where('id', $find_lvl_3[0]->agency_id)->get();

                        $agency_lvl4 = $agency_3[0]->parent_id;
                    // Level 4
                        $commission_item_lvl4->commission_id = $commission_last_id;
                        $commission_item_lvl4->agency_id     = $agency_lvl4;
                        $commission_item_lvl4->agency_level  = 4;
                        $commission_item_lvl4->commission    = 0.1;
                        $commission_item_lvl4->condition     = $agency_condition;
                        $commission_item_lvl4->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl4->save();
                        
                    } elseif ($count_parent == 5) {
                    // Level 1
                        $commission_item->commission_id = $commission_last_id;
                        $commission_item->agency_id     = $agency_id;
                        $commission_item->agency_level  = 1;
                        $commission_item->commission    = $agency_commission;
                        $commission_item->condition     = $agency_condition;
                        $commission_item->amount        = ($sale_price * $agency_commission / 100);
                        $commission_item->save();
                        

                        $agency_1 = User::where('id', $agency_id)->get();

                        $agency_lvl2 = $agency_1[0]->parent_id;
                    // Level 2
                        $commission_item_lvl2->commission_id = $commission_last_id;
                        $commission_item_lvl2->agency_id     = $agency_lvl2;
                        $commission_item_lvl2->agency_level  = 2;
                        $commission_item_lvl2->commission    = 0.1;
                        $commission_item_lvl2->condition     = $agency_condition;
                        $commission_item_lvl2->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl2->save();
                        

                        $find_lvl_2 = CommissionItemModel::where('agency_level',2)
                        ->where('commission_id', $commission_last_id)
                        ->get();

                        $agency_2 = User::where('id', $find_lvl_2[0]->agency_id)->get();

                        $agency_lvl3 = $agency_2[0]->parent_id;
                    // Level 3
                        $commission_item_lvl3->commission_id = $commission_last_id;
                        $commission_item_lvl3->agency_id     = $agency_lvl3;
                        $commission_item_lvl3->agency_level  = 3;
                        $commission_item_lvl3->commission    = 0.1;
                        $commission_item_lvl3->condition     = $agency_condition;
                        $commission_item_lvl3->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl3->save();
                        

                        $find_lvl_3 = CommissionItemModel::where('agency_level',3)
                        ->where('commission_id', $commission_last_id)
                        ->get();
                        $agency_3 = User::where('id', $find_lvl_3[0]->agency_id)->get();

                        $agency_lvl4 = $agency_3[0]->parent_id;
                    // Level 4
                        $commission_item_lvl4->commission_id = $commission_last_id;
                        $commission_item_lvl4->agency_id     = $agency_lvl4;
                        $commission_item_lvl4->agency_level  = 4;
                        $commission_item_lvl4->commission    = 0.1;
                        $commission_item_lvl4->condition     = $agency_condition;
                        $commission_item_lvl4->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl4->save();
                        

                        $find_lvl_4 = CommissionItemModel::where('agency_level',4)
                        ->where('commission_id', $commission_last_id)
                        ->get();
                        $agency_4 = User::where('id', $find_lvl_4[0]->agency_id)->get();

                        $agency_lvl5 = $agency_4[0]->parent_id;
                    // Level 5
                        $commission_item_lvl5->commission_id = $commission_last_id;
                        $commission_item_lvl5->agency_id     = $agency_lvl5;
                        $commission_item_lvl5->agency_level  = 5;
                        $commission_item_lvl5->commission    = 0.1;
                        $commission_item_lvl5->condition     = $agency_condition;
                        $commission_item_lvl5->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl5->save();
                        
                    } elseif ($count_parent == 6) {
                    // Level 1
                        $commission_item->commission_id = $commission_last_id;
                        $commission_item->agency_id     = $agency_id;
                        $commission_item->agency_level  = 1;
                        $commission_item->commission    = $agency_commission;
                        $commission_item->condition     = $agency_condition;
                        $commission_item->amount        = ($sale_price * $agency_commission / 100);
                        $commission_item->save();
                        

                        $agency_1 = User::where('id', $agency_id)->get();

                        $agency_lvl2 = $agency_1[0]->parent_id;
                    // Level 2
                        $commission_item_lvl2->commission_id = $commission_last_id;
                        $commission_item_lvl2->agency_id     = $agency_lvl2;
                        $commission_item_lvl2->agency_level  = 2;
                        $commission_item_lvl2->commission    = 0.1;
                        $commission_item_lvl2->condition     = $agency_condition;
                        $commission_item_lvl2->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl2->save();
                        

                        $find_lvl_2 = CommissionItemModel::where('agency_level',2)
                        ->where('commission_id', $commission_last_id)
                        ->get();

                        $agency_2 = User::where('id', $find_lvl_2[0]->agency_id)->get();

                        $agency_lvl3 = $agency_2[0]->parent_id;
                    // Level 3
                        $commission_item_lvl3->commission_id = $commission_last_id;
                        $commission_item_lvl3->agency_id     = $agency_lvl3;
                        $commission_item_lvl3->agency_level  = 3;
                        $commission_item_lvl3->commission    = 0.1;
                        $commission_item_lvl3->condition     = $agency_condition;
                        $commission_item_lvl3->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl3->save();
                        

                        $find_lvl_3 = CommissionItemModel::where('agency_level',3)
                        ->where('commission_id', $commission_last_id)
                        ->get();
                        $agency_3 = User::where('id', $find_lvl_3[0]->agency_id)->get();

                        $agency_lvl4 = $agency_3[0]->parent_id;
                    // Level 4
                        $commission_item_lvl4->commission_id = $commission_last_id;
                        $commission_item_lvl4->agency_id     = $agency_lvl4;
                        $commission_item_lvl4->agency_level  = 4;
                        $commission_item_lvl4->commission    = 0.1;
                        $commission_item_lvl4->condition     = $agency_condition;
                        $commission_item_lvl4->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl4->save();

                        $find_lvl_4 = CommissionItemModel::where('agency_level',4)
                        ->where('commission_id', $commission_last_id)
                        ->get();
                        $agency_4 = User::where('id', $find_lvl_4[0]->agency_id)->get();

                        $agency_lvl5 = $agency_4[0]->parent_id;
                    // Level 5
                        $commission_item_lvl5->commission_id = $commission_last_id;
                        $commission_item_lvl5->agency_id     = $agency_lvl5;
                        $commission_item_lvl5->agency_level  = 5;
                        $commission_item_lvl5->commission    = 0.1;
                        $commission_item_lvl5->condition     = $agency_condition;
                        $commission_item_lvl5->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl5->save();
                        

                        $find_lvl_5 = CommissionItemModel::where('agency_level',5)
                        ->where('commission_id', $commission_last_id)
                        ->get();
                        $agency_5 = User::where('id', $find_lvl_5[0]->agency_id)->get();

                        $agency_lvl6 = $agency_5[0]->parent_id;
                    // Level 6
                        $commission_item_lvl6->commission_id = $commission_last_id;
                        $commission_item_lvl6->agency_id     = $agency_lvl6;
                        $commission_item_lvl6->agency_level  = 6;
                        $commission_item_lvl6->commission    = 0.1;
                        $commission_item_lvl6->condition     = $agency_condition;
                        $commission_item_lvl6->amount        = ($sale_price * 0.1 / 100);
                        $commission_item_lvl6->save();
                        
                    }

                    if ($project_type == 2) {
                        $payment_amount = $deposit;
                        $obj_commission->set_commission_external_client_payment($item_code, $deposit);
                        $obj_agency_commission->active_agency_commission($sale_stock_last_id);
                        $obj_agency_commission->agency_commission_external_project($payment_amount, $sale_stock_last_id);
                        
                    }
                    if ($project_type == 1) {
                        $payment_amount = $deposit;
                        $obj_agency_commission->active_agency_commission($sale_stock_last_id);
                        $obj_agency_commission->agency_commission_external_project($payment_amount, $sale_stock_last_id);
                        
                    }

                    
                    \LogActivity::addToLog('You have deposited successfully!');

                    return redirect()->route('booking.index')
                    ->with('success','You have deposited successfully!');
                
                
            }
            else{
                \LogActivity::addToLog('Your Balance Invalid !');
                return back()->with('danger','Your Balance Invalid !');
            }
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

        $decrypt_id = Crypt::decrypt($id);
        $invoice = DB::select("SELECT 
        nso007_client.id,
        nso007_client.client_fullname,
        nso007_client.client_phone1,
        nso007_client.client_address,
        nso007_sale_stock.sale_date,
        nso007_sale_stock.sale_deposit,
        nso007_sale_stock.sale_receive,
        nso007_sale_detail_stock.saledetail_price,
        GROUP_CONCAT(nso007_item_stock.item_name) as item_name,
        nso007_item_stock.item_street,
        nso007_sale_stock.sale_datecontract,
        nso007_item_stock.item_house,
        nso007_item_stock.item_price,
        nso007_category_stock.category_name,
        nso007_project_stock.project_name,
        CONCAT(users.user_firstname,' ',users.user_lastname) AS agency_name
        FROM `nso007_client` 
        INNER JOIN nso007_sale_stock ON nso007_sale_stock.sale_clientid = nso007_client.id
        INNER JOIN users ON nso007_sale_stock.agency_id = users.id
        INNER JOIN nso007_sale_detail_stock ON nso007_sale_detail_stock.saledetail_saleid = nso007_sale_stock.id
        INNER JOIN nso007_item_stock ON nso007_item_stock.id = nso007_sale_detail_stock.saledetail_itemid
        INNER JOIN nso007_category_stock ON nso007_category_stock.id = nso007_item_stock.item_categoryid 
        INNER JOIN nso007_project_stock ON nso007_project_stock.id =nso007_item_stock.item_projectid
        where  nso007_client.id =  $decrypt_id
        order by nso007_client.id desc");

        // $date = date("Y-m-d"); // or specific date that you want
        // $khmer = new KhmerDatetime($date);
        // $khmer_date_now = $khmer->getDate();
        // $date_contract = $invoice[0]->sale_datecontract;
        // $date_contract = new KhmerDatetime($date_contract);
        // $khmer_date_contract = $date_contract->getDate();

        $branch = DB::table('nso007_branches')->where('id',\Branch::branch_id())->first();
         return view('agencies.booking.show',compact('invoice','branch'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
    // Add commission to admin when booking
    public function set_commission_booking_external($sale_id, $commission, $condition)
    {
        $sale_stock = SaleStockModel::where('id', $sale_id)->select('sale_amount')->get();
        $sale_amount = $sale_stock[0]->sale_amount;
        $commission_amount = ($commission * $sale_amount / 100);
        $data = array(
            'sale_id'               => $sale_id,
            'commission'            => $commission,
            'condition'             => $condition,
            'commission_amount'     => $commission_amount,
            'commission_received'   => 0
        );
        CommissionAdminModel::insert($data);
    }
}
