<?php

namespace App\Http\Controllers\Admin\Warehouse;

use App\Http\Controllers\Controller;
use App\Models\Warehouse;
use App\Models\WarehouseStock;
use App\Service\Warehouse\WarehouseService;
use Illuminate\Http\Request;
use Inertia\Inertia;

class WarehouseController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return Inertia::render('Warehouse/Warehouses');
    }

    public function view()
    {
        return response()->json(['warehouse' => Warehouse::orderbydesc('id')->where('status', 'warehouse')->get()]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {

        $data = request()->all();
        $data['status'] = 'warehouse';
        WarehouseService::StoreData(data: $data);

        return response()->json(['success' => 'Warehouse carate successfully', 'warehouse' => Warehouse::where('status', 'warehouse')->orderbydesc('id')->get()]);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Request $request, $id) {}

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        WarehouseService::UpdateData(request()->all(), $id);

        return response()->json(['success' => 'Warehouse update successfully', 'warehouse' => Warehouse::where('status', 'warehouse')->orderbydesc('id')->get()]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $warehouse = Warehouse::where('id', $id)->first();

        if (! $warehouse) {
            return response()->json(['error' => 'Warehouse not found'], 404);
        }

        $data = WarehouseStock::where('warehouse_id', '=', $warehouse->id)->first();

        if ($data) {
            return response()->json(['error' => 'This Warehouse has a product'], 422);
        }

        $warehouse->delete();

        return response()->json(['success' => 'Warehouse delete successfully', 'warehouse' => Warehouse::where('status', 'warehouse')->orderbydesc('id')->get()]);
    }
}
