<?php

namespace App\Http\Controllers\Administrator;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\ItemModel;
use App\ClientModel;
use App\DepositModel;
use App\DepositScheduleModel;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Session;
use DB;
use App\user;
use App\FundsRegisterModel;
use App\JournalModel;
use App\ProjectModel;
use App\SaleStockDetailModel;
use App\SaleStockModel;
use App\BlockedItemModel;
use App\CategoryModel;
use App\InventoryModel;
use App\PromotionDetailModel;
use App\PromotionModel;
use Auth;
use Gate;
use Yajra\DataTables\DataTables;
use App\Helpers\Branch;
use App\BranchModel;

class POSController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct()
    {
        $this->middleware('permission:POS-Create', ['only' => ['create', 'store']]);
        $this->middleware('permission:POS-Blocked-Item-List', ['only' => ['blocked_item']]);
    }
    public function index()
    {
    }
    public function create_pos(Request $request, $project_id = null, $category_id = null, $inventory_id = null, $item_name = null)
    {
        $project_id = $request->project_id;
        $category_id = $request->category_id;
        $inventory_id = $request->inventory_id;
        $item_name = $request->item_name;
        // dd([$project_id,$category_id,$inventory_id,$item_name]);
        $clients = ClientModel::select(DB::raw('concat(client_firstname," ",client_lastname) as client_name'), 'id')->pluck('client_name', 'id')->prepend('Please Select', '');
        
        $hours = DB::table('nso007_block_time')->where('status', 1)->get();
        $category = CategoryModel::pluck('category_name', 'id');
        $inventory = InventoryModel::pluck('inv_name', 'id')->prepend('Please Select', '');
        $parent_id = User::select(DB::Raw('GROUP_CONCAT(id) as ids'))->where([['role', 'Agencies'], ['parent_id', 0]])->first()->ids;
        $agencyLV2 = User::select(DB::raw('GROUP_CONCAT(id) as ids'))->whereIn('parent_id', explode(',', $parent_id))->first()->ids;
        $agencies = User::whereNull('company_agent')
            ->where(function ($query) use ($agencyLV2) {
                $query->orwhereIn('parent_id', explode(',', $agencyLV2));
                $query->orwhere('agency_type', 1);
            })
            ->select(
                DB::raw('CONCAT(user_firstname," ",user_lastname) AS client_name'),
                'id'
            )
            ->pluck('client_name', 'id')
            ->prepend('Please Select', '');
        
        $closeSale = User::where('role','Agencies')
                    ->select(DB::raw('CONCAT(user_firstname," ",user_lastname) As closesale'),'id')
                    ->pluck('closesale','id')->prepend('Select Close Sale','');
        $employees = User::where("role","Administrator")->select(DB::raw('CONCAT(user_firstname," ",user_lastname) As name'),'id')->pluck("name","id")->prepend("Please Select","");
        $from           = date('Y-m-d', strtotime('first day of this month'));
        $to             = date('Y-m-d', strtotime('last day of this month'));

        $promotion = DB::table("nso007_promotion")
            ->join("nso007_project_stock","nso007_project_stock.id","nso007_promotion.project_id")
            ->where('nso007_promotion.available',1)
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->pluck("nso007_promotion.name","nso007_promotion.id")->prepend("Please Select","");                

        $payment_policy = DB::table("nso007_payment_policy")->pluck("name","id")->prepend("Please Select","");
        $payment_policy_detail = DB::table("nso007_payment_policy_detail as po_detail")
            ->pluck('name',"id")
            ->prepend("Please Select","");

        if (Auth::user()->branch_id == 1) {
            $projects = ProjectModel::select(
                DB::raw('CONCAT(project_code," ",project_name) AS project'),
                'id'
            )
            ->pluck('project', 'id');
            $data = ItemModel::join('nso007_project_stock as project', 'project.id', 'nso007_item_stock.item_projectid')
                ->leftjoin('nso007_inventery_stock as inven', 'inven.id', 'nso007_item_stock.inv_id')
                ->leftjoin('nso007_blocked_item As block', 'block.item_id', 'nso007_item_stock.id')
                ->leftjoin('users', 'users.id', 'block.user_id')
                ->select('nso007_item_stock.*', 'inven.inv_name', DB::raw('CONCAT(user_firstname," ",user_lastname) As user'),'project.feature')
                ->where([['available', 1], ['item_salestatus', 0]])
                ->when(empty(\Branch::branch_key()), function ($query) {
                    $query->where('project.branch_id', \Branch::branch_id());
                })
                ->when(request('project_id'), function ($query) use ($project_id) {
                    $query->whereIn('item_projectid', $project_id);
                })
                ->when(request('category_id'), function ($query) use ($category_id) {
                    $query->whereIn('item_categoryid', $category_id);
                })
                ->when($inventory_id, function ($query) use ($inventory_id) {
                    $query->where('inv_id', $inventory_id);
                })
                ->when($item_name, function ($query) use ($item_name) {
                    $query->where('item_house', 'LIKE', "%$item_name%");
                })
                ->orderBy('nso007_item_stock.id', 'asc')
                ->paginate(30);
        } else {
            $projects = ProjectModel::select(
                DB::raw('CONCAT(project_code," ",project_name) AS project'),
                'id'
            )->where('branch_id', Auth::user()->branch_id)
                ->pluck('project', 'id');
            $data = ItemModel::join('nso007_project_stock as project', 'project.id', 'nso007_item_stock.item_projectid')
                ->leftjoin('nso007_inventery_stock as inven', 'inven.id', 'nso007_item_stock.inv_id')
                ->leftjoin('nso007_blocked_item As block', 'block.item_id', 'nso007_item_stock.id')
                ->leftjoin('users', 'users.id', 'block.user_id')
                ->select('nso007_item_stock.*', 'inven.inv_name', DB::raw('CONCAT(user_firstname," ",user_lastname) As user'),'project.feature')
                ->where([['available', 1], ['item_salestatus', 0]])
                ->when(empty(\Branch::branch_key()), function ($query) {
                    $query->where('project.branch_id', \Branch::branch_id());
                })
                ->when($project_id, function ($query) use ($project_id) {
                    $query->whereIn('item_projectid', $project_id);
                })
                ->when($category_id, function ($query) use ($category_id) {
                    $query->whereIn('item_categoryid', $category_id);
                })
                ->when($inventory_id, function ($query) use ($inventory_id) {
                    $query->where('inv_id', $inventory_id);
                })
                ->when($item_name, function ($query) use ($item_name) {
                    $query->where('item_house', 'LIKE', "%$item_name%");
                })
                ->orderBy('nso007_item_stock.id', 'asc')
                ->paginate(30);
        }
        if ($request->ajax()) {
            return view('administrator.pos.pre-result', ['data' => $data]);
        }

        return view('administrator.pos.index', ['payment_policy_detail'=>$payment_policy_detail,'closesale'=>$closeSale,'category_id' => $category_id, 'inventory_id' => $inventory_id, 'inventory' => $inventory, 'project_id' => $project_id, 'category' => $category, 'hours' => $hours, 'data' => $data, 'clients' => $clients, 'agencies' => $agencies, 'projects' => $projects,'employees'=>$employees,'promotion'=>$promotion,'payment_policy'=>$payment_policy]);
    }

    public function get_promotion_(Request $request)
    {
        $promotion_id = $request->promotion_id;
        return json_encode(DB::table('nso007_promotion')
                            ->select(DB::raw('group_concat(nso007_promotion.name) as name'))
                            ->whereIn("id",$promotion_id)
                            ->where('available',1)->first());
    }
    public function get_policy_detail($id)
    {
        return json_encode(DB::table('nso007_payment_policy_detail as pa_po_de')
            ->where("pa_po_de.policy_id",$id)
            ->get());
    }
    public function get_promotion_detail(Request $request){

        $promotion_id = $request->promotion_id;
        $promotion_detail = PromotionDetailModel::join("nso007_product_promotion","nso007_product_promotion.id","nso007_promotion_detail.product_id")
            
            ->select('nso007_promotion_detail.id',
                'nso007_promotion_detail.product_unit_cost',
                DB::raw('nso007_product_promotion.name As promotion_detail'))
            ->where('nso007_promotion_detail.promotion_id',$promotion_id)
            ->where('nso007_promotion_detail.available',1)
            ->get();

        echo json_encode($promotion_detail);
    }
    public function filter(Request $request)
    {
        $session = Session::get('cart');
        $project = $request->project_id;
        $data = ItemModel::join('nso007_project_stock as project', 'project.id', 'nso007_item_stock.item_projectid')
            ->leftjoin('nso007_inventery_stock as inven', 'inven.id', 'nso007_item_stock.inv_id')
            ->select('nso007_item_stock.*', 'inven.inv_name', 'project.feature')
            ->where('item_salestatus', 0)
            ->where('available', 1)
            ->when(request('project_id', ''), function ($query) use ($project) {
                $query->where('item_projectid', $project);
            })->orderBy('nso007_item_stock.id', 'asc')->get();
        $div='';
        foreach ($data as $key => $item) {
            $btn_block = '';
            $button = '';
            $status = 0;
            if (!$session) {
                $button = '<p class="btn-holder"><a href="#" data-id="' . $item->id . '" class="btn btn-warning btn-block text-center btn-add-to-cart" role="button">Add To Cart</a> </p>';
            } else {
                foreach ($session as $key => $cart) {
                    if ($cart['item_id'] == $item->id) {
                        $button = '<p class="btn-holder"><a href="#" data-id="' . $item->id . '" class="btn btn-danger btn-block text-center" role="button">Added To Cart</a> </p>';
                        $status = 1;
                    }
                }
                if ($status != 1) {
                    $button = '<p class="btn-holder"><a href="#" data-id="' . $item->id . '" class="btn btn-warning btn-block text-center btn-add-to-cart" role="button">Add To Cart</a> </p>';
                }
            }
            if (Auth::user()->block_permission == 1) {
                $btn_block = '<p class="btn-holder"><a href="#" data-id="' . $item->id . '" class="btn btn-default btn-block button_success text-center btn-block-item" role="button">Block Item</a> </p>';
            }

            $div .= '<div class="col-xs-12 col-sm-3 col-md-2 padding-0 bg">
                        <div class="thumbnail">
                            <div class="caption" style="background-size: cover;background-image: '.asset('assets/images/resize/768x768/'.$item->feature).');">
                                <p><img src="/assets/images/resize/768x768/'.$project->feature.'" width="100px" class="hide_img"></p>
                                <h4>' . $item->item_names . '</h4>
                                <p><strong>Price: </strong>$' . $item->item_price . '</p>
                                <p>' . $item->inv_name . '</p>
                                ' . $button . '
                                ' . $btn_block . '
                            </div>
                        </div>
                    </div>';
        }
        return $div;
    }
    public function search(Request $request)
    {
        $project        = $request->project_id;
        $category       = $request->category_id;
        $inventory      = $request->inventory_id;
        $item_name      = $request->item_name;
        $session        = Session::get('cart');
        $div            = "";

        $button = '';
        $btn_add = '';
        $btn_block = '';
        $status = 0;

        $data = ItemModel::join('nso007_project_stock as project', 'project.id', 'nso007_item_stock.item_projectid')
            ->leftjoin('nso007_inventery_stock as inven', 'inven.id', 'nso007_item_stock.inv_id')
            ->select('nso007_item_stock.*', 'inven.inv_name', DB::raw('CONCAT(user_firstname," ",user_lastname) As user'),'project.feature')
            ->where('item_house', 'LIKE', "%$item_name%")
            ->leftjoin('nso007_blocked_item As block', 'block.item_id', 'nso007_item_stock.id')
            ->leftjoin('users', 'users.id', 'block.user_id')
            ->when(request('project_id', ''), function ($query) use ($project) {
                $query->where('item_projectid', $project);
            })
            ->when($category, function ($query) use ($category) {
                $query->where('item_categoryid', $category);
            })
            ->when($inventory, function ($query) use ($inventory) {
                $query->where('inv_id', $inventory);
            })
            ->orderBy('nso007_item_stock.id', 'asc')
            ->get();
        if (!empty($data)) {
            foreach ($data as $key => $item) {

                if (!$session) {
                    $button = '<p class="btn-holder"><a href="#" data-id="' . $item->id . '" class="btn btn-default btn-block text-center btn-add-to-cart" role="button">Add To Cart</a> </p>';
                } else {
                    foreach ($session as $key => $cart) {
                        if ($cart['item_id'] == $item->id) {
                            $button = '<p class="btn-holder"><a href="" data-id="' . $item->id . '" class="btn btn-danger btn-block text-center" role="button">Added To Cart</a> </p>';
                            $status = 1;
                        }
                    }
                    if ($status != 1) {
                        $button = '<p class="btn-holder"><a href="#" data-id="' . $item->id . '" class="btn btn-default btn-block text-center btn-add-to-cart" role="button">Add To Cart</a> </p>';
                    }
                }
                if (Auth::user()->block_permission == 1) {
                    $btn_block = '<p class="btn-holder"><a href="#" data-id="' . $item->id . '" data-hour="'.$item->item_block_time.'" class="btn btn-block btn-default text-center btn-block-item" role="button">Block Item</a> </p>';
                }

                if (!empty($item)) {
                    if ($item->item_salestatus == 0 && $item->block_status == 2) //block
                    {
                        if(Auth::user()->block_permission==1){
                            $btn_add = '<p class="btn-holder"><a href="#" data-id="' . $item->id . '" class="btn btn-default btn-block text-center txt-danger fa fa-times" role="button"> Not Available</a> </p>';
                        }
                        $button = '<p class="btn-holder"><a href="#" data-id="{{$item->id}}" class="btn btn-block btn-default text-center txt-warning" role="button" data-toggle="tooltip" data-placement="top" title="Blocked By : ' . $item->user . '"> BLOCKED</a> </p>';
                        $div .= '<div class="col-lg-2 col-md-4 col-sm-6 col-xs-3 col-6 bg pos-item p-5">
                           <div class="thumbnail">
                               <div class="caption" data-url="'.asset('assets/images/resize/768x768/'.$item->feature).'">
                                   <center><h4 class="text-danger"><b>' . $item->item_house . '</b></h4>
                                   <p class="text-blue"><b>$' . $item->item_price . '</b></p>
                                   <p class="text-blue inven-name"><b>Stock : ' . $item->inv_name . '</b></p></center>
                                   ' . $btn_add . '
                                   ' . $button . '
                               </div>
                           </div>
                       </div>';
                    } else if ($item->item_salestatus == 2 && $item->item_stockstatus == 2) //sold
                    {
                        $btn_add = '<p class="btn-holder"><a href="" data-id="" class="btn btn-default btn-block text-center" role="button">Add To Cart</a> </p>';
                        $button = '<p class="btn-holder"><a href="" data-id="" class="btn btn-block btn-info text-center btn-block-item-" role="button">Item Sold</a> </p>';
                        $div .= '<div class="col-lg-2 col-md-4 col-sm-6 col-xs-3 col-6 bg pos-item p-5">
                           <div class="thumbnail">
                               <div class="caption" data-url="'.asset('assets/images/resize/768x768/'.$item->feature).'">
                                   <center><h4 class="text-danger"><b>' . $item->item_house . '</b></h4>
                                   <p class="text-blue"><b>$' . $item->item_price . '</b></p>
                                   <p class="text-blue inven-name"><b>Stock : ' . $item->inv_name . '</b></p></center>
                                   ' . $btn_add . '
                                   ' . $button . '
                               </div>
                           </div>
                       </div>';
                    } else {
                        $div .= '<div class="col-lg-2 col-md-4 col-sm-6 col-xs-3 col-6 bg pos-item p-5">
                           <div class="thumbnail">
                               <div class="caption" data-url="'.asset('assets/images/resize/768x768/'.$item->feature).'">
                                   <center><h4 class="text-danger"><b>' . $item->item_house . '</b></h4>
                                   <p class="text-blue"><b>$' . $item->item_price . '</b></p>
                                   <p class="text-blue inven-name"><b>Stock : ' . $item->inv_name . '</b></p></center>
                                   ' . $btn_block . '
                                   ' . $button . '
                               </div>
                           </div>
                       </div>';
                    }
                }
            }
            return $div;
        }
    }

    public function create()
    {
        //
    }

    public function store(Request $request, $Digit = 6)
    {
        $this->validate($request, [
            'sale_clientid' => 'required',
            'date_contract' => 'required'
        ]);
        $status = true;
        $items = Session::get('cart');
        $itemNames = [];
        if ($items == null) {
            return \back()->with('warning', 'Please Select An Item Before Booking');
        } else {
            foreach ($items as $cart) {
                $Item = ItemModel::find($cart['item_id']);
                if ($Item->available == 0) {
                    array_push($itemNames, $Item->item_house);
                    $status = false;
                }
            }
        }
        if ($status == false) {
            return redirect()->back()->with('danger', "Sorry, Item(s) " . implode(',', $itemNames) . " sold out a while ago");
        }

        $booking_amount     = empty($request->sale_receive)?0:$request->sale_receive;
        $agency_id          = $request->agency_id;
        $close_sale_id      = $request->close_sale_id;
        $client_id          = $request->sale_clientid;
        $date_contract      = $request->date_contract;
        $remark             = $request->remark;
        $total_items_amount = 0;
        $item_id            = null;
        foreach ($items as $key => $cart) {
            $total_items_amount += $cart['item_price'];
            $item_id            = $cart['item_id'];
        }
        $remain_amount      = $total_items_amount - $booking_amount - (empty($request->sale_discount_amount)?0:$request->sale_discount_amount);
        $remain_amount_ar      = $total_items_amount - $request->sale_discount_amount ;

        $item_stock         = ItemModel::find($item_id);
        $project_commission = $item_stock->commission;
        $project_condition  = $item_stock->condition;

        $update_status_client = array(
            'status_delete' => 2,
        );
        ClientModel::where('id', $client_id)->update($update_status_client);

        $salestock                              = new SaleStockModel();
        $salestock->sale_clientid               = $client_id;
        $salestock->agency_id                   = $agency_id;
        $salestock->close_sale_id               = $close_sale_id;
        $salestock->sale_type                   = 1;
        $salestock->sale_discount               = $request->sale_discount_amount;
        $salestock->sale_date                   = date("Y-m-d",strtotime($request->date_deposit));
        $salestock->sale_amount                 = $total_items_amount;
        $salestock->sale_datecontract           = $date_contract;
        $salestock->sale_receive                = $booking_amount;
        $salestock->sale_remain                 = $remain_amount;
        $salestock->sale_status                 = 1;
        $salestock->admin_commission            = $project_commission;
        $salestock->admin_commission_condition  = $project_condition;
        $salestock->approve_status              = 1;
        $salestock->deposit_remark              = $remark;
        $salestock->sale_type_by                = $request->sale_type_by;
        $salestock->sale_employees              = $request->employees;
        $salestock->save();

        $sale_stock_last_id = SaleStockModel::max('id');
        
        if(!empty($request->promotion_detail)&&!empty($request->promotion_detail[0])){
            
            DB::table("nso007_sale_promotion")
                ->insert([
                            'sale_id'=>$sale_stock_last_id,
                            'promotion_id'=>$request->promotion
                            ]);
            DB::table('nso007_promotion')->where("id",$request->promotion)->update(['status'=>1]);
                    
            if(!empty($request->promotion_detail[0]))
            {
                if(count($request->promotion_detail)>0){
                    foreach($request->promotion_detail as $key=>$value)
                    {
                        
                        DB::table("nso007_sale_promotion_detail")
                        ->insert([
                                    'sale_id'=>$sale_stock_last_id,
                                    'promotion_detail_id'=>$value,
                                    'qty'=>$request->product_qty[$key],
                                    'type'=>0
                                ]);
                        DB::table("nso007_promotion_detail")->where("id",$value)->increment('qty_used',$request->product_qty[$key]); 
                        DB::table("nso007_promotion_detail")->where("id",$value)->update(['status'=>1]);
                        
                        
                    }
                }
            }
            
        }
        
        if(isset($request->payment_policy))
        {
            DB::table("nso007_sale_policy_payment")->insert(['sale_id'=>$sale_stock_last_id,'policy_detail_id'=>$request->payment_policy_detail,'payment_policy_id'=>$request->payment_policy]);
            DB::table('nso007_payment_policy')->where("id",$request->payment_policy)->update(['status'=>1]);
            DB::table('nso007_payment_policy_detail')->where("id",$request->payment_policy_detail)->update(['status'=>1]);
        }
        

        $item_cp_id="";
        foreach ($items as $key => $cart) {

            $salestockdetail = new SaleStockDetailModel();

            $salestockdetail->saledetail_saleid     = $sale_stock_last_id;
            $salestockdetail->saledetail_price      = $cart['item_price'];
            $salestockdetail->saledetail_itemid     = $cart['item_id'];
            $salestockdetail->save();
            $update_status = array(
                'item_salestatus' => 2,
                'available' => 0,
            );
            ItemModel::where('id', $cart['item_id'])->update($update_status);
            $item_cp_id = $cart['item_id'];
        }

        $branch = ItemModel::join("nso007_project_stock","nso007_project_stock.id","nso007_item_stock.item_projectid")->where("nso007_item_stock.id",$item_cp_id)->first()->branch_id;

        $prefix = DepositModel::join("nso007_sale_detail_stock","nso007_deposit.deposit_saleid","nso007_sale_detail_stock.saledetail_saleid")
                    ->join("nso007_item_stock","nso007_sale_detail_stock.saledetail_itemid","nso007_item_stock.id")
                    ->join("nso007_project_stock","nso007_project_stock.id","nso007_item_stock.item_projectid")
                    ->where('deposit_invoice','LIKE',date('Y')."%")
                    ->where("nso007_project_stock.branch_id",$branch)
                    ->orderBy('nso007_deposit.id','desc')
                    ->first();
        $auto_invoice = '';
        if(empty($prefix)){
            $auto_invoice = 1;
        }else{
            $invoice_code = explode('-',$prefix->deposit_invoice);
            $auto_invoice = (int)$invoice_code[1]+1;
        }

        $increas = date('Y').'-'.str_pad($auto_invoice, 6, "0", STR_PAD_LEFT);
        if ($booking_amount != null && $booking_amount > 0) {

            $nso007_deposit = new DepositModel();
            $nso007_deposit->deposit_saleid     = $sale_stock_last_id;
            $nso007_deposit->deposit_date       = date('Y-m-d');
            $nso007_deposit->deposit_amount     = $booking_amount;
            $nso007_deposit->status_num         = 1;
            $nso007_deposit->deposit_invoice    = $increas;
            $nso007_deposit->save();
        }

        $down_pay_id=0;
        if(!empty($request->itempro_payamount)&&!empty($request->itempro_payamount[0])){
            foreach ($request->itempro_payamount as $key => $payment_no){
                $nso007_deposit_schedule = new DepositScheduleModel();
                $nso007_deposit_schedule->ds_saleid     = $sale_stock_last_id;
                $nso007_deposit_schedule->ds_date       = date('Y-m-d',strtotime($request->itempro_date[$key]));
                $nso007_deposit_schedule->ds_amount     = $request->itempro_payamount[$key];
                $nso007_deposit_schedule->ds_status     = 1;
                $nso007_deposit_schedule->type          = $request->type[$key];
                $nso007_deposit_schedule->save();
                $down_pay_id++;
            }
        }

        $j=JournalModel::select(DB::raw("Max(journal_tran_id) as last_num"))->first();

        $journal=new JournalModel;
        $journal->branch_id=\Globals::get_branch_and_project_id($sale_stock_last_id,'branch_id');
        $journal->journal_parentid=0;
        $journal->journal_type=1;
        $journal->journal_acccode=11003;
        $journal->voucher_type=1;
        $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
        $journal->journal_des=\Globals::BookingBySaleID("", $sale_stock_last_id);
        $journal->journal_debit=$remain_amount_ar;
        $journal->journal_credit=0;
        $journal->journal_tran_id=$j->last_num+1;
        $journal->journal_transactiondate=date("Y-m-d");
        $journal->journal_paydate=date("Y-m-d",strtotime($request->date_deposit));
        $journal->journal_currency=1;
        $journal->transaction_type='Deposit';
        $journal->journal_referenceid=$sale_stock_last_id;
        $journal->journal_by_project=\Globals::get_branch_and_project_id($sale_stock_last_id,'project_id');
        $journal->journal_by=auth()->user()->id;
        $journal->save();
        $jj1=JournalModel::select(DB::raw("Max(id) as last_id"))->first();
        if (!empty($request->sale_discount_amount) || $request->sale_discount_amount > 0){
            $journal=new JournalModel;
            $journal->branch_id=\Globals::get_branch_and_project_id($sale_stock_last_id,'branch_id');
            $journal->journal_parentid=$jj1->last_id;
            $journal->journal_type=4;
            $journal->journal_acccode=41002;
            $journal->voucher_type=1;
            $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
            $journal->journal_des=\Globals::BookingBySaleID("", $sale_stock_last_id);
            $journal->journal_debit=$request->sale_discount_amount;
            $journal->journal_credit=0;
            $journal->journal_tran_id=$j->last_num+1;
            $journal->journal_transactiondate=date("Y-m-d");
            $journal->journal_paydate=date("Y-m-d",strtotime($request->date_deposit));
            $journal->journal_currency=1;
            $journal->transaction_type='Deposit Discount';
            $journal->journal_referenceid=$sale_stock_last_id;
            $journal->journal_by_project=\Globals::get_branch_and_project_id($sale_stock_last_id,'project_id');
            $journal->journal_by=auth()->user()->id;
            $journal->save();
        }
        $journal=new JournalModel;
        $journal->branch_id=\Globals::get_branch_and_project_id($sale_stock_last_id,'branch_id');
        $journal->journal_parentid=$jj1->last_id;
        $journal->journal_type=4;
        $journal->journal_acccode=41000;
        $journal->voucher_type=1;
        $journal->voucher_ref="V-".\Globals::generate_voucher_number(($j->last_num+1),8);
        $journal->journal_des=\Globals::BookingBySaleID("", $sale_stock_last_id);
        $journal->journal_debit=0;
        $journal->journal_credit=$total_items_amount;
        $journal->journal_tran_id=$j->last_num+1;
        $journal->journal_transactiondate=date("Y-m-d");
        $journal->journal_paydate=date("Y-m-d",strtotime($request->date_deposit));
        $journal->journal_currency=1;
        $journal->transaction_type='Deposit';
        $journal->journal_referenceid=$sale_stock_last_id;
        $journal->journal_by_project=\Globals::get_branch_and_project_id($sale_stock_last_id,'project_id');
        $journal->journal_by=auth()->user()->id;
        $journal->save();
        \LogActivity::addToLog('You have deposited successfully!');
        session()->forget('cart');
        return back()->with('success', 'Items Were Successfully Booked');
    }
    public function add_client(Request $request)
    {
        $this->validate($request, [
            'first_name'      => 'required',
            'last_name'       => 'required', 
            'client_phone1'   => 'required',
            'client_gender'   => 'required',
            'client_address'  => 'required'
        ]);
        $data = array(
            'client_firstname'   => $request->first_name,
            'client_lastname'   => $request->last_name,
            'client_phone1'     => $request->client_phone1,
            'client_gender'     => $request->client_gender==1?"Male":"Female",
            'client_address'    => $request->client_address
        );
        DB::table('nso007_client')->insert($data);
        echo \json_encode($data);
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

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

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
    public function add_to_cart($id)
    {
        $item = ItemModel::find($id);
        $status = '';
        if (!$item) {
            $status = "Item not Found!";
        } else {
            $cart = session()->get('cart');
            if (!$cart) {
                $cart = [
                    $id => [
                        "item_id" => $item->id,
                        "item_name" => $item->item_house,
                        "quantity" => 1,
                        "item_price" => $item->item_price,
                        "item_cost" => $item->item_cost,
                        "photo" => $item->photo
                    ]
                ];

                session()->put('cart', $cart);
                $status = 'success';
            } else {
                if (isset($cart[$id])) {
                    session()->flash('danger', 'Item was already added!');
                    $status = 'error';
                } else {
                    $cart[$id] = [
                        "item_id" => $item->id,
                        "item_name" => $item->item_house,
                        "quantity" => 1,
                        "item_price" => $item->item_price,
                        "item_cost" => $item->item_cost,
                        "photo" => $item->photo
                    ];
                    session()->put('cart', $cart);
                    $status = "success";
                }
            }
        }
        echo json_encode($status);
    }
    public function remove(Request $request)
    {
        if ($request->id) {

            $cart = session()->get('cart');

            if (isset($cart[$request->id])) {

                unset($cart[$request->id]);

                session()->put('cart', $cart);
            }
            return response()->json(['success'=>true,'status'=>200,'data'=>'item removed successfully']);
        }
    }
    public function new_client(Request $request)
    {

        $clients = ClientModel::all();
        echo \json_encode($clients);
    }
    public function get_cart()
    {
        $cart = session()->get('cart');
        echo \json_encode($cart);
    }
    public function block_item(Request $request)
    {
        try {
            $cart = session()->get('cart');
            if (isset($cart[$request->id])) {
                unset($cart[$request->id]);
                session()->put('cart', $cart);
            }

            $item_id    = $request->id;
            $hour       = empty($request->hour) ? null : $request->hour;
            $item       = ItemModel::find($item_id);
            $item->block_status = 2;
            $item->update();

            BlockedItemModel::insert([
                'date'      => date('Y-m-d H:i:s A'),
                'hour'      => $item->item_block_time,
                'item_id'   => $item_id,
                'user_id'   => Auth::user()->id
            ]);
            $data = ['success'=>true,'status'=>200,'data'=>'Item Successfully Blocked'];
        } catch (\Illuminate\Database\QueryException $ex) {
            $data = ['success'=>false,'status'=>502,'data'=>$ex->getMessage()];
        }
        return response()->json($data);
    }
    public function unblock_item(Request $request)
    {

        DB::table('nso007_item_stock')->where('id', $request->id)->update([
            'block_status' => 1
        ]);
        BlockedItemModel::where('item_id', $request->id)->delete();
        echo json_encode($request->id);
    }
    public function blocked_item(Request $request)
    {
        $data = DB::table('nso007_item_stock as item')
            ->join('nso007_blocked_item as block', 'block.item_id', 'item.id')
            ->select('item.*')
            ->where([['item_salestatus', 0], ['block.user_id', Auth::user()->id]])
            ->where([['available', 1], ['block_status', 2]])->orderBy('item_id','asc')
            ->paginate(30);
        if ($request->ajax()) {
            return view('administrator.pos.pre-blocked-items', ['data' => $data]);
        }
        return view('administrator.pos.blocked-item', ['data' => $data]);
    }

    //block time feature
    public function time_list()
    {
        return view('administrator.pos.block-time');
    }
    public function get_time_list()
    {
        $time = DB::table('nso007_block_time')->where('status', 1)->get();
        return DataTables::of($time)
            ->addIndexColumn()
            ->addColumn('action', function ($time) {
                $edit = '';
                $delete = '';
                if (Gate::check('POS-Block-Time-Edit')) {
                    $edit = '<a style="color:white;margin-left:0;" data-id="' . $time->id . '" data-hour="' . $time->hour . '" href="#" class="btn_edit_time button_info btn-circle btn-xs"><i class="fa fa-pencil" title="Edit Time"></i></a>';
                }
                if (Gate::check('POS-Block-TIme-Delete')) {
                    $delete = '<a style="color:white;margin-left:0;" data-id="' . $time->id . '" data-hour="' . $time->hour . '" href="#" class="btn_remove_time button_danger btn-circle btn-xs"><i class="fa fa-trash" title="Remove Time"></i></a>';
                }
                return $edit . $delete;
            })
            ->make(true);
    }
    public function store_time(Request $request)
    {
        $this->validate($request, [
            'hour' => 'required'
        ]);
        DB::table('nso007_block_time')->insert([
            'hour' => $request->hour
        ]);
        return back()->with('success', 'Time Created Successfully');
    }
    public function update_time(Request $request, $id)
    {
        DB::table('nso007_block_time')->where('id', $id)->update([
            'hour' => $request->hour
        ]);
        return back()->with('success', 'Time Updated Sucessfully');
    }
    public function delete_time($id)
    {
        DB::table('nso007_block_time')->where('id', $id)->update([
            'status' => 0
        ]);
        return back()->with('success', 'Time Removed Sucessfully');
    }
    public function moveToCart($id)
    {
        ItemModel::where('id', $id)->update([
            'block_status'  => 1
        ]);
        BlockedItemModel::where('item_id', $id)->delete();
        $item = ItemModel::find($id);
        $status = '';
        if (!$item) {
            $status = "Item not Found!";
        } else {
            $cart = session()->get('cart');
            if (!$cart) {

                $cart = [
                    $id => [
                        "item_id" => $item->id,
                        "item_name" => $item->item_house,
                        "quantity" => 1,
                        "item_price" => $item->item_price,
                        "item_cost" => $item->item_cost,
                        "photo" => $item->photo
                    ]
                ];

                session()->put('cart', $cart);
                // session()->flash('success', 'Item was successfully added!');
                $status = 'success';
            } else {
                if (isset($cart[$id])) {
                    // $cart[$id]['quantity']++;
                    // session()->put('cart', $cart);
                    session()->flash('danger', 'Item was already added!');
                    $status = 'error';
                } else {
                    // if item not exist in cart then add to cart with quantity = 1
                    $cart[$id] = [
                        "item_id" => $item->id,
                        "item_name" => $item->item_house,
                        "quantity" => 1,
                        "item_price" => $item->item_price,
                        "item_cost" => $item->item_cost,
                        "photo" => $item->photo
                    ];

                    session()->put('cart', $cart);
                    $status = "success";
                }
            }
        }
        echo json_encode($status);
    }
    //block time feature
    public function get_promotion_by_deposit_date(Request $request)
    {
        $date_posit = date("Y-m-d",strtotime($request->deposit_date));
        return json_encode(DB::table("nso007_promotion")->where("to_date",">=",$date_posit)->where("from_date","<=",$date_posit)->get());
    }
}
