<?php

namespace App\Http\Controllers\Administrator;

use App\AgencyGroupModel;
use App\CategoryModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\InventoryModel;
use App\ItemGroupModel;
use App\ItemModel;
use App\ItemZoneModel;
use App\ProjectModel;
use DataTables;
use DB;
use Auth;
use PDO;
use Gate;
use Session;
use App\User;
use App\UserGroupModel;
use Illuminate\Support\Facades\Crypt;
use Yajra\DataTables\DataTables as DataTablesDataTables;

class InventoryStockController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct()
    {
        $this->middleware('permission:Inventory-List', ['only' => ['index']]);
        $this->middleware('permission:Inventory-Create', ['only' => ['create', 'store']]);
        $this->middleware('permission:Inventory-Edit', ['only' => ['edit_inv', 'update_inventory']]);
        $this->middleware('permission:Transfer-Inventory-Stock-list', ['only' => ['list']]);
        $this->middleware('permission:Inventory-Stock-Edit', ['only' => ['edit', 'update']]);
        $this->middleware('permission:Inventory-Delete', ['only' => ['destroy_inventory']]);
        $this->middleware('permission:Inventory-Assign-List', ['only' => ['assign_stock', 'inven_assign_list']]);
        $this->middleware('permission:Inventory-Assign-Edit', ['only' => ['edit_assign', 'update_assign']]);
        $this->middleware('permission:Assign-Inventory', ['only' => ['create_assign_stock', 'assign_store']]);
    }
    public function index()
    {
        return view("administrator.inventory.inventory-stock.index");
    }
    public function get_data()
    {
        $inventory_data = DB::table("nso007_inventery_stock")->select("*")->take(20);
        return Datatables::of($inventory_data)
            ->addIndexColumn()
            ->addColumn("action", function ($inventory_data) {
                $items = ItemModel::where('inv_id', $inventory_data->id)->get();
                $AvailableDelete = true;
                foreach ($items as $key => $item) {
                    if ($item->available == 0) $AvailableDelete = false;
                }
                $btn_view = '';
                $btn_edit = '';
                $btn_edit_item = '';
                if (count($items) > 0) {
                    if (Gate::check('Inventory-View')) $btn_view = '<a style="margin-right:5px;" href="' . route('inventory-stock.show', Crypt::encrypt($inventory_data->id)) . '" class="btn btn-sm btn-info btn-view-inv"><i class="fa fa-eye"></i></a>';
                    if (Gate::check('Inventory-Stock-Edit')) $btn_edit_item = '<a href="' . route('inventory_stock.edit', $inventory_data->id) . '" style="margin-left:5px;" class="btn btn-warning btn-sm"><i class="fa fa-exchange"></i></a>';
                }
                $btn_delete = "";
                if ($inventory_data->inv_status == 1) {
                    if (Gate::check('Inventory-Delete')) $btn_delete = " <a href='#delete-inventory' style='margin-left:5px;' onclick='delete_performance(this)' class='btn btn-sm btn-danger' id=" . $inventory_data->id . " data-toggle='modal'><i class='fa fa-trash-o'></i></a>";
                }
                if (Gate::check('Inventory-Edit')) {
                    $btn_edit = "<a href='#edit-inventory' onclick='edit_performance(this)' class='btn btn-sm btn-primary' id=" . $inventory_data->id . " data-toggle='modal'><i class='fa fa-edit'></i></a> ";
                }
                if ($AvailableDelete == false) {
                    $btn_delete = '';
                }
                $btn_edit_item = '';
                return $btn_view . $btn_edit . $btn_edit_item . $btn_delete;
            })
            ->editColumn('inv_date', function ($data) {
                return date('d-m-Y', strtotime($data->inv_date));
            })
            ->rawColumns(['action'])
            ->make(true);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view("administrator.inventory.inventory-stock.create");
    }
    public function list(Request $request)
    {
        if ($request->ajax()) {
            $list = DB::table("nso007_inventery_stock")->select("*")->take(20);
            return Datatables::of($list)
                ->addIndexColumn()
                ->addColumn("action", function ($inventory_data) {
                    $items = ItemModel::where('inv_id', $inventory_data->id)->get();
                    $AvailableDelete = true;
                    foreach ($items as $key => $item) {
                        if ($item->available == 0) $AvailableDelete = false;
                    }
                    $btn_edit_item = '';
                    if (count($items) > 0) {
                        if (Gate::check('Inventory-Stock-Edit')) {
                            $btn_edit_item = '<a href="' . route('inventory_stock.edit', $inventory_data->id) . '" style="margin-left:5px;" class="btn btn-warning btn-sm" title="Edit Stock"><i class="fa fa-exchange"></i></a>';
                        }
                    }

                    return $btn_edit_item;
                })
                ->editColumn('inv_date', function ($data) {
                    return date('d-m-Y', strtotime($data->inv_date));
                })
                ->rawColumns(['action'])
                ->make(true);
        }
        return view('administrator.inventory.transfer.list');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'date' => 'required',
            'name' => 'required'
        ]);
        DB::table("nso007_inventery_stock")->insert(['inv_date' => date("Y-m-d", strtotime($request['date'])), 'inv_name' => $request['name'], 'inv_description' => $request['des'], 'inv_status' => 1, 'create_by' => Auth::user()->id]);
        \LogActivity::addToLog('Inventory is Created');
        return \back()->with("success", "Creating is successfull");
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request, $id)
    {
        $project        = ProjectModel::pluck('project_name', 'id')->prepend('Select Project', '');
        $category       = CategoryModel::pluck('category_name', 'id')->prepend('Select Category', '');
        $group          = ItemGroupModel::pluck('item_group_name', 'id')->prepend('Select Group', '');
        $zone           = ItemZoneModel::pluck('item_zone_name', 'id')->prepend('Select Zone', '');
        $project_id     = $request->project_id;
        $category_id    = $request->category_id;
        $zone_id        = $request->zone_id;
        $group_id       = $request->group_id;
        if ($request->ajax()) {
            $inventory = DB::table('nso007_inventery_stock as inventory')
                ->join('nso007_item_stock as stock', 'stock.inv_id', 'inventory.id')
                ->join('nso007_category_stock as category', 'category.id', 'stock.item_categoryid')
                ->join('nso007_project_stock as project', 'project.id', 'stock.item_projectid')
                ->join('nso007_item_zone as zone', 'zone.id', 'stock.item_zone_id')
                ->join('nso007_item_group as group', 'group.id', 'stock.item_groupid')
                ->select(
                    'project.project_name',
                    'category.category_name',
                    'zone.item_zone_name as zone_name',
                    'group.item_group_name as group_name',
                    'stock.item_house as item_name',
                    'stock.available',
                    'stock.item_size_land as size',
                    'stock.item_price'
                )
                ->where('stock.inv_id', Crypt::decrypt($id))
                ->when($project_id, function ($query, $project_id) {
                    $query->where('item_projectid', $project_id);
                })
                ->when($category_id, function ($query, $category_id) {
                    $query->where('item_categoryid', $category_id);
                })
                ->when($group_id, function ($query, $group_id) {
                    $query->where('item_groupid', $group_id);
                })
                ->when($zone_id, function ($query, $zone_id) {
                    $query->where('item_zone_id', $zone_id);
                })
                ->get();
            if ($request->isMethod('get')) {
                return DataTablesDataTables::of($inventory)
                    ->addIndexColumn()
                    ->addColumn('status', function ($inv) {
                        if ($inv->available == 1) {
                            return '<span class="text-info text-bold">Available for Sale</span>';
                        } else {
                            if ($inv->item_salestatus == 1) {
                                return '<span class="text-danger text-bold">Booking</span>';
                            } else {
                                return '<span class="text-danger text-bold">Contracted</span>';
                            }
                        }
                    })
                    ->rawColumns(['status' => 'status'])
                    ->make(true);
            } else {
                return $inventory;
            }
        }
        return view("administrator.inventory.inventory-stock.show", compact('id', 'zone', 'group', 'category', 'project'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, $id)
    {
        Session::put('inv_id', $id);
        $inv = InventoryModel::all();
        return view('administrator.inventory.transfer.edit', compact('inv'));
    }
    public function get_edit()
    {
        $id = Session::get('inv_id');
        // $item = ItemModel::where('inv_id',$id)->get();
        $item = DB::table('nso007_item_stock as stock')
            ->join('nso007_project_stock as project', 'project.id', 'stock.item_projectid')
            ->join('nso007_category_stock as cat', 'cat.id', 'stock.item_categoryid')
            ->join('nso007_item_group as group', 'group.id', 'stock.item_groupid')
            ->select('stock.*', 'project.project_name', 'cat.category_name', 'group.item_group_name as group_name')
            ->where('inv_id', $id)->get();
        return Datatables::of($item)
            ->addIndexColumn()
            ->addColumn('check_box', function ($item) {
                $check_box = '';
                if ($item->available == 1 && $item->block_status == 1) {
                    $check_box = '<label class="checkbox-list">
                <input type="checkbox" class="checkbox" data-id="' . $item->id . '" data-name="' . $item->item_house . '">
                <span class="checkmark"></span></label>';
                }
                return $check_box;
            })
            ->rawColumns(['check_box' => 'check_box'])
            ->make(true);
    }
    public function update_store(Request $request)
    {
        $from_inv_id = $request->from_inv_id;
        $inv_id = $request->inv_id;
        $item_ids = $request->item_ids;
        DB::table('nso007_transfer_history')
            ->insert([
                'inv_to_id'     =>  $inv_id,
                'inv_from_id'   => $from_inv_id,
                'date_transfer' => date('Y-m-d'),
                'user_transfer' => Auth::user()->id
            ]);
        $max = DB::table('nso007_transfer_history')->max('id');
        foreach (explode(',', $item_ids) as $key => $id) {
            ItemModel::where('id', $id)->update([
                'inv_id' => $inv_id
            ]);
            DB::table('nso007_transfer_history_detail')
                ->insert([
                    'transfer_id'   => $max,
                    'item_id'       => $id
                ]);
        }
        return redirect()->route('inventory_stock.index')->with('success', 'Items Successfully Transfered');
    }
    public function inventory_cart_adding($id)
    {
        $item = ItemModel::find($id);
        $status = '';
        if (!$item) {
            $status = "Item not Found!";
        } else {
            $cart = session()->get('transfer_edit');
            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('transfer_edit', $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('transfer_edit', $cart);
                    $status = "success";
                }
            }
        }
        echo json_encode($status);
    }
    public function inventory_cart_removal(Request $request)
    {
        if ($request->id) {

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

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

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

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

            session()->flash('success', 'item removed successfully');
            return $cart;
        }
    }
    public function edit_inv($id)
    {
        $data_inventory = DB::table("nso007_inventery_stock")->where("id", $id)->first();
        return json_encode($data_inventory);
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $removal_items = Session::get('transfer_edit');
        foreach ($removal_items as $item) {
            ItemModel::where('id', $item['item_id'])->update([
                'inv_id' => null
            ]);
        }
        session()->forget('transfer_edit');
        return redirect()->route('inventory_stock.edit', $id)->with('Success', 'Items Remove From Inventory Successfully');
    }
    public function update_inventory(Request $request)
    {
        $id = $request['id'];
        $date = date("Y-m-d", strtotime($request['date']));
        $name = $request['name'];
        $des = $request['des'];

        $result = DB::table("nso007_inventery_stock")->where("id", $id)->update(["inv_date" => $date, "inv_name" => $name, "inv_description" => $des]);
        if ($result != 1)  return \back()->with("warning", "updating is not successfull");

        \LogActivity::addToLog('Inventory is updated');
        return \back()->with("success", "updating is successfull");
    }
    public function assign_stock()
    {
        return view('administrator.inventory.assign.index');
    }
    public function create_assign_stock()
    {
        $invs = DB::table('nso007_inventery_stock')->where([['inv_status', 1],['agent_id',null]])
            ->pluck('inv_name', 'id')->prepend('Please Select', '');
        $invens = InventoryModel::whereNotnull('agent_id')->get();
        $invAgentIDs = [];
        if (!empty($invens)) {
            foreach ($invens as $key => $v) {
                $agentIDs = $v->agent_id;
                $agentIDs = explode(',', $agentIDs);
                if (empty($invAgentIDs)) {
                    $invAgentIDs = $agentIDs;
                } else {
                    foreach ($agentIDs as $i) {
                        $search = array_search($i, $invAgentIDs);
                        if ($search == false) {
                            array_push($invAgentIDs, $i);
                        }
                    }
                }
            }
        }
        $teams = DB::table('nso007_agency_team')->pluck('agency_team_name', 'id')->prepend('Please Select', '');
        $agencies = DB::table('users')
            ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
            ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
            ->leftjoin('nso007_agency_team', 'users.agency_team_id', 'nso007_agency_team.id')
            ->select(
                'nso007_agency_type.agency_type_name as group_type',
                'users.id',
                'users.group_id',
                'nso007_agency_group.agency_group_name AS group',
                'nso007_agency_team.agency_team_name',
                DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
            )
            ->where([['users.id', '!=', 1], ['users.role', 'Agencies']])
            ->whereNotIn('users.id', $invAgentIDs)->get();
        // dd($agencies);
        return view('administrator.inventory.assign.create', compact('invs', 'agencies', 'teams'));
    }
    public function edit_assign($id)
    {
        $teams      = DB::table('nso007_agency_team')->pluck('agency_team_name', 'id')->prepend('Please Select', '');
        $id         = Crypt::decrypt($id);
        $inv        = DB::table('nso007_inventery_stock')
            ->select(
                'id',
                DB::Raw('IFNULL( `nso007_inventery_stock`.`group_id` , `nso007_inventery_stock`.`agent_id`) AS agen_ids'),
                'group_id as g_id',
                'agent_id as ag_id'
            )
            ->where('id', $id)->first();
        $invs = InventoryModel::where('id', $id)->pluck('inv_name', 'id');
        $agentIDs   = explode(',', $inv->ag_id);
        $agencies = DB::table('users')
            ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
            ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
            ->leftjoin('nso007_agency_team as team', 'team.id', 'users.agency_team_id')
            ->select(
                'nso007_agency_type.agency_type_name as group_type',
                'users.id',
                'team.agency_team_name as team_name',
                'users.group_id',
                'nso007_agency_group.agency_group_name AS group',
                DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
            )
            ->where([['users.id', '!=', 1], ['users.role', 'Agencies']])
            ->get();
        // return view('administrator.inventory.assign.edit', compact('inv', 'agens', 'type', 'invs', 'groups', 'networks', 'agencies', 'teams'));
        return view('administrator.inventory.assign.edit', compact('inv', 'invs', 'agencies', 'teams'));
    }
    public function filter_agency_edit($iv, $id = null)
    {

        $inv        = InventoryModel::find($iv);
        $agentIDs   = explode(',', $inv->agent_id);
        if ($id == null) {
            $agencies = DB::table('users')
                ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
                ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
                ->leftjoin('nso007_agency_team as team', 'team.id', 'users.agency_team_id')
                ->select(
                    'nso007_agency_type.agency_type_name as group_type',
                    'users.id',
                    'users.group_id',
                    'team.agency_team_name as team_name',
                    'nso007_agency_group.agency_group_name AS group',
                    DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                    DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
                )
                ->where([['users.id', '!=', 1], ['users.role', 'Agencies']])
                ->where(function ($q) use ($agentIDs) {
                    $q->orwhereIn('users.id', $agentIDs);
                    $q->orwhere('users.group_id', '!=', null);
                })
                ->get();
        } else {
            $agencies = DB::table('users')
                ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
                ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
                ->leftjoin('nso007_agency_team as team', 'team.id', 'users.agency_team_id')
                ->select(
                    'nso007_agency_type.agency_type_name as group_type',
                    'users.id',
                    'users.group_id',
                    'team.agency_team_name as team_name',
                    'nso007_agency_group.agency_group_name AS group',
                    DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                    DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
                )
                ->where([['users.id', '!=', 1], ['users.role', 'Agencies']])
                ->where(function ($q) use ($agentIDs, $id) {
                    $q->orwhereIn('users.id', $agentIDs);
                    $q->orwhere('users.group_id', $id);
                })
                ->get();
        }

        echo json_encode($agencies);
    }
    public function filter_edit_assign($iv, $id)
    {
    }
    public function filter_agency_to_edit($inv, $id = null)
    {
        $inven          = InventoryModel::find($inv);
        $invenAgentIDs  = explode(',', $inven->agent_id);
        $groups         = null;
        if ($id == 1) { //network
            $agencies = DB::table('users')
                ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
                ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
                ->leftjoin('nso007_agency_team as team', 'team.id', 'users.agency_team_id')
                ->select(
                    'nso007_agency_type.agency_type_name as group_type',
                    'users.id',
                    'users.group_id',
                    'team.agency_team_name as team_name',
                    'nso007_agency_group.agency_group_name AS group',
                    DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                    DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
                )
                ->where([['users.id', '!=', 1], ['users.role', 'Agencies']])
                ->where(function ($q) use ($invenAgentIDs) {
                    $q->orwhereIn('users.id', $invenAgentIDs);
                    $q->orwhereNull('users.group_id');
                })
                ->get();
        } else if ($id == 2) { //group
            $agencies = DB::table('users')
                ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
                ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
                ->leftjoin('nso007_agency_team as team', 'team.id', 'users.agency_team_id')
                ->select(
                    'nso007_agency_type.agency_type_name as group_type',
                    'users.id',
                    'users.group_id',
                    'team.agency_team_name as team_name',
                    'nso007_agency_group.agency_group_name AS group',
                    DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                    DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
                )
                ->where([['users.id', '!=', 1], ['users.role', 'Agencies']])
                ->where(function ($q) use ($invenAgentIDs) {
                    $q->orwhereIn('users.id', $invenAgentIDs);
                    $q->orwhereNotNull('users.group_id');
                })
                ->get();
            $groups     = DB::table('nso007_agency_group')->get();
        } else {
            $agencies = DB::table('users')
                ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
                ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
                ->leftjoin('nso007_agency_team as team', 'team.id', 'users.agency_team_id')
                ->select(
                    'nso007_agency_type.agency_type_name as group_type',
                    'users.id',
                    'users.group_id',
                    'team.agency_team_name as team_name',
                    'nso007_agency_group.agency_group_name AS group',
                    DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                    DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
                )
                ->where([['users.id', '!=', 1], ['users.role', 'Agencies']])
                ->get();
        }
        echo json_encode(array(
            'agency'        => $agencies,
            'group'         => $groups
        ));
    }
    public function inven_assign_list()
    {
        $invs = DB::table('nso007_inventery_stock')->select('nso007_inventery_stock.*')->whereNotNull('group_id')->orwhereNotNull('agent_id')->get();
        return Datatables::of($invs)
            ->addIndexColumn()
            ->editColumn('inven', function ($invs) {
                return $invs->inv_name;
            })
            ->setRowId('id')
            ->editColumn('agency', function ($invs) {
                $agency = $invs->agent_id;
                $agencys = explode(',', $agency);
                if ($agencys == []) {
                    return 0;
                }
                return count($agencys);
            })
            ->editColumn('item', function ($invs) {
                $items      = ItemModel::where('inv_id', $invs->id)->count();
                return $items;
            })
            ->addColumn('details_url', function ($invs) {
                return route('table-detail-inventory', $invs->id);
            })
            ->addColumn('action', function ($invs) {
                $btn_edit = '';
                if (!empty($invs->id)) {
                    if (Gate::check('Inventory-Assign-Edit'))
                        $btn_edit = '<a href="' . route('assign-inven-to-agency.edit', Crypt::encrypt($invs->id)) . '" class="btn btn-sm btn-info"><i class="fa fa-edit"></i></a>';
                }
                return $btn_edit;
            })
            ->rawColumns(['action' => 'action'])
            ->make(true);
    }
    public function detail_url($id)
    {
        $inven = DB::table('nso007_inventery_stock')
            ->where('id', $id)->get();
        return Datatables::of($inven)
            ->addIndexColumn()
            ->editColumn('item', function ($inven) {
                $items      = ItemModel::where('inv_id', $inven->id)->select(DB::raw('GROUP_CONCAT(item_house) as item'))->first();
                $item_name  = $items->item;
                $item_name  = explode(',', $item_name);
                $class_item = '';
                if ($item_name[0] != '') {
                    foreach ($item_name as $key => $item) {
                        $class_item .= '<span class="item-circle">' . $item . '</span>​​​​ ​' . " ​​​";
                    }
                }
                return '<div><div class="control-item">' . $class_item . ' ​​​​​</div></div>';
            })
            ->editColumn('agency', function ($inven) {
                $ul = '<ul class="ul-angency">';
                $names = [];
                $agen_ids = $inven->agent_id;
                if ($agen_ids != null) {
                    $agen_ids = explode(',', $agen_ids);
                    $agencies = User::whereIn('id', $agen_ids)->get();
                    foreach ($agencies as $key => $agn) {
                        $name = ($agn->user_firstname . " " . $agn->user_lastname);
                        array_push($names, $name);
                    }
                    foreach ($names as $key => $name) {
                        $ul .= '<li>' . $name . '</li>';
                    }
                }
                return $ul . "</ul>";
            })
            ->rawColumns(['agency' => 'agency', 'item' => 'item'])
            ->make(true);
    }
    public function filter_agency($inv_id, $id = null)
    {
        $inventory = DB::table('nso007_inventery_stock')->where('id', $inv_id)->first();
        $groups    = null;
        $agent_ids = $inventory->agent_id;
        $agent_ids = explode(',', $agent_ids);

        if ($id == 1) { //network

            $agents = DB::table('users')
                ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
                ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
                ->leftjoin('nso007_agency_team as team', 'team.id', 'users.agency_team_id')
                ->select(
                    'nso007_agency_type.agency_type_name as group_type',
                    'users.id',
                    'team.agency_team_name as team_name',
                    'users.group_id',
                    'nso007_agency_group.agency_group_name AS group',
                    DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                    DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
                )
                ->where([['users.id', '!=', 1], ['users.group_id', null], ['users.role', 'Agencies']])
                ->whereNotIn('users.id', $agent_ids)->get();
        } else if ($id == 2) { //group
            $groups     = DB::table('nso007_agency_group')->get();
            $agents     = DB::table('users')
                ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
                ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
                ->leftjoin('nso007_agency_team as team', 'team.id', 'users.agency_team_id')
                ->select(
                    'nso007_agency_type.agency_type_name as group_type',
                    'users.id',
                    'team.agency_team_name as team_name',
                    'users.group_id',
                    'nso007_agency_group.agency_group_name AS group',
                    DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                    DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
                )
                ->where([['users.id', '!=', 1], ['users.group_id', '!=', null], ['users.role', 'Agencies']])
                ->whereNotIn('users.id', $agent_ids)->get();
        } else {
            $agents     = DB::table('users')
                ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
                ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
                ->leftjoin('nso007_agency_team as team', 'team.id', 'users.agency_team_id')
                ->select(
                    'nso007_agency_type.agency_type_name as group_type',
                    'users.id',
                    'users.group_id',
                    'team.agency_team_name as team_name',
                    'nso007_agency_group.agency_group_name AS group',
                    DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                    DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
                )
                ->where([['users.id', '!=', 1], ['users.role', 'Agencies']])
                ->whereNotIn('users.id', $agent_ids)->get();
        }
        $data = array(
            'group'     => $groups,
            'agency'    => $agents
        );
        // dd($data);
        echo json_encode($data);
    }
    public function filter_agencyGroup($inv, $id = null)
    {
        $inven      = InventoryModel::find($inv);
        $invAgenIDs = explode(',', $inven->agent_id);
        $agents     = DB::table('users')
            ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
            ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
            ->leftjoin('nso007_agency_team as team', 'team.id', 'users.agency_team_id')
            ->select(
                'nso007_agency_type.agency_type_name as group_type',
                'users.id',
                'team.agency_team_name as team_name',
                'nso007_agency_group.agency_group_name AS group',
                DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
            )
            ->where([['users.id', '!=', 1], ['users.role', 'Agencies']])
            ->when($id, function ($q, $id) {
                $q->where('users.group_id', $id);
            })
            ->whereNotIn('users.id', $invAgenIDs)->get();
        // $agencies   = User::where('group_id',$id)->whereNotIn('id',$invAgenIDs)->get();
        echo json_encode($agents);
    }
    public function update_assign(Request $request, $id)
    {
        $this->validate($request, [
            'agentIDs'  => 'required'
        ]);
        InventoryModel::where('id', $id)->update([
            'agent_id'  => $request->agentIDs
        ]);
        return redirect()->route('assign-inven-to-agency')->with('success', 'Iventory Updated Successfully');
    }
    public function assign_store(Request $request)
    {
        $this->validate($request, [
            'invenID'        => 'required',
            'agentIDs'      => 'required'
        ]);

        $arrayAgentIDs  = [];
        $inven          = InventoryModel::find($request->invenID);
        $invAgentIDs    = $inven->agent_id;

        if ($invAgentIDs == null) {
            $inven->agent_id = $request->agentIDs;
            $inven->save();
        } else {
            $arrayAgentIDs = explode(',', $invAgentIDs);
            foreach (explode(',', $request->agentIDs) as $id) {
                array_push($arrayAgentIDs, $id);
            }
            $arrayAgentIDs      = implode(',', $arrayAgentIDs);
            $inven->agent_id    = $arrayAgentIDs;
            $inven->save();
        }
        return redirect()->back()->with('success', 'Agency Assigned to Agencies Successfully');
    }
    public function stock_in_inventory($id)
    {
        $items  = ItemModel::where('inv_id', $id)->get();
        echo json_encode($items);
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy_inventory(Request $request)
    {
        $id = $request['id'];
        ItemModel::where('inv_id', $id)->update([
            'inv_id'    => null
        ]);
        $result = DB::table("nso007_inventery_stock")->where("id", $id)->delete();
        if ($result != 1)  return \back()->with("warning", "deleting is not successfull");

        \LogActivity::addToLog('Inventory is deleted');
        return \back()->with("success", "deleting is successfull");
    }
    public function view_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();
        echo json_encode($items);
    }
    public function agent_info($id)
    {
        $info = DB::table('users')
            ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
            ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
            ->leftjoin('nso007_agency_team as team', 'team.id', 'users.agency_team_id')
            ->select(
                'nso007_agency_type.agency_type_name as group_type',
                'users.id',
                'team.agency_team_name as team_name',
                'users.group_id',
                'nso007_agency_group.agency_group_name AS group',
                DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
            )
            ->where('users.id', $id)->first();
        echo json_encode($info);
    }
    public function filterByTeam(Request $request)
    {
        $team       = $request->team;
        $group      = $request->group;
        $type       = $request->type;
        $inv        = $request->inv;
        $inventory  = InventoryModel::find($inv);
        $agents     = DB::table('users')
            ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
            ->leftjoin('nso007_agency_team as team', 'team.id', 'users.agency_team_id')
            ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
            ->select(
                'nso007_agency_type.agency_type_name as group_type',
                'users.id',
                'team.agency_team_name as team_name',
                'nso007_agency_group.agency_group_name AS group',
                DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
            )
            ->where([['users.id', '!=', 1], ['users.role', 'Agencies']])
            ->when($type, function ($q) use ($type, $group) {
                if ($type == 1) {
                    $q->whereNull('users.group_id');
                } else {
                    if (!empty($group)) {
                        $q->where('users.group_id', $group);
                    } else {
                        $q->whereNotNull('users.group_id');
                    }
                }
            })
            ->when($team, function ($q, $team) {
                $q->where('users.agency_team_id', $team);
            })
            ->whereNotIn('users.id', explode(',', $inventory->agent_id))->get();
        echo json_encode($agents);
    }
    public function filterByTeamEdit(Request $request)
    {
        $team       = $request->team;
        $group      = $request->group;
        $type       = $request->type;
        $inv        = $request->inv;
        $inventory  = InventoryModel::find($inv);
        $agents     = DB::table('users')
            ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
            ->leftjoin('nso007_agency_team as team', 'team.id', 'users.agency_team_id')
            ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
            ->select(
                'nso007_agency_type.agency_type_name as group_type',
                'users.id',
                'team.agency_team_name as team_name',
                'nso007_agency_group.agency_group_name AS group',
                DB::raw('(CASE WHEN users.group_id = null THEN "Network" ELSE "Group" END) AS type'),
                DB::raw('CONCAT(user_firstname," ",user_lastname) as name')
            )
            ->where([['users.id', '!=', 1], ['users.role', 'Agencies']])
            ->when($type, function ($q) use ($type, $group, $inventory) {
                if ($type == 1) {
                    $q->whereNull('users.group_id');
                } else {
                    if (!empty($group)) {
                        $q->where('users.group_id', $group);
                    } else {
                        $q->whereNotNull('users.group_id');
                    }
                }
            })
            ->when($team, function ($q) use ($inventory, $team) {
                $q->where('users.agency_team_id', $team);
            })
            ->orWhereIn('users.id', explode(',', $inventory->agent_id))
            ->get();
        echo json_encode($agents);
    }
    public function get_search_data(Request $request)
    {
        $inv_id             = $request->inv_id;
        $agency_type_id     = $request->agent_type;
        $agency_group_id    = $request->agency_group;
        $agency_name_id     = $request->agency_name;
        $agency_team_id     = $request->team_id;

        $data = DB::table('users')
            ->join('nso007_agency_type', 'nso007_agency_type.id', 'users.agency_type')
            ->leftjoin('nso007_agency_team', 'nso007_agency_team.id', 'users.agency_team_id')
            ->leftjoin('nso007_agency_group', 'nso007_agency_group.id', 'users.group_id')
            ->select(
                'users.id',
                'nso007_agency_type.id',
                'nso007_agency_team.id',
                'nso007_agency_group.id',
                'nso007_agency_type.agency_type_name as group_type',
                'nso007_agency_team.agency_team_name as team_name',
                'nso007_agency_group.agency_group_name AS group',
                DB::raw('CONCAT(user_firstname," ",user_lastname) as agency_name')
            )
            ->where('users.id', '!=', 1)
            ->where('users.role', 'Agencies')
            ->where(function ($query) use ($agency_type_id) {
                if ($agency_type_id != null) {
                    $query->where('nso007_agency_type.id', $agency_type_id);
                }
            })
            ->where(function ($query) use ($agency_team_id) {
                if ($agency_team_id != null) {
                    $query->where('nso007_agency_team.id', $agency_team_id);
                }
            })
            ->where(function ($query) use ($agency_group_id) {
                if ($agency_group_id != null) {
                    $query->where('nso007_agency_group.id', $agency_group_id);
                }
            })
            ->where(function ($query) use ($agency_name_id) {
                if ($agency_name_id != null) {
                    $query->where('users.id', $agency_name_id);
                }
            })
            ->get();
        // dd($data);
        echo json_encode($data);
    }
}
