<?php

namespace App\Http\Controllers\Administrator;

use App\Classes\AgencyCommission;

use App\ItemTransferModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\CategoryModel;
use App\SubCategoryModel;
use App\ProjectModel;
use App\ItemModel;
use App\ClientModel;
use App\SaleStockModel;
use App\SaleStockDetailModel;
use App\JournalModel;
use App\DepositModel;
use App\ItemGroupModel;
use App\CommissionModel;
use App\CommissionItemModel;
use App\AccessoriesModel;
use App\RaiseItemAmount;
use App\ItemZoneModel;
use DataTables;
use App\Fun\Fun;
use App\InventoryModel;
use DB;
use Auth;
use Illuminate\Support\Facades\Crypt;
use Image;
use Gate;
use App\User;
use Session;
use function GuzzleHttp\Psr7\str;
use App\BranchModel;

class ItemController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:Item-List');
        $this->middleware('permission:Item-House-Create', ['only' => ['create', 'store']]);
        $this->middleware('permission:Item-Edit', ['only' => ['edit', 'update', 'edit_multi']]);
        // $this->middleware('permission:Item-Commission-Edit', ['only' => ['edit_multi_commission']]);
        $this->middleware('permission:Item-Delete', ['only' => ['items_delete']]);

    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categories = CategoryModel::select(
            DB::raw('CONCAT(category_code," | ",category_name) AS category_mixed'),
            'id'
        )
        ->pluck('category_mixed', 'id');

        $sub_categories = SubCategoryModel::select(
            DB::raw('CONCAT(sub_category_code," | ",sub_category_name) AS sub_category_mixed'),
            'id'
        )
        ->pluck('sub_category_mixed', 'id');

        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })->select(
                DB::raw('CONCAT(project_code," | ",project_name) AS project_mixed'),
                'id'
            )
            ->pluck('project_mixed', 'id');

        $item_zone = ItemZoneModel::select(
                DB::raw('nso007_item_zone.item_zone_name'),
                'nso007_item_zone.id'
            )
            ->pluck('item_zone_name', 'id');

        $item_group = ItemGroupModel::select(
                DB::raw('item_group_name'),'id'
            )
            ->pluck('item_group_name', 'id');

        return view('administrator.items.index',compact('categories','sub_categories','projects','item_zone','item_group'));
    }

    public function datatable_get_items(Request $request)
    {
        $project_id = $request->project_id;
        $category_id = $request->category_id;
        $sub_category_id = $request->sub_category_id;
        $item_group_id = $request->item_group_id;
        $item_zone_id = $request->item_zone_id;
        $item_name = $request->item_name;
        $items = ItemModel::join('nso007_category_stock', 'nso007_category_stock.id', 'nso007_item_stock.item_categoryid')
            ->leftJoin('nso007_sub_category_stock', 'nso007_sub_category_stock.id', 'nso007_item_stock.item_sub_categoryid')
            ->join('nso007_project_stock', 'nso007_project_stock.id', 'nso007_item_stock.item_projectid')
            ->leftJoin('nso007_item_group', 'nso007_item_group.id', 'nso007_item_stock.item_groupid')
            ->leftJoin('nso007_item_zone', 'nso007_item_zone.id', 'nso007_item_stock.item_zone_id')
            ->select(
                'nso007_category_stock.category_name',
                'nso007_sub_category_stock.sub_category_name',
                'nso007_project_stock.project_name',
                'nso007_item_stock.item_salestatus',
                'nso007_item_stock.item_stockstatus',
                'nso007_item_stock.item_price',
                'nso007_item_stock.item_cost',
                'nso007_item_stock.commission_amount',
                'nso007_item_stock.commission',
                'nso007_item_stock.condition',
                'nso007_item_stock.available',
                'nso007_item_stock.item_title_number',
                'nso007_item_stock.id',
                'nso007_item_stock.item_size_house',
                'nso007_item_stock.item_size_land',
                'nso007_item_stock.item_house',
                'nso007_item_zone.item_zone_name',
                'nso007_item_group.item_group_name'
            )
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->when(request('project_id'),function($query) use($project_id){
                $query->whereIn("nso007_item_stock.item_projectid",$project_id);
            })
            ->when(request('category_id'),function($query) use($category_id){
                $query->whereIn("nso007_item_stock.item_categoryid",$category_id);
            })
            ->when(request('sub_category_id'),function($query) use($sub_category_id){
                $query->whereIn("nso007_item_stock.item_sub_categoryid",$sub_category_id);
            })
            ->when(request('item_group_id'),function($query) use($item_group_id){
                $query->whereIn("nso007_item_stock.item_groupid",$item_group_id);
            })
            ->when(request('item_zone_id'),function($query) use($item_zone_id){
                $query->whereIn("nso007_item_stock.item_zone_id",$item_zone_id);
            })
            ->when(request('item_name'),function($query) use($item_name){
                $query->where("nso007_item_stock.item_house","LIKE","%".$item_name."%");
            })
            ->where(function ($query) {
                $query->where('nso007_item_stock.transfer_status', 0)->orWhere('nso007_item_stock.transfer_status', 1);
            })
            ->orderBy('id', 'asc')
            ->get();
        return Datatables::of($items)
            ->addIndexColumn()
            ->addColumn('action', function ($items) {
                $btn_edit = "";
                $btn_delete = "";
                if (Gate::check('Item-Edit'))
                    $btn_edit .= '<a href="' . Route("items.edit", Crypt::encrypt($items->id)) . '"  class="button_success fa fa-edit" data-toggle="tooltip" data-placement="top" title="Edit"></a>';
                if ($items->item_salestatus == 0 && $items->item_stockstatus == 1) {
                    // if (Gate::check('Item-Edit'))
                    //     $btn_edit .= '<a href="' . Route("items.edit", Crypt::encrypt($items->id)) . '"  class="button_success fa fa-edit" data-toggle="tooltip" data-placement="top" title="Edit"></a>';
                    if (Gate::check('Item-Delete'))
                        $btn_delete .= ' <a href="#" data-id = "' . $items->id . '" data-toggle="modal" data-target="#form-delete" class="button_danger fa fa-trash confirm_delete" data-toggle="tooltip" data-placement="top" title="Delete"></a>';
                }
                return $btn_edit . $btn_delete;
            })
            ->addColumn('item_price', function ($items) {
                return '$' . number_format($items->item_price, 2);
            })
            ->addColumn('item_cost', function ($items) {
                return '$' . number_format($items->item_cost, 2);
            })
            ->editColumn('commission_amount', function ($items) {
                $commission_amount = number_format($items->commission_amount, 2) . " $";
                return  $commission_amount;
            })
            ->editColumn('commission', function ($items) {
                $commission = number_format($items->commission, 2) . " %";
                return  $commission;
            })
            ->editColumn('condition', function ($items) {
                $condition = number_format($items->condition, 2) . " %";
                return  $condition;
            })
            ->addColumn('item_size_house', function ($items) {

                $item_size_house = empty($items->item_size_house) ? '' : $items->item_size_house . ' m<sup>2</sup>';
                return  empty($item_size_house) ? '' : $item_size_house;
            })
            ->addColumn('item_size_land', function ($items) {
                $item_size_land = $items->item_size_land . ' m<sup>2</sup>';
                return  $item_size_land;
            })
            ->addColumn('available', function ($items) {
                $available = '';
                if ($items->available == 0) {
                    $available = '<label><strong class="text-red"> Unavailable</strong></label>';
                } else {
                    $available = '<label><strong class="text-blue"> Available</strong></label>';
                }
                return $available;
            })
            ->rawColumns([
                'action' => 'action',
                'available' => 'available',
                'item_size_land' => 'item_size_land',
                'item_size_house' => 'item_size_house',
            ])
            ->make(true);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $assessories = AccessoriesModel::all();

        $branches = BranchModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_branches.id', \Branch::branch_id());
            })
            ->select(
            DB::raw('CONCAT(id," ",branch_en," ",branch_kh) AS branch_name'),'id')
            ->pluck('branch_name','id');

        $categories = CategoryModel::select(
            DB::raw('CONCAT(category_code," | ",category_name) AS category_mixed'),
            'id'
        )
            ->pluck('category_mixed', 'id')
            ->prepend('Please Select', '');

        $sub_categories = SubCategoryModel::select(
            DB::raw('CONCAT(sub_category_code," | ",sub_category_name) AS sub_category_mixed'),
            'id'
        )
            ->pluck('sub_category_mixed', 'id')
            ->prepend('Please Select', '');

        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })->select(
                DB::raw('CONCAT(project_code," | ",project_name) AS project_mixed'),
                'id'
            )
            ->pluck('project_mixed', 'id')
            ->prepend('Please Select', '');
        $item_zone = ItemZoneModel::select(
                DB::raw('nso007_item_zone.item_zone_name'),
                'nso007_item_zone.id'
            )
            ->pluck('item_zone_name', 'id')
            ->prepend('Please Select', '');

        $item_group = ItemGroupModel::select(
                DB::raw('item_group_name'),
                'id'
            )
                ->pluck('item_group_name', 'id')
                ->prepend('Please Select', '');
        
        $item_group_option = ItemGroupModel::select(
                    DB::raw('item_group_name'),'id'
                )
                ->get();

        return view('administrator.items.create', compact('sub_categories','categories', 'projects', 'assessories', 'item_group', 'item_zone','branches','item_group_option'));
    }

    public function create_condo()
    {
        $assessories = AccessoriesModel::all();

        $branches = BranchModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_branches.id', \Branch::branch_id());
            })
            ->select(
            DB::raw('CONCAT(id," ",branch_en," ",branch_kh) AS branch_name'),'id')
            ->pluck('branch_name','id');

        $item_group = ItemGroupModel::select(
            DB::raw('item_group_name'),
            'id'
        )
        ->where("item_group_cat_id",3)
        ->pluck('item_group_name', 'id')
        ->prepend('Please Select', '');

        $projects = ProjectModel::select(
            DB::raw('CONCAT(project_code," | ",project_name) AS project_mixed'),'id')
            ->pluck('project_mixed','id')
            ->prepend('Please Select', '');

        $categories = CategoryModel::select(
            DB::raw('CONCAT(category_code," | ",category_name) AS category_mixed'),
            'id'
        )
            ->pluck('category_mixed', 'id')
            ->prepend('Please Select', '');

        return view('administrator.items.create_condo',compact('projects','assessories','item_group','categories','branches'));
    }

    public function save_create_condo(Request $request)
    {
        // dd($request->all());
        $this->validate($request, [
            'item_projectid'      => 'required',
            // 'item_groupid'      => 'required',
            'item_block_time'      => 'required',
            'item_develop_by'      => 'required',
            'item_type'      => 'required',
            'item_title'      => 'required',
            'item_price.*'      => 'required|numeric',
            'item_house.*'      => 'required',
            // 'item_name' 	=> 'required|unique:nso007_item_stock,item_name',
            // 'image'     => 'dimensions:height=300,width=525'
            'category_type'=>'required'
        ]);


        // $group = ItemGroupModel::find($request->item_groupid);
        // $group->item_group_status  = 1;
        // $group->update();
        $project = ProjectModel::find($request->item_projectid);
        DB::beginTransaction();
        try{

            foreach ($request->item_name as $key => $value)
            {
                $assessor   =  $request->accessory;
                $item_accessories = "";
                if($assessor!= null){
                    foreach($assessor as $keys =>$v){
                       $item_accessories .= $v.',';
                    }
                }
                $gallery = '';
                // if($files = $request->file('gallery'))
                // {
                //     foreach($files as $file)
                //     {
                //         $original_name = $file->getClientOriginalName();
                //         $original_name = date('ymdhis') . $original_name;
                //         $destinationPath = 'assets/images/resize/784x500';
                //         $thum = Image::make($file->getRealPath())->resize(525, 230);
                //         $thum->save($destinationPath . '/' . $original_name, 80);
                //         $gallery .= $original_name .'||';
                //     }
                // }
                $items = array(
                    'item_categoryid'    =>$request->category_type,
                    'item_create_type'   =>3,
                    'item_accessories'      => $item_accessories, 
                    'item_projectid'        => $request->item_projectid, 
                    'item_develop_by'       => $request->item_develop_by,
                    'item_type'             => $request->item_type, 
                    'available'             => $request->available[$key], 
                    'item_name'             => $request->item_name[$key], 
                    'item_price'            => $request->item_price[$key],
                    'item_house'            => $request->item_house[$key],
                    'commission_amount'     =>$request->commission_amount_g[$key], 
                    'commission'            => $request->commission_percentage_g[$key], 
                    'condition'             => $request->commission_condition_g[$key], 
                    'item_cost'             => $request->item_cost[$key], 
                    'item_size_house'       => $request->size_house[$key],
                    'item_floor'            => $request->item_floor, 
                    'item_title'            => $request->item_title, 
                    'item_des'              => $request->item_des, 
                    'item_sq_fp'            => $request->item_sq_fp, 
                    'item_parking'          => $request->item_parking, 
                    'item_completed_year'   => $request->item_completed_year,
                    'item_block_time'       => $request->item_block_time,
                    'item_groupid'       => $request->item_groupid,
                    'item_bedroom'    =>$request->item_bedroom,
                    'item_bathroom'=>$request->item_bathroom,
                    'user_id' => Auth::user()->id,
                    'transfer_status'       =>  0,
                );
                ItemModel::insert($items);
            }
            DB::commit();
            \LogActivity::addToLog('Item Created successfully!');
            return redirect()->route('items.index')
            ->with('success','Item Created successfully!');
        }catch(\Exception $e){
            DB::rollback();
            \LogActivity::addToLog('Sothing wrong !');
            return redirect()->route('items.index')
            ->with('danger','Sothing wrong !');
        
        }
        
    }

    public function ajax_get_project_commission($id)
    {
        $data = ProjectModel::find($id);
        echo json_encode($data);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'item_categoryid'      => 'required',
            'item_sub_categoryid'      => 'required',
            'item_projectid'      => 'required',
            'item_groupid'      => 'required',
            'item_zone_id'      => 'required',
            'item_block_time'      => 'required',
            'item_develop_by'      => 'required',
            'item_type'      => 'required',
            'item_price.*'      => 'required|numeric',
            // 'item_street.*'      => 'required',
            'item_house.*'      => 'required',
            // 'item_name'     => 'required|unique:nso007_item_stock,item_name'
        ]);

        $group = ItemGroupModel::find($request->item_groupid);
        $group->item_group_status  = 1;
        $group->update();

        $zone = ItemZoneModel::find($request->item_zone_id);
        $zone->item_zone_status  = 1;
        $zone->update();

        $projectid = ProjectModel::find($request->item_projectid);
        $projectid->status  = 0;
        $projectid->update();

        $categoryid = CategoryModel::find($request->item_categoryid);
        $categoryid->status  = 0;
        $categoryid->update();

        $sub_categoryid = SubCategoryModel::find($request->item_sub_categoryid);
        $sub_categoryid->sub_category_status  = 1;
        $sub_categoryid->update();

        DB::beginTransaction();
        try {
            $items_array = [];
            foreach ($request->item_name as $key => $value) {


                $assessor   =  $request->accessory;
                $item_accessories = "";
                if ($assessor != null) {
                    foreach ($assessor as $keys => $v) {
                        $item_accessories .= $v . ',';
                    }
                }         
                $items = array(
                    'item_categoryid'       => $request->item_categoryid,
                    'item_sub_categoryid'       => $request->item_sub_categoryid,
                    'item_accessories'      => $item_accessories,
                    'item_projectid'        => $request->item_projectid,
                    'item_zone_id'          => $request->item_zone_id,
                    'item_develop_by'       => $request->item_develop_by,
                    'item_posted'           => date("Y-m-d"),
                    'item_type'             => $request->item_type,
                    'available'             => $request->available[$key],
                    'item_name'             => $request->item_name[$key],
                    'item_title_number'     => $request->title_number[$key],
                    'item_price'            => $request->item_price[$key],
                    'item_zone'             => $request->prefix_house,
                    'item_street'           => $request->item_street,
                    'item_house'            => $request->item_house[$key],
                    'commission_amount'     => $request->commission_amount_g[$key],
                    'commission'            => $request->commission_percentage_g[$key],
                    'condition'             => $request->commission_condition_g[$key],
                    'item_cost'             => $request->item_cost[$key],
                    'item_size_house'       => $request->size_house[$key],
                    'item_size_land'        => $request->size_land[$key],
                    'item_width_house'      => $request->item_width_house,
                    'item_length_house'     => $request->item_length_house,
                    'item_width_land'       => $request->item_width_land,
                    'item_length_land'      => $request->item_length_land,
                    'item_bordering_north'  => $request->item_bordering_north,
                    'item_bordering_south'  => $request->item_bordering_south,
                    'item_bordering_west'   => $request->item_bordering_west,
                    'item_bordering_east'   => $request->item_bordering_east,
                    'item_bathroom'         => $request->item_bathroom,
                    'item_bedroom'          => $request->item_bedroom,
                    'item_floor'            => $request->item_floor,
                    'item_title'            => $request->item_title,
                    'item_des'              => $request->item_des,
                    'item_sq_fp'            => $request->item_sq_fp,
                    'item_parking'          => $request->item_parking,
                    'item_completed_year'   => $request->item_completed_year ? date('Y-m-d', strtotime($request->item_completed_year)) : null,
                    'item_block_time'       => $request->item_block_time,
                    'item_groupid'          => $request->group_item[$key],
                    'transfer_status'       =>  0,
                    'item_count'            => $request->item_count,
                    'item_create_type'      => 1,
                    'user_id'               => Auth::user()->id
                );


                ItemModel::insert($items);
            }
            DB::commit();
            \LogActivity::addToLog('Item Created successfully!');
            return redirect()->route('items.index')
                ->with('success', 'Item Created successfully!');
        } catch (\Exception $e) {
            DB::rollback();
            \LogActivity::addToLog('Sothing wrong !');
            return redirect()->route('items.index')
                ->with('danger', 'Sothing wrong !');
        }
    }

    /**
     * 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)
    {
        $assessories    = AccessoriesModel::all();
        $decrypt_id     = Crypt::decrypt($id);
        $items          = ItemModel::find($decrypt_id);

        $categories     = CategoryModel::pluck('category_name', 'id')->prepend('Please Select', '')->toArray();
        $projects       = ProjectModel::pluck('project_name', 'id')->prepend('Please Select', '')->toArray();

        $item_zone = ItemZoneModel::select(
            DB::raw('nso007_item_zone.item_zone_name'),
            'nso007_item_zone.id'
        )
        ->pluck('item_zone_name', 'id')
        ->prepend('Please Select', '');
        
        $item_group = ItemGroupModel::select(
                DB::raw('item_group_name'),
                'id'
            )
                ->pluck('item_group_name', 'id')
                ->prepend('Please Select', '');
                
        return view('administrator.items.edit', compact('items', 'categories', 'projects', 'assessories', 'item_group', 'item_zone'));
    }
    public function edit_multi()
    {
        $assessories = AccessoriesModel::all();

        $categories = CategoryModel::select(
            DB::raw('CONCAT(category_code," | ",category_name) AS category_mixed'),
            'id'
        )
            ->pluck('category_mixed', 'id')
            ->prepend('Please Select', '');
        $item_group = ItemGroupModel::select(
            DB::raw('item_group_name'),
            'id'
        )
            ->pluck('item_group_name', 'id')
            ->prepend('Please Select', '');

        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })->select(
                DB::raw('CONCAT(project_code," | ",project_name) AS project_mixed'),
                'id'
            )
            ->pluck('project_mixed', 'id')
            ->prepend('Please Select', '');

        $items = [];
        $item_zone = ItemZoneModel::select(
            DB::raw('item_zone_name'),
            'id'
        )
            ->pluck('item_zone_name', 'id')
            ->prepend('Please Select', '');
            
        return view('administrator.items.edit-multiple', compact('items', 'item_group', 'categories', 'projects', 'assessories', 'item_zone'));
    }
    public function filterItem(Request $request)
    {
        $projectID  = $request->projectID;
        $categoryID = $request->categoryID;
        $zoneID     = $request->zoneID;
        $groupID    = $request->groupID;
        $itemID     = $request->itemID;
        $zone       = null;
        $group      = null;
        $item       = null;
        if (!empty($projectID) || !empty($categoryID)) {
            $zone = ItemZoneModel::when($projectID, function ($query, $projectID) {
                $query->where('item_zone_pro_id', $projectID);
            })->when($categoryID, function ($query, $categoryID) {
                $query->where('item_zone_cat_id', $categoryID);
            })->get();
            $group = ItemGroupModel::when($projectID, function ($query, $projectID) {
                $query->where('item_group_pro_id', $projectID);
            })->when($categoryID, function ($query, $categoryID) {
                $query->where('item_group_cat_id', $categoryID);
            })->get();
        }

        $item = DB::table('nso007_item_stock as item')
            ->join('nso007_category_stock as category', 'category.id', 'item.item_categoryid')
            ->join('nso007_project_stock as project', 'project.id', 'item.item_projectid')
            ->join('nso007_item_group as group', 'group.id', 'item.item_groupid')
            ->join('nso007_item_zone as zone', 'zone.id', 'item.item_zone_id')
            ->when($projectID, function ($query, $projectID) {
                $query->where('item_projectid', $projectID);
            })->when($categoryID, function ($query, $categoryID) {
                $query->where('item_categoryid', $categoryID);
            })
            ->when($zoneID, function ($query, $zoneID) {
                $query->where('item_zone_id', $zoneID);
            })
            ->when($groupID, function ($query, $groupID) {
                $query->where('item_groupid', $groupID);
            })
            ->when($itemID, function ($query, $itemID) {
                $query->whereIn('item.id', $itemID);
            })
            ->where('available', 1)
            ->select(
                'item.item_groupid',
                'item.item_zone_id',
                'item.id', 
                'item.commission_amount',
                'item.commission', 
                'item.item_price', 
                'item.item_house', 
                'category.category_name',
                'project.project_name',
                'group.item_group_name as group_name', 
                'zone.item_zone_name as zone_name',
                'item.item_title_number'
            )
            ->get();
        echo json_encode(['item' => $item, 'zone' => $zone, 'group' => $group]);
    }
    public function filterByid(Request $request)
    {
        $id = $request->id;
        $item = DB::table('nso007_item_stock as item')
            ->join('nso007_category_stock as category', 'category.id', 'item.item_categoryid')
            ->join('nso007_project_stock as project', 'project.id', 'item.item_projectid')
            ->join('nso007_item_group as group', 'group.id', 'item.item_groupid')
            ->join('nso007_item_zone as zone', 'zone.id', 'item.item_zone_id')
            ->select('item.id', 'item.commission_amount', 'item.commission', 'item.item_price', 'item.item_house', 'category.category_name', 'project.project_name', 'group.item_group_name as group_name', 'zone.item_zone_name as zone_name')
            ->where('available', 1)
            ->when($request->id, function ($query, $id) {
                $query->whereIn('item.id', $id);
            })->get();
        echo json_encode($item);
    }

    public function update_multi(Request $request)
    {
        $this->validate($request, [
            'item_id'       => 'required',
            'new_price'     => 'required'
        ]);

        $item_id    = $request->item_id;
        $new_price  = $request->new_price;

        foreach ($item_id as $key => $id) {
            $items  = ItemModel::where('id', $id);
            $data   = $items->first();
            RaiseItemAmount::insert([
                'item_id'       => $data->id,
                'previous_price' => $data->item_price,
                'raise_amount'  => $new_price[$key],
                'remark'        => $request->remark
            ]);
            $items->update([
                'item_price'    => !empty($new_price[$key])?$new_price[$key]:DB::raw('item_price'),
                'item_house'    => $request->item_house_new[$key],
                'item_zone_id'  => $request->item_zone_new[$key],
                'item_groupid'  => $request->item_group_new[$key],
                'item_title_number' => $request->item_title_number_new[$key]
            ]);
        }
        \LogActivity::addToLog('Item increase amount successfully!');
        return redirect()->route('items.index')
            ->with('success', 'Item increase amount successfully!');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // dd($request->all());
        $item = ItemModel::find($id);
        $this->validate($request, [
            'item_develop_by'      => 'required',
            'item_price'      => 'required|numeric',
            'item_type'      => 'required',
        ]);
        try {
            DB::beginTransaction();
            ItemModel::where('id', $id)
                ->update([
                    'item_categoryid'       => $request->item_categoryid,
                    'item_projectid'        => $request->item_projectid,
                    'item_groupid'          => $request->item_groupid,
                    'item_zone_id'          => $request->item_zone_id,
                    'item_title'            => $request->item_title,
                    'commission_amount'     => ($request->commission_type == 1) ? $request->commission_amount : 0,
                    'commission'            => ($request->commission_type == 2) ? $request->commission : 0,
                    'item_width_land'       => $request->item_width_land,
                    'item_length_land'      => $request->item_length_land,
                    'item_size_land'        => $request->item_size_land,
                    'item_bordering_north'  => $request->item_bordering_north,
                    'item_bordering_south'  => $request->item_bordering_south,
                    'item_bordering_west'   => $request->item_bordering_west,
                    'item_bordering_east'   => $request->item_bordering_east,
                    'item_cost'             => $request->item_cost,
                    'item_develop_by'       => $request->item_develop_by,
                    'item_sq_fp'            => $request->item_sq_fp,
                    'item_parking'          => $request->item_parking,
                    'item_street'           => $request->item_street,
                    'item_house'            => $request->item_house,
                    'item_completed_year'   => !empty($request->item_completed_year) ? date('Y-m-d', strtotime($request->item_completed_year)) : '',
                    'item_block_time'       => $request->item_block_time,
                    'item_count'            => $request->item_count,
                    'item_des'              => $request->item_des,
                    'item_price'            => $request->item_price,
                    'item_title_number'     => $request->item_title_number
                ]);
            if ($item->item_create_type == 1) {
                ItemModel::where('id', $id)->update([
                    'item_width_house'  => $request->item_width_house,
                    'item_length_house' => $request->item_length_house,
                    'item_size_house'   => $request->item_size_house,
                    'item_bedroom'      => $request->item_bedroom,
                    'item_bathroom'     => $request->item_bathroom,
                    'item_floor'        => $request->item_floor
                ]);
            }
            DB::commit();
            \LogActivity::addToLog('Item updated successfully!');
            return redirect()->route('items.index')
                ->with('success', 'Item updated successfully!');
        } catch (\Exception $ex) {
            return redirect()->route('items.index')
                ->with('warning', 'Item not updated!' . $ex->getMessage());
        }
    }


    public function items_booking($id)
    {
        $decrypt_id = Crypt::decrypt($id);
        $item = ItemModel::find($decrypt_id);

        return view('administrator.items.item-booking', compact('item'));
    }

    public function edit_multi_commission($value = '')
    {
        $assessories = AccessoriesModel::all();

        $item_group = ItemGroupModel::select(
            DB::raw('item_group_name'),
            'id'
        )
            ->pluck('item_group_name', 'id')
            ->prepend('Please Select', '');

        $categories = CategoryModel::select(
            DB::raw('CONCAT(category_code," | ",category_name) AS category_mixed'),
            'id'
        )
            ->pluck('category_mixed', 'id')
            ->prepend('Please Select', '');

        $projects = ProjectModel::select(
            DB::raw('CONCAT(project_code," | ",project_name) AS project_mixed'),
            'id'
        )
            ->pluck('project_mixed', 'id')
            ->prepend('Please Select', '');
        $items = [];
        $item_zone = ItemZoneModel::select(
            DB::raw('item_zone_name'),
            'id'
        )
            ->pluck('item_zone_name', 'id')
            ->prepend('Please Select', '');
        return view('administrator.items.edit-multiple-commission', compact('item_group', 'item_zone', 'categories', 'projects', 'assessories', 'items'));
    }
    public function edit_multi_commission_item($proid = '', $groupid = '', $catid = '', $zoneid = '')
    {
        // $items=ItemModel::where("item_projectid",$value)->where("available",1)->select("item_name","id")->get();
        $items = DB::table("nso007_item_stock")
            ->join("nso007_project_stock", "nso007_item_stock.item_projectid", "nso007_project_stock.id")
            ->join("nso007_category_stock", "nso007_item_stock.item_categoryid", "nso007_category_stock.id")
            ->when((!empty($proid)), function ($query) use ($proid) {
                $query->where('item_projectid', $proid);
            })
            ->when((!empty($groupid)), function ($query) use ($groupid) {
                $query->where('item_groupid', $groupid);
            })
            ->when((!empty($zoneid)), function ($query) use ($zoneid) {
                $query->where('item_zone_id', $zoneid);
            })
            ->when((!empty($catid)), function ($query) use ($catid) {
                $query->where('item_categoryid', $catid);
            })
            ->where("available", 1)
            ->select(
                "nso007_item_stock.item_name",
                "nso007_item_stock.id",
                "nso007_project_stock.commission_amount",
                "nso007_project_stock.commission",
                "nso007_project_stock.condition"
            )
            ->get();
        echo json_encode($items);
    }

    public function edit_multi_commission_item_info($value = '')
    {
        $item = ItemModel::where("id", $value)->where("available", 1)->select("commission_amount", "commission", "condition", "item_projectid", "item_name", "id")->first();
        echo json_encode($item);
    }

    public function update_commission(Request $request)
    {
        $this->validate($request, [
            'item_id' => 'required'
        ]);
        if (empty($request->newCom_percent) && empty($request->newCom_amount)) {
            return redirect()->back()->with('danger', 'New Commission is required');
        }
        $itemid = $request->item_id;
        $commA  = $request->newCom_amount;
        $commP  = $request->newCom_percent;
        foreach ($itemid as $key => $id) {
            $item = ItemModel::where('id', $id);
            $data = $item->first();
            RaiseItemAmount::insert([
                'item_id'           => $id,
                'previous_comm'     => $data->commission_amount,
                'new_comm'          => $commA[$key],
                'previous_percent'  => $data->commission,
                'new_percent'       => $commP[$key],
                'user_id'           => Auth::user()->id
            ]);
            $item->update([
                'commission_amount' => $commA[$key],
                'commission'        => $commP[$key]
            ]);
        }
        \LogActivity::addToLog('You have updated commission successfully!');
        return redirect()->route('items.index')->with('success', 'You have updated successfully!');
    }

    public function items_booking_store(Request $request)
    {
        $agencycommission = new AgencyCommission;
        $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;
        $agency_type = $agencycommission->get_agencytype_by_agencyid($user_id);
        if ($agency_type == 0) {
            \LogActivity::addToLog('Super admin cannot booking!');
            return redirect()->route('items.index')
                ->with('danger', 'You cannot deposited!');
        } else {
            $client = new ClientModel();
            $salestock = new SaleStockModel();
            $salestockdetail = new SaleStockDetailModel();
            $journal = new JournalModel;
            $journal_one = new JournalModel;
            $journal_two = new JournalModel;
            $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->item_price;
            $deposit = $request->sale_receive;
            $debit_item_amount = $own_amount_item - $deposit;
            $sale_remark = "Sale Deposit: " . $request->item_name;


            $this->validate($request, [

                'sale_receive'      => 'required|numeric|min:500',
                'client_phone1'      => 'required',
                'client_address'      => 'required',
                'client_fullname'      => 'required',
                'client_gender'  => 'required',

            ]);

            $client->client_fullname = $request->client_fullname;
            $client->client_phone1 = $request->client_phone1;
            $client->client_address = $request->client_address;
            $client->client_status = 1;
            $client->client_gender = $request->client_gender;
            $client->client_userid = $user_id;
            $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 H:i:s");
            $salestock->sale_amount = $request->item_price;
            $salestock->sale_datecontract = $date_next_seven_day;
            $salestock->sale_receive = $request->sale_receive;
            $salestock->sale_remain = $debit_item_amount;
            $salestock->save();

            $sale_stock_last_id = SaleStockModel::max('id');

            $salestockdetail->saledetail_saleid = $sale_stock_last_id;
            $salestockdetail->saledetail_price = $request->item_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);

            $journal->journal_parentid = 0;
            $journal->journal_type = 13;
            $journal->journal_acccode = 11001;
            $journal->journal_des = $sale_remark;
            $journal->journal_debit = $debit_item_amount;
            $journal->journal_by = $user_id;
            $journal->journal_currency = 1;
            $journal->journal_referenceid = $user_id;
            $journal->save();
            $journal_id = JournalModel::max('id');

            $journal_one->journal_parentid = $journal_id;
            $journal_one->journal_type = 13;
            $journal_one->journal_acccode = 10000;
            $journal_one->journal_des = $sale_remark;
            $journal_one->journal_debit = $deposit;
            $journal_one->journal_by = $user_id;
            $journal_one->journal_currency = 1;
            $journal_one->journal_referenceid = $user_id;
            $journal_one->save();
            // $journal_id_nd = JournalModel::max('id');


            $journal_two->journal_parentid = $journal_id;
            $journal_two->journal_type = 13;
            $journal_two->journal_des = $sale_remark;
            $journal_two->journal_credit = $own_amount_item;
            $journal_two->journal_by = $user_id;
            $journal_two->journal_currency = 1;
            $journal_two->journal_referenceid = $user_id;
            $journal_two->save();

            // 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->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->item_price;
            $nso007_agency_commission->commission   =   3;
            $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->item_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    = 3;
                $commission_item->amount        = ($sale_price * 3 / 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    = 3;
                $commission_item->amount        = ($sale_price * 3 / 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->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    = 3;
                $commission_item->amount        = ($sale_price * 3 / 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->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->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    = 3;
                $commission_item->amount        = ($sale_price * 3 / 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->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->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->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    = 3;
                $commission_item->amount        = ($sale_price * 3 / 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->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->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->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->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    = 3;
                $commission_item->amount        = ($sale_price * 3 / 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->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->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->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->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->amount        = ($sale_price * 0.1 / 100);
                $commission_item_lvl6->save();
            }

            \LogActivity::addToLog('You have deposited successfully!');
            return redirect()->route('items.index')
                ->with('success', 'You have deposited successfully!');
        }
    }
    public function updatedPriceList(Request $request)
    {
        if ($request->ajax()) {
            $item = DB::table('nso007_item_stock_updated as update')
                ->join('nso007_item_stock as item', 'item.id', 'update.item_id')
                ->join('nso007_category_stock as category', 'category.id', 'item.item_categoryid')
                ->join('nso007_project_stock as project', 'project.id', 'item.item_projectid')
                ->join('nso007_item_group as group', 'group.id', 'item.item_groupid')
                ->join('nso007_item_zone as block', 'block.id', 'item.item_zone_id')
                ->select('update.previous_price as old_price', 'update.raise_amount as new_price', 'item.item_house as item_name', 'category.category_name', 'project.project_name', 'group.item_group_name as group_name', 'block.item_zone_name as block_name')
                ->whereNotNull('update.previous_price')
                ->orderBy('update.id', 'desc')
                ->get();
            return DataTables::of($item)
                ->addIndexColumn()
                ->editColumn('old_price', function ($item) {
                    return "$ " . number_format($item->old_price, 2);
                })
                ->editColumn('new_price', function ($item) {
                    return "$ " . number_format($item->new_price, 2);
                })
                ->make(true);
        }
        return view('administrator.item-history.price');
    }
    public function updatedCommList(Request $request)
    {
        if ($request->ajax()) {
            $item = DB::table('nso007_item_stock_updated as update')
                ->join('nso007_item_stock as item', 'item.id', 'update.item_id')
                ->join('nso007_category_stock as category', 'category.id', 'item.item_categoryid')
                ->join('nso007_project_stock as project', 'project.id', 'item.item_projectid')
                ->join('nso007_item_group as group', 'group.id', 'item.item_groupid')
                ->join('nso007_item_zone as block', 'block.id', 'item.item_zone_id')
                ->select('update.previous_comm as old_commission', 'update.previous_percent as old_percent', 'update.new_percent', 'update.new_comm as new_commission', 'item.item_house as item_name', 'category.category_name', 'project.project_name', 'group.item_group_name as group_name', 'block.item_zone_name as block_name')
                ->whereNull('update.previous_price')
                ->orderBy('update.id', 'desc')
                ->get();
            return DataTables::of($item)
                ->addIndexColumn()
                ->editColumn('old_commission', function ($item) {
                    $return = null;
                    if (empty($item->old_commission) || $item->old_commission == 0) {
                        $return = number_format($item->old_percent, 2) . " %";
                    } else {
                        $return = "$ " . number_format($item->old_commission, 2);
                    }
                    return $return;
                })
                ->editColumn('new_commission', function ($item) {
                    $return = null;
                    if (empty($item->new_commission) || $item->new_commission == 0) {
                        $return = number_format($item->new_percent, 2) . " %";
                    } else {
                        $return = "$ " . number_format($item->new_commission, 2);
                    }
                    return $return;
                })
                ->make(true);
        }
        return view('administrator.item-history.commission');
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function items_prefixcode(Request $request)
    {
        $project_code = $request->project_code;
        $category_code = $request->category_code;

        $category = CategoryModel::select('category_code')
            ->where('id', $category_code)
            ->get();
        $project = ProjectModel::select('project_code')
            ->where('id', $project_code)
            ->get();

        $data = array(
            'category' => $category,
            'project' => $project
        );

        echo json_encode($data);
    }

    public function get_group_house_item(Request $request)
    {
        $project_code = $request->project_code;
        $category_code = $request->category_code;

        $item_group = ItemGroupModel::select('id', 'item_group_name')
            ->where('item_group_cat_id', $category_code)->where('item_group_pro_id', $project_code)
            ->get();
        $item_zone = ItemZoneModel::select('id', 'item_zone_name')
            ->where('item_zone_cat_id', $category_code)->where('item_zone_pro_id', $project_code)
            ->get();

        echo json_encode(array('item_group'=>$item_group,'item_zone'=>$item_zone));
    }
    public function get_zone_house_item(Request $request)
    {
        $project_code = $request->project_code;
        $category_code = $request->category_code;

        $item_group = ItemZoneModel::select('id', 'item_zone_name')
            ->where('item_zone_cat_id', $category_code)->where('item_zone_pro_id', $project_code)
            ->get();
        echo json_encode($item_group);
    }

    public function get_group_update_item(Request $request)
    {
        $project_code = $request->project_code;
        $category_code = $request->category_code;

        $item_group = ItemGroupModel::select('id', 'item_group_name')
            ->where('item_group_cat_id', $category_code)->where('item_group_pro_id', $project_code)
            ->get();
        echo json_encode($item_group);
    }

    public function items_prefixcode_start(Request $request)
    {
        $project_code = $request->project_code;
        $category_code = $request->category_code;
        $items = ItemModel::where('item_projectid', $project_code)
            ->where('item_categoryid', $category_code)
            ->get();
        $items_count = empty(count($items)) ? '' : count($items);
        $item_bathroom = empty($items[0]->item_bathroom) ? '' : $items[0]->item_bathroom;
        $item_bedroom = empty($items[0]->item_bedroom) ? '' : $items[0]->item_bedroom;
        $item_cost = empty($items[0]->item_cost) ? '' : $items[0]->item_cost;
        // $item_des = empty($items[0]->item_des)? '' : $items[0]->item_des;
        $item_develop_by = empty($items[0]->item_develop_by) ? '' : $items[0]->item_develop_by;
        $item_floor = empty($items[0]->item_floor) ? '' : $items[0]->item_floor;
        $item_parking = empty($items[0]->item_parking) ? '' : $items[0]->item_parking;
        $item_price = empty($items[0]->item_price) ? '' : $items[0]->item_price;
        $item_width_land = empty($items[0]->item_width_land) ? '' : $items[0]->item_width_land;
        $item_length_land = empty($items[0]->item_length_land) ? '' : $items[0]->item_length_land;
        $item_size_land = empty($items[0]->item_size_land) ? '' : $items[0]->item_size_land;
        $item_width_house = empty($items[0]->item_width_house) ? '' : $items[0]->item_width_house;
        $item_length_house = empty($items[0]->item_length_house) ? '' : $items[0]->item_length_house;
        $item_size_house = empty($items[0]->item_size_house) ? '' : $items[0]->item_size_house;
        $item_sq_fp = empty($items[0]->item_sq_fp) ? '' : $items[0]->item_sq_fp;
        $item_title = empty($items[0]->item_title) ? '' : $items[0]->item_title;
        $item_bordering_north = empty($items[0]->item_bordering_north) ? '' : $items[0]->item_bordering_north;
        $item_bordering_south = empty($items[0]->item_bordering_south) ? '' : $items[0]->item_bordering_south;
        $item_bordering_west = empty($items[0]->item_bordering_west) ? '' : $items[0]->item_bordering_west;
        $item_bordering_east = empty($items[0]->item_bordering_east) ? '' : $items[0]->item_bordering_east;
        $item_completed_year = empty($items[0]->item_completed_year) ? '' : $items[0]->item_completed_year;
        $commission_amount = empty($items[0]->commission_amount) ? '' : $items[0]->commission_amount;
        $commission_percentage = empty($items[0]->commission_percentage) ? '' : $items[0]->commission_percentage;
        $condition = empty($items[0]->condition) ? '' : $items[0]->condition;

        $data = array(
            'item_bathroom' => $item_bathroom,
            'item_bedroom' => $item_bedroom,
            'item_cost' => $item_cost,
            // 'item_des' => $item_des ,
            'item_develop_by' => $item_develop_by,
            'item_floor' => $item_floor,
            'item_parking' => $item_parking,
            'item_price' => $item_price,
            'item_width_land' => $item_width_land,
            'item_length_land' => $item_length_land,
            'item_size_land' => $item_size_land,
            'item_width_house' => $item_width_house,
            'item_length_house' => $item_length_house,
            'item_size_house' => $item_size_house,
            'item_sq_fp' => $item_sq_fp,
            'item_title' => $item_title,
            'item_title' => $item_title,
            'item_completed_year' => $item_completed_year,
            'items_count' => $items_count,
            'item_bordering_north' => $item_bordering_north,
            'item_bordering_south' => $item_bordering_south,
            'item_bordering_west' => $item_bordering_west,
            'item_bordering_east' => $item_bordering_east,
            'commission_amount' => $commission_amount,
            'commission_percentage' => $commission_percentage,
            'condition' => $condition,
        );
        echo json_encode($data);
    }
    public function transfer_item()
    {
        $projects = ProjectModel::select(
            DB::raw('CONCAT(project_code," | ",project_name) AS project_mixed'),
            'id'
        )
            ->pluck('project_mixed', 'id')
            ->prepend('Please Select', '');
        $user = User::where('role', 'Agencies')->select(DB::raw('CONCAT(user_firstname," ",user_lastname) As full_name'), 'id')
            ->pluck('full_name', 'id')->prepend('Please Select', '');
        return view('administrator.items.transfer-item', compact('projects', 'user'));
    }
    public function transfer_item_store(Request $request)
    {
        $cart = Session::get('cart_transfer');
        if (!$cart) {
            return redirect()->back()->with('warning', 'No Item Selected, Please Select Any Items');
        } else {
            DB::table('nso007_transfer_history')->insert([
                'inv_to_id'     => $request->invent_id,
                'inv_from_id'   => 0,
                'date_transfer' => date('Y-m-d'),
                'user_transfer' => Auth::user()->id,
                'des'           => $request->des
            ]);

            $max_id = DB::table('nso007_transfer_history')->max('id');
            foreach ($cart as $j => $khart) {
                ItemModel::where('id', $khart['item_id'])->update([
                    'inv_id'    => $request->invent_id
                ]);
                DB::table('nso007_transfer_history_detail')
                    ->insert([
                        'transfer_id'   => $max_id,
                        'item_id'       => $khart['item_id']
                    ]);
            }
        }
        session()->forget('cart_transfer');
        \LogActivity::addToLog('Stock Transfered Successfully!');
        return redirect()->back()->with('success', 'Item transfer successfully');
    }
    public function get_item_by_project_id(Request $request)
    {
        $item = ItemModel::where('item_salestatus', 0)->where([['available', 1], ['block_status', 1]])->where('item_projectid', $request->item_projectid)->get();
        return json_encode($item);
    }
    public function create_transfer(Request $request, $item_name = null, $project_id = null)
    {
        $project_id = $request->project_id;
        $item_name  = $request->item_name;
        $inventory = DB::table('nso007_inventery_stock')->select(
            'inv_name',
            'id'
        )
            ->pluck('inv_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')
                ->prepend('Please Select', '');
            $data = ItemModel::where('item_salestatus', 0)
                ->where([['available', 1], ['block_status', 1]])
                ->when($project_id, function ($query) use ($project_id) {
                    $query->where('item_projectid', $project_id);
                })
                ->when($item_name, function ($query) use ($item_name) {
                    $query->where('item_house', 'LIKE', "%$item_name%");
                })
                ->whereNull('inv_id')
                ->select('nso007_item_stock.*')
                ->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')
                ->prepend('Please Select', '');
            $data = ItemModel::where('item_salestatus', 0)
                ->join('nso007_project_stock as project', 'project.id', 'nso007_item_stock.item_projectid')
                ->where([['available', 1], ['block_status', 1], ['project.branch_id', Auth::user()->branch_id]])
                ->when($project_id, function ($query) use ($project_id) {
                    $query->where('item_projectid', $project_id);
                })
                ->when($item_name, function ($query) use ($item_name) {
                    $query->where('item_house', 'LIKE', "%$item_name%");
                })
                ->whereNull('inv_id')
                ->select('nso007_item_stock.*')
                ->paginate(30);
        }

        if ($request->ajax()) {
            return view('administrator.pos.presult-transfer', ['data' => $data]);
        }
        return view('administrator.pos.transfer', ['data' => $data, 'item_name' => $item_name, 'project_id' => $project_id, 'inventory' => $inventory, 'projects' => $projects]);
    }
    public function get_cart()
    {
        $cart = session()->get('cart_transfer');
        echo \json_encode($cart);
    }
    public function remove_transfer_cart(Request $request)
    {
        if ($request->id) {

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

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

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

                session()->put('cart_transfer', $cart);
            }

            session()->flash('success', 'item removed successfully');
            return $cart;
        }
    }
    public function add_transfer_cart($id)
    {
        $item = ItemModel::find($id);
        $status = '';
        if (!$item) {
            $status = "Item not Found!";
        } else {
            $cart = session()->get('cart_transfer');
            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_transfer', $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_transfer', $cart);
                    $status = "success";
                }
            }
        }
        echo json_encode($status);
    }
    public function filter_transfer(Request $request)
    {
        $project    = $request->project_id;
        $item_name  = $request->item_name;
        $session    = Session::get('cart_transfer');
        $div        = "";

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

        $data = ItemModel::where('item_house', 'LIKE', "%$item_name%")
            ->when(request('project_id', ''), function ($query) use ($project) {
                $query->where('item_projectid', $project);
            })
            ->whereNull('inv_id')
            ->get();
        if (!empty($data)) {
            foreach ($data as $key => $item) {
                $status = 0;
                $btn_cart = '';
                if (!$session) {
                    $btn_cart = '<p class="btn-holder"><a href="#" data-id="' . $item->id . '" class="btn btn-default btn-block text-center btn-add-to-cart btn-add-to-cart-transfer" role="button">Add To Cart</a> </p>';
                } else {
                    foreach ($session as $ses) {
                        if ($ses['item_id'] == $item->id) {
                            $btn_cart = '<p class="btn-holder"><a href="#" data-id = "' . $item->id . '" class="btn btn-danger btn-block text-center btn-remove-from-cart-transfer" role="button">Added To Cart</a> </p>';
                            $status = 1;
                        }
                    }
                    if ($status != 1) {
                        $btn_cart = '<p class="btn-holder"><a href="#" data-id="' . $item->id . '" class="btn btn-default btn-block text-center btn-add-to-cart btn-add-to-cart-transfer" role="button">Add To Cart</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">
                                <center>
                                    <h4 class="text-danger"><b>' . $item->item_house . '</b></h4>
                                    <p class="text-blue"><b>' . $item->item_price . '$</b></p>
                                    ' . $btn_cart . '
                                </center>
                                </div>
                            </div>
                        </div>';
            }
            return $div;
        }
    }
    public function start_transfer()
    {
        $category   = CategoryModel::pluck('category_name', 'id');
        $project    = ProjectModel::where('status', 1)->pluck('project_name', 'id');
        $groupitem  = ItemGroupModel::pluck('item_group_name', 'id');
        $zones      = ItemZoneModel::pluck('item_zone_name', 'id');
        $inventory  = DB::table('nso007_inventery_stock')->pluck('inv_name', 'id')->prepend('Main Stock', '0');
        $invenF     = DB::table('nso007_inventery_stock')->pluck('inv_name', 'id');
        $items      = DB::table('nso007_item_stock')->join('nso007_project_stock', 'nso007_project_stock.id', 'nso007_item_stock.item_projectid')
            ->join('nso007_item_group', 'nso007_item_group.id', 'nso007_item_stock.item_groupid')
            ->join('nso007_item_zone', 'nso007_item_zone.id', 'nso007_item_stock.item_zone_id')
            ->join('nso007_category_stock', 'nso007_category_stock.id', 'nso007_item_stock.item_categoryid')
            ->select(
                'nso007_item_stock.*',
                'nso007_project_stock.project_name as project',
                'nso007_category_stock.category_name as category',
                'nso007_item_group.item_group_name as group',
                'nso007_item_zone.item_zone_name as zone'
            )
            ->where([['nso007_item_stock.inv_id', null], ['nso007_item_stock.available', 1], ['nso007_item_stock.block_status', 1]])->get();
        return view('administrator.inventory.transfer.index', compact('project', 'category', 'groupitem', 'inventory', 'items', 'zones', 'invenF'));
    }
    public function affect_item(Request $request)
    {
        $cat    = $request->cat;
        $pro    = $request->pro;
        $itmg   = $request->itmg;
        $items  = DB::table('nso007_item_stock')
            ->join('nso007_project_stock', 'nso007_project_stock.id', 'nso007_item_stock.item_projectid')
            ->join('nso007_item_group', 'nso007_item_group.id', 'nso007_item_stock.item_groupid')
            ->join('nso007_item_zone', 'nso007_item_zone.id', 'nso007_item_stock.item_zone_id')
            ->join('nso007_category_stock', 'nso007_category_stock.id', 'nso007_item_stock.item_categoryid')
            ->select(
                'nso007_item_stock.*',
                'nso007_project_stock.project_name as project',
                'nso007_category_stock.category_name as category',
                'nso007_item_group.item_group_name as group',
                'nso007_item_zone.item_zone_name as zone'
            )
            ->where([['inv_id', null], ['available', 1], ['block_status', 1]])
            ->when($cat, function ($q) use ($cat) {
                $q->where('item_categoryid', $cat);
            })
            ->when($pro, function ($q) use ($pro) {
                $q->where('item_projectid', $pro);
            })
            ->when($itmg, function ($q) use ($itmg) {
                $q->where('item_groupid', $itmg);
            })->get();
        echo json_encode($items);
    }
    public function tranfer(Request $request)
    {
        $this->validate($request, [
            'itemIDs'   => 'required',
            'invenID'   => 'required'
        ]);
        $totalItem = count(explode(',', $request->itemIDs));
        $inventory = InventoryModel::find($request->invenID);
        ItemModel::whereIn('id', explode(',', $request->itemIDs))->update([
            'inv_id' => $request->invenID
        ]);
        return redirect(route('transfer-inventory-stock'))->with('success', $totalItem . ' Items Successfully Transfered to Inventory ' . $inventory->inv_name);
    }
    public function store_transfer(Request $request)
    {
        $cat    = $request->cat;
        $pro    = $request->pro;
        $itmg   = $request->itmg;
        $item   = $request->item;
        $inv    = $request->inv;
        $items  = ItemModel::where([['inv_id', null], ['available', 1], ['block_status', 1]])
            ->when($cat, function ($q) use ($cat) {
                $q->where('item_categoryid', $cat);
            })
            ->when($pro, function ($q) use ($pro) {
                $q->where('item_projectid', $pro);
            })
            ->when($itmg, function ($q) use ($itmg) {
                $q->where('item_groupid', $itmg);
            })
            ->when($item, function ($q) use ($item) {
                $q->whereIn('id', $item);
            })->update([
                'inv_id'    => $inv
            ]);
        session()->flash('success', 'Items Successfully Transfered');
        echo json_encode($items);
    }
    public function filter_by_inventory($id)
    {
        $items  = DB::table('nso007_item_stock')
            ->join('nso007_project_stock', 'nso007_project_stock.id', 'nso007_item_stock.item_projectid')
            ->join('nso007_item_group', 'nso007_item_group.id', 'nso007_item_stock.item_groupid')
            ->join('nso007_item_zone', 'nso007_item_zone.id', 'nso007_item_stock.item_zone_id')
            ->join('nso007_category_stock', 'nso007_category_stock.id', 'nso007_item_stock.item_categoryid')
            ->select(
                'nso007_item_stock.*',
                'nso007_project_stock.project_name as project',
                'nso007_category_stock.category_name as category',
                'nso007_item_group.item_group_name as group',
                'nso007_item_zone.item_zone_name as zone'
            )->where('nso007_item_stock.inv_id', $id)->get();
        if ($id == 0) {
            $items = DB::table('nso007_item_stock')
                ->join('nso007_project_stock', 'nso007_project_stock.id', 'nso007_item_stock.item_projectid')
                ->join('nso007_item_group', 'nso007_item_group.id', 'nso007_item_stock.item_groupid')
                ->join('nso007_item_zone', 'nso007_item_zone.id', 'nso007_item_stock.item_zone_id')
                ->join('nso007_category_stock', 'nso007_category_stock.id', 'nso007_item_stock.item_categoryid')
                ->select(
                    'nso007_item_stock.*',
                    'nso007_project_stock.project_name as project',
                    'nso007_category_stock.category_name as category',
                    'nso007_item_group.item_group_name as group',
                    'nso007_item_zone.item_zone_name as zone'
                )->whereNull('nso007_item_stock.inv_id')->get();
        }
        echo json_encode($items);
    }
    //////////////////block Filter and Transfer///////////////////
    public function filterByCategoryOrProject(Request $request)
    {
        $cat    = $request->cat;
        $group  = $request->itmg;
        $zone   = $request->itmz;
        $pro    = $request->pro;
        $ivf    = $request->ivf;
        $items  = DB::table('nso007_item_stock')
            ->join('nso007_project_stock', 'nso007_project_stock.id', 'nso007_item_stock.item_projectid')
            ->join('nso007_item_group', 'nso007_item_group.id', 'nso007_item_stock.item_groupid')
            ->join('nso007_item_zone', 'nso007_item_zone.id', 'nso007_item_stock.item_zone_id')
            ->join('nso007_category_stock', 'nso007_category_stock.id', 'nso007_item_stock.item_categoryid')
            ->select(
                'nso007_item_stock.*',
                'nso007_project_stock.project_name as project',
                'nso007_category_stock.category_name as category',
                'nso007_item_group.item_group_name as group',
                'nso007_item_zone.item_zone_name as zone'
            )
            ->where([['nso007_item_stock.available', 1], ['nso007_item_stock.block_status', 1]])
            ->when($request->cat, function ($que) use ($cat) {
                $que->where('nso007_category_stock.id', $cat);
            })
            ->when($request->pro, function ($q) use ($pro) {
                $q->where('nso007_project_stock.id', $pro);
            })
            ->when($request->itmg, function ($qr) use ($group) {
                $qr->where('nso007_item_group.id', $group);
            })
            ->when($request->itmz, function ($query) use ($zone) {
                $query->where('nso007_item_zone.id', $zone);
            })
            ->where(function ($qury) use ($ivf) {
                if (!empty($ivf)) {
                    $qury->where('nso007_item_stock.inv_id', $ivf);
                } else {
                    $qury->whereNull('nso007_item_stock.inv_id');
                }
            })
            ->get();
        $groups     = ItemGroupModel::select('item_group_name as name', 'id')
            ->when($request->cat, function ($qr, $cat) {
                $qr->where('item_group_cat_id', $cat);
            })
            ->when($request->pro, function ($q) use ($pro) {
                $q->where('item_group_pro_id', $pro);
            })
            ->get();
        $zones      = ItemZoneModel::select('item_zone_name as name', 'id')
            ->when($request->cat, function ($qr, $cat) {
                $qr->where('item_zone_cat_id', $cat);
            })
            ->when($request->pro, function ($q) use ($pro) {
                $q->where('item_zone_pro_id', $pro);
            })->get();
        echo json_encode(array(
            'items'     => $items,
            'groups'    => $groups,
            'zones'     => $zones
        ));
    }
    public function filterByGrouporZone(Request $request)
    {
        $p_id   = $request->pro_id;
        $g_id   = $request->group_id;
        $z_id   = $request->zone_id;
        $cat_id = $request->cat_id;
        $ivf    = $request->ivf;
        $items  = DB::table('nso007_item_stock')
            ->join('nso007_project_stock', 'nso007_project_stock.id', 'nso007_item_stock.item_projectid')
            ->join('nso007_item_group', 'nso007_item_group.id', 'nso007_item_stock.item_groupid')
            ->join('nso007_item_zone', 'nso007_item_zone.id', 'nso007_item_stock.item_zone_id')
            ->join('nso007_category_stock', 'nso007_category_stock.id', 'nso007_item_stock.item_categoryid')
            ->select(
                'nso007_item_stock.*',
                'nso007_project_stock.project_name as project',
                'nso007_category_stock.category_name as category',
                'nso007_item_group.item_group_name as group',
                'nso007_item_zone.item_zone_name as zone'
            )
            ->where([['nso007_item_stock.available', 1], ['nso007_item_stock.block_status', 1]])
            ->when($request->pro_id, function ($qq) use ($p_id) {
                $qq->where('nso007_item_stock.item_projectid', $p_id);
            })
            ->when($request->cat_id, function ($qqq) use ($cat_id) {
                $qqq->where('nso007_item_stock.item_categoryid', $cat_id);
            })
            ->when($request->group_id, function ($qr) use ($g_id) {
                $qr->where('nso007_item_group.id', $g_id);
            })
            ->when($request->zone_id, function ($query) use ($z_id) {
                $query->where('nso007_item_zone.id', $z_id);
            })
            ->where(function ($qury) use ($ivf) {
                if (!empty($ivf)) {
                    $qury->where('nso007_item_stock.inv_id', $ivf);
                } else {
                    $qury->whereNull('nso007_item_stock.inv_id');
                }
            })
            ->get();
        echo json_encode($items);
    }
    public function search_arrayitem($id)
    {
        $ids    = explode(',', $id);
        $items  = DB::table('nso007_item_stock')
            ->join('nso007_project_stock', 'nso007_project_stock.id', 'nso007_item_stock.item_projectid')
            ->join('nso007_item_group', 'nso007_item_group.id', 'nso007_item_stock.item_groupid')
            ->join('nso007_item_zone', 'nso007_item_zone.id', 'nso007_item_stock.item_zone_id')
            ->join('nso007_category_stock', 'nso007_category_stock.id', 'nso007_item_stock.item_categoryid')
            ->select(
                'nso007_item_stock.*',
                'nso007_project_stock.project_name as project',
                'nso007_category_stock.category_name as category',
                'nso007_item_group.item_group_name as group',
                'nso007_item_zone.item_zone_name as zone'
            )
            ->whereIn('nso007_item_stock.id', $ids)
            ->get();
        echo json_encode($items);
    }

    public function items_delete(Request $request)
    {
        $delete_item = ItemModel::findOrFail($request->delete_id);
        $delete_item->delete();
        return response()->json(['success' => true, 'message' => 'Delete item successfully']);
    }
    public function itemproperty(Request $request)
    {
        $project_id = $request->project_id;
        $category_id = $request->category_id;
        $zone = ItemZoneModel::select('item_zone_name as name', 'id')
            ->when($project_id, function ($q, $project_id) {
                $q->where('item_zone_pro_id', $project_id);
            })
            ->when($category_id, function ($q, $category_id) {
                $q->where('item_zone_cat_id', $category_id);
            })->get();
        $group = ItemGroupModel::select('item_group_name as name', 'id')
            ->when($project_id, function ($q, $project_id) {
                $q->where('item_group_pro_id', $project_id);
            })
            ->when($category_id, function ($q, $category_id) {
                $q->where('item_group_cat_id', $category_id);
            })
            ->get();
        return response()->json(['success' => true, 'data' => ['zone' => $zone, 'group' => $group]]);
    }
    public function create_project(Request $request){

        $project = new ProjectModel;
        $project->branch_id     = $request->branch_id;
        $project->project_code  = $request->project_code;
        $project->project_name  = $request->project_name;
        $project->project_des   = $request->description;
        $project->save();

        return $project;

    }
    public function create_category(Request $request){
        
        $category = new CategoryModel;
        $category->category_code = $request->category_code;
        $category->category_name = $request->category_name;
        $category->category_des = $request->description;
        $category->save();
        
        return $category;
    }
    public function create_sub_category(Request $request){

        $category = new SubCategoryModel;
        $category->sub_category_code = $request->sub_category_code;
        $category->sub_category_name = $request->sub_category_name;
        $category->sub_category_amount = $request->sub_category_amount;
        $category->save();

        return $category;
    }
    public function create_item_group(Request $request){

        $item_group = new ItemGroupModel;
        $item_group->item_group_code = $request->item_group_code;
        $item_group->item_group_name = $request->item_group_name;
        $item_group->save();

        return $item_group;

    }
    public function create_item_zone(Request $request){

        $item_zone = new ItemZoneModel;
        $item_zone->item_zone_code = $request->item_zone_code;
        $item_zone->item_zone_name = $request->item_zone_name;
        $item_zone->save();

        return $item_zone;
    }
}
