<?php

namespace App\Http\Controllers\Admin;

use App\Models\Warehouse;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Response;

class WarehouseController extends Controller
{
    /**
     * Display a listing of warehouses.
     */
    public function index(Request $request)
    {
        Gate::authorize('viewAny', Warehouse::class);

        $warehouses = Warehouse::with('shop')
            ->forUser($request->user())
            ->latest()
            ->paginate(20);

        return $request->ajax()
            ? response()->json($warehouses)
            : view('pages.admin.warehouses.index', compact('warehouses'));
    }
    /**
     * Show the form for creating a new warehouse.
     */
    public function create()
    {
        return view('pages.admin.warehouses.create');
    }

    /**
     * Store a newly created warehouse in storage.
     */
    public function store(Request $request)
    {
        Gate::authorize('create', Warehouse::class);

        $validated = $request->validate([
            'shop_id'   => 'required|exists:shops,id',
            'name'      => 'required|string|max:255',
            'code'      => 'nullable|string|max:64|unique:warehouses,code',
            'is_active' => 'boolean',
            'address'   => 'nullable|array',
        ]);

        // Force shop users to only create for their own shop_id
        if (!$request->user()->hasRole('admin')) {
            $validated['shop_id'] = $request->user()->shop->id;
        }

        $warehouse = Warehouse::create($validated);

        return $request->ajax()
            ? response()->json(['data' => $warehouse, 'message' => __('Warehouse created successfully.')], 201)
            : redirect()->route('admin.warehouses.index')->with('success', __('Warehouse created successfully.'));
    }

    /**
     * Display the specified warehouse.
     */
    public function show(Request $request, Warehouse $warehouse)
    {
        Gate::authorize('view', $warehouse);
        $warehouse->load('shop', 'inventories');

        return $request->ajax()
            ? response()->json($warehouse)
            : view('pages.admin.warehouses.show', compact('warehouse'));
    }

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

    /**
     * Update the specified warehouse in storage.
     */

    public function update(Request $request, Warehouse $warehouse)
    {
        Gate::authorize('update', $warehouse);

        $validated = $request->validate([
            'shop_id'   => 'required|exists:shops,id',
            'name'      => 'required|string|max:255',
            'code'      => 'nullable|string|max:64|unique:warehouses,code,' . $warehouse->id,
            'is_active' => 'boolean',
            'address'   => 'nullable|array',
        ]);

        if (!$request->user()->hasRole('admin')) {
            $validated['shop_id'] = $request->user()->shop->id; // cannot switch tenant
        }

        $warehouse->update($validated);

        return $request->ajax()
            ? response()->json(['data' => $warehouse, 'message' => __('Warehouse updated successfully.')])
            : redirect()->route('admin.warehouses.index')->with('success', __('Warehouse updated successfully.'));
    }

    /**
     * Remove the specified warehouse from storage.
     */
    public function destroy(Request $request, Warehouse $warehouse)
    {
        Gate::authorize('delete', $warehouse);
        $warehouse->delete();

        return $request->ajax()
            ? response()->json(['message' => __('Warehouse deleted successfully.')])
            : redirect()->route('admin.warehouses.index')->with('success', __('Warehouse deleted successfully.'));
    }
}
