<?php

namespace App\Http\Controllers\Product;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\ProductLocationRack;
use App\Models\ProductWarehouse;
use Illuminate\Http\Request;

class ProductLocationRackController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:product-location-rack-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = ProductLocationRack::select([
            'product_location_racks.id',
            'product_location_racks.name',
            'product_location_racks.code',
            'product_location_racks.warehouse_id',
            'product_location_racks.company_id',
            'product_location_racks.priority',
            'product_location_racks.is_default',
            'product_location_racks.status',
        ])
        ->with('getCompany')
        ->with('getWarehouse')
        ->paginate(10);

            if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = ProductLocationRack::select([
                'product_location_racks.id',
                'product_location_racks.name',
                'product_location_racks.code',
                'product_location_racks.warehouse_id',
                'product_location_racks.company_id',
                'product_location_racks.priority',
                'product_location_racks.is_default',
                'product_location_racks.status',
            ])
            ->with('getCompany')
            ->with('getWarehouse')
            ->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where( 'product_location_racks.name', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);
            return view('product-location-rack.table', compact('data'));
        } else {
            return view('product-location-rack.index', compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        // $warehouse = ProductWarehouse::all();
        $warehouse = ProductWarehouse::select('id', 'name')->where('status',1)->get();
        $company = Company::select('id', 'name')->get();
        // $company = Company::all();
        return view('product-location-rack.create', compact('warehouse','company'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name'         => 'required|unique:product_location_racks',
            'warehouse_id' => 'required',
            'company_id'   => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $default_check = ProductLocationRack::where(['is_default' => 1,'status' => 1])->first();

        if (!$default_check) {
            $data['is_default'] = 1;
        }

        $quality = ProductLocationRack::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Location Rack created successfully',
                'data'    => $quality
            ]);
        }
        return redirect()->route('product-location-rack.index')
            ->with('success', 'Location Rack created successfully');
    }


    /**
     * 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)
    {
        $location  = ProductLocationRack::find($id);
        $warehouse = ProductWarehouse::select('id', 'name')->where('status',1)->get();
        $company   = Company::all();

        return view('product-location-rack.edit', compact('location', 'warehouse','company'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:product_location_racks,name,'.$id,
        ]);

        if ($validator->fails()) {
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $master = ProductLocationRack::find($id);

        if (!$master) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => "Product Location Rack  Type not found!",
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', "Product Location Rack  not found!");
        }

        $master->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Product Location Rack has been created successfully',
            ]);
        }

        return redirect()->route('product-location-rack.index')->with('success','Product Location Rack updated successfully');
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        ProductLocationRack::find($request->id)->delete();

        $Redirect = 'product-location-rack';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }

    public function changeStatus(Request $request)
    {
       if ($request->ajax())
       {
           $data   = array('status' => $request->status );
           $Update = ProductLocationRack::where('id', '=', $request->id)->update($data);

           if($Update){
               return response()->json([
                   'success' => true,
                   'message' => ['Location Rack status successfully change'],
                   'data'    => [
                       'redirect'=>'/buckets/',
                       'reload'=>true,
                   ]
               ]);
           }
           else{
               return response()->json([
                   'success' => false,
                   'message' => ['Location Rack for change status'],
                   'data'    => []
               ]);
           }
       }
    }
}
