<?php


namespace App\Http\Controllers\Administrator\setup;

use App\Model\people\TailorModel;
use App\Model\stock_inventory\PurchaseDetailsModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\setup\BranchModel;
use DB;
use DataTables;
use App\Model\setup\WarehouseModel;
use App\User;
use Illuminate\Validation\ValidationException;
use Session;
use Auth;

class WarehouseController extends Controller

{
    function __construct()
    {
        $this->middleware('permission:Warehouse Create', ['only' => [ 'create', 'store']]);
        $this->middleware('permission:Warehouse List', ['only' => ['index']]);
        $this->middleware('permission:Warehouse Show', ['only' => ['show']]);
        $this->middleware('permission:Warehouse Edit', ['only' => ['update','edit']]);
        $this->middleware('permission:Warehouse Set-main', ['only' => ['warehouse_changeStatus']]);

    }
    public function index()

    {
        $user_role = Auth::user()->branch_id;
        $user_role = findBranch($user_role);
        $user_role = $user_role->main??'';
        $data= WarehouseModel:: where(function ($query) use ($user_role) {
            if ($user_role!==1) {
                $query->Where('branch_id',Auth::user()->branch_id);
            }
        })
        ->latest()->get();
        return view('administrator.setup.warehouse.index', compact('data'));
    }
    public function destroy_wh(Request $request){
        WarehouseModel::where('id',$request->id)->delete();
        return response()->json('ok');
    }
    public function create()

    {
        $user = User::pluck('name', 'id');
        $branch = BranchModel::pluck('name', 'id');
        return view('administrator.setup.warehouse.create', compact('user', 'branch'));
    }
    public function getAvailableTailor(Request $request){
        $tailor_pre = null;
        if($request->wh_id){
            $wh = findWarehouse($request->wh_id);
            $tailor = $wh?$wh->tailor_id:'';
            $tailor_pre = findTailor($tailor);
        }
        $tailor = null;
        $t_wh = WarehouseModel::where('tailor_id','!=',null)->where('warehouse_type',$request->type)->groupBy('tailor_id')->pluck('tailor_id');
        $tailor = TailorModel::whereNotIn('id',$t_wh)->pluck('name','id');
        if($tailor_pre){
            $tailor = $tailor->prepend(($tailor_pre->name),($tailor_pre->id));
        }
        return response()->json($tailor);
    }
    public function store(Request $request)

    {
        $this->validate($request, [
            'warehouse_name' => 'required|max:30|unique:nso007_warehouse,warehouse_name',
            'warehouse_type'=> myBranch()->main?'required':'nullable',
            'branch_id'=> myBranch()->main?'required':'nullable'
        ]);
        $type = $request->warehouse_type;
        $tailor = $request->tailor_id;
        if($type=='tailor'){
            if(!$tailor){
                throw ValidationException::withMessages(['warning'=>'Please Select a tailor']);
            }
        }
        $warehouse = new WarehouseModel;
        $warehouse->warehouse_name = $request->warehouse_name;
        if(myBranch()->main){
            $warehouse->branch_id = $request->branch_id;
            $warehouse->warehouse_type     = $type;
            $warehouse->tailor_id     = $tailor;
        }else{
            $warehouse->warehouse_type     = 'item';
            $warehouse->branch_id = Auth::user()->branch_id;
        }
        $warehouse->location_name = $request->address;
        $warehouse->description = $request->description;
        $warehouse->save();
        session()->put('success','Record inserted successful');
        return response()->json(['status' => 'success', 'route' => route('warehouse.index')]);
    }

    public function show($id)
    {
        $warehouse = WarehouseModel::find($id);
        return view('administrator.setup.warehouse.show', compact('warehouse'));
    }

    public function datatable_history_suppliers(Request $request)
    {
        $id = Session::get('id');
        $search = $request->input('search.value');
        $count_total = WarehouseModel::select('nso007_suppliers.id')
            ->join('nso007_suppliers', 'nso007_suppliers.id', '=', 'nso007_purchases.warehouse_id')
            ->where(['nso007_purchases.status' => 1])
            ->where(['nso007_suppliers.id' => $id])
            ->count();

        $count_filter = WarehouseModel::select('nso007_purchases.*')
            ->join('nso007_suppliers', 'nso007_suppliers.id', '=', 'nso007_purchases.warehouse_id')
            ->where(['nso007_purchases.status' => 1])
            ->where(['nso007_suppliers.id' => $id])
            ->where(function ($query) use ($search) {
                $query->orWhere('nso007_purchases.invoice_number', 'LIKE', '%' . $search . '%');
                $query->orWhere('nso007_purchases.transaction_code', 'LIKE', '%' . $search . '%');
            })
            ->count();

        $data = WarehouseModel::select('nso007_purchases.*',

            DB::raw('SUM(nso007_purchase_details.qty*nso007_purchase_details.cost - nso007_purchase_details.qty*nso007_purchase_details.cost*nso007_purchase_details.dis/100) as amount'))
            ->join('nso007_purchase_details', 'nso007_purchase_details.purchase_id', '=', 'nso007_purchases.id')
            ->join('nso007_suppliers', 'nso007_suppliers.id', '=', 'nso007_purchases.warehouse_id')
            ->where(['nso007_purchases.status' => 1])
            ->where(['nso007_suppliers.id' => $id])
            ->groupby('nso007_purchase_details.purchase_id')
            ->take(10);

        if ($request->isMethod('get')) {

            return Datatables::of($data)
                ->with([

                    "recordsTotal" => $count_total,

                    "recordsFiltered" => $count_filter,

                ])
                ->addColumn('created_at', function ($purchase) {

                    return date('d-m-Y', strtotime($purchase->created_at));

                })
                ->addColumn('total', function ($purchase) {

                    return '$' . number_format($purchase->amount, 2);

                })
                ->addColumn('purchase_date', function ($purchase) {

                    return date('d-m-Y', strtotime($purchase->purchase_date));

                })
                ->addColumn('invoice_number', function ($purchase) {

                    return '<a href="' . route("show_history_detials", $purchase->id) . '" title="Edit" class="button_info">' . $purchase->invoice_number . '</a>';

                })
                ->addIndexColumn()
                ->rawColumns(['invoice_number' => 'invoice_number'])
                ->make(true);

        }

    }

    public function show_history_detials($id)

    {

        // Purchases

        $purchases = WarehouseModel::join('nso007_suppliers', 'nso007_suppliers.id', '=', 'nso007_purchases.warehouse_id')
            ->join('users', 'users.id', '=', 'nso007_purchases.user_id')->find($id);

        $warehouse_id = $purchases->warehouse_id;


        // Find Supplier Type

        $warehouse_type = WarehouseModel::join('nso007_warehouse_type', 'nso007_warehouse_type.id', '=', 'nso007_suppliers.warehouse_type_id')
            ->where('nso007_suppliers.id', $warehouse_id)
            ->first();

        // Purchase Details

        $purchase_details = PurchaseDetailsModel::select('nso007_suppliers.*', 'nso007_purchase_details.*', 'nso007_products.product_name')
            ->join('nso007_products', 'nso007_products.barcode', '=', 'nso007_purchase_details.product_code')
            ->join('nso007_purchases', 'nso007_purchases.id', '=', 'nso007_purchase_details.purchase_id')
            ->join('nso007_suppliers', 'nso007_suppliers.id', '=', 'nso007_purchases.warehouse_id')
            ->where(['nso007_purchase_details.status' => 1])
            ->where(['nso007_purchase_details.purchase_id' => $id])
            ->get();
        return view('administrator.setup.warehouse.show-history-detials', compact('purchase_details', 'purchases', 'warehouse_type'));

    }

    public function edit($id)

    {
        $warehouse = WarehouseModel::find($id);
        $user = User::pluck('name', 'id');
        $branch = BranchModel::pluck('name', 'id');
        $t_wh = WarehouseModel::where('tailor_id','!=',null)->groupBy('tailor_id')->pluck('tailor_id');
        $s_tailor = findTailor($warehouse->tailor_id);
        $s_tailor = $s_tailor?$s_tailor->name:'';
        $tailor = TailorModel::whereNotIn('id',$t_wh)->pluck('name','id')->prepend($s_tailor,$warehouse->tailor_id);
        return view('administrator.setup.warehouse.edit', compact('user', 'branch','tailor','warehouse'));

    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'warehouse_name' => 'required|max:30|unique:nso007_warehouse,warehouse_name,' . $id,
            'warehouse_type' => myBranch()->main?'required':'nullable',
            'branch_id'=> myBranch()->main?'required':'nullable'

        ]);
        $type = $request->warehouse_type;
        $tailor = $request->tailor_id;
        if($type=='tailor'){
            if(!$tailor){
                throw ValidationException::withMessages(['warning'=>'Please Select a tailor']);
            }
        }
        $warehouse = WarehouseModel::find($id);
        $warehouse->warehouse_name = $request->warehouse_name;
        if(myBranch()->main){
            $warehouse->branch_id = $request->branch_id;
            $warehouse->warehouse_type     = $type;
            $warehouse->tailor_id     = $tailor;
        }else{
            $warehouse->warehouse_type     = 'item';
            $warehouse->branch_id = Auth::user()->branch_id;
        }
        $warehouse->location_name = $request->address;
        $warehouse->description = $request->description;
        $warehouse->update();
        session()->put('success','Record inserted successful');
        return response()->json(['status' => 'success', 'route' => route('warehouse.index')]);
    }

    public function warehouse_changeStatus(Request $request)
    {
        $warehouse = WarehouseModel::find($request->id);
        WarehouseModel::where(['branch_id'=>Auth::user()->branch_id,'warehouse_type'=>$warehouse->warehouse_type])->update(['main' => 0]);
        $warehouse->update(['main' => 1]);

        return response()->json(['success' => 'Status change successfully.']);
    }


    // public use
    public function get_select_warehouse(Request $request)
    {
        $type = $request->type;
        $wh = WarehouseModel::where('branch_id', $request->branch)
            ->where(function ($q) use ($type){
                $q->where('warehouse_type',$type);
            })
            ->pluck('warehouse_name', 'id');
        $option = '<option value="">' . __('administrator.please_select') . '</option>';
        foreach ($wh as $key => $row) {
            $option .= '<option value="' . $key . '">' . $row . '</option>';
        }
        return $option;
    }
    public function find_warehouse_by_type(Request $request){
        $type = $request->type;
        $tailor = TailorModel::where('type',$type)->pluck('id');
        $warehouse = WarehouseModel::whereIn('tailor_id',$tailor)->pluck('tailor_id');
        $tailor = TailorModel::whereIn('id',$warehouse)->pluck('name','id');
        return response()->json($tailor);
    }
}

