<?php

namespace App\Http\Controllers;
use App\Http\Requests\warehouseRequest;
use App\Models\establishment;
use App\Models\warehouse;
use Illuminate\Http\Request;
use Inertia\Inertia;

class warehouseController extends Controller
{
    public function getWarehouseByName() {
        $data = warehouse::where('status', '1')->get();

        return response()->json($data, 200);
    }

    public function getStablishmentByName() {
        $data = establishment::where('status', '1')->get();

        return response()->json($data, 200);
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $query = warehouse::select(['warehouse.*', 'establishment.name as establishment_name'])
            ->join('establishment', 'warehouse.establishment_id', '=', 'establishment.id')
            ->latest('warehouse.id');

        if (request()->input('name')) {
            $query->where('warehouse.name', 'LIKE', '%' . request()->input('name') . '%');
        }

        if (request()->input('description')) {
            $query->where('warehouse.description', 'LIKE', '%' . request()->input('description') . '%');
        }

        if (request()->input('establishment_name')) {
            $query->where('establishment.name', 'LIKE', '%' . request()->input('establishment_name') . '%');
        }

        $warehouse = $query->paginate(10)->withQueryString();

        return Inertia::render('warehouse/Index', [
            'warehouse' => $warehouse
        ]);
    }


    /**
     * Store a newly created resource in storage.
     */
    public function store(warehouseRequest $request)
    {
        $data = new warehouse($request->input());
        $data->save();
        return redirect('warehouse');
    }

    /**
     * Display the specified resource.
     */
    public function show(warehouse $warehouse)
    {
        $warehouse->load('district.province.department');
        return $warehouse;
    }

    public function update(Request $request, warehouse $warehouse)
    {
        $warehouse->update($request->input());
        return redirect('warehouse');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(warehouse $warehouse)
    {
        $warehouse->status = '1';
        $warehouse->save();
        $warehouse->delete();
        return redirect('warehouse');
    }

}
