<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Warehouse;
use Illuminate\Support\Facades\Validator;

class WarehouseController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $warehouses = Warehouse::withCount('inventories')->paginate(10);

        if ($request->wantsJson() || $request->is('api/*')) {
            return response()->json($warehouses);
        }

        return view('warehouses.index', compact('warehouses'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('warehouses.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'code' => 'required|string|unique:warehouses,code',
            'type' => 'required|in:raw_material,finished_goods,returns,scrap',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        Warehouse::create($request->all());

        return redirect()->route('warehouses.index')->with('success', 'Warehouse registered.');
    }

    /**
     * Display the specified resource.
     */
    public function show(Warehouse $warehouse)
    {
        $warehouse->load('inventories.product');
        return view('warehouses.show', compact('warehouse'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Warehouse $warehouse)
    {
        return view('warehouses.edit', compact('warehouse'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Warehouse $warehouse)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|required|string|max:255',
            'code' => 'sometimes|required|string|unique:warehouses,code,' . $warehouse->id,
            'type' => 'sometimes|required|in:raw_material,finished_goods,returns,scrap',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $warehouse->update($request->all());

        return redirect()->route('warehouses.index')->with('success', 'Warehouse updated.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Warehouse $warehouse)
    {
        if ($warehouse->inventories()->where('quantity', '>', 0)->exists()) {
            return back()->with('error', 'Cannot delete warehouse with active stock.');
        }
        $warehouse->delete();
        return redirect()->route('warehouses.index')->with('success', 'Warehouse removed.');
    }
}
