<?php

namespace App\Http\Controllers;

use App\Models\Warehouse;
use App\Models\WarehouseType;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class WarehouseController extends Controller
{
    /** UI string → INT stored in DB */
    private const TYPE_MAP = [
        'raw'     => 1,
        'finish'  => 2,
        'bag'     => 3,
        'g_store' => 4,
    ];

    /** INT in DB → UI string (reverse) */
    private const TYPE_REVERSE = [
        1 => 'raw',
        2 => 'finish',
        3 => 'bag',
        4 => 'g_store',
    ];

    /** GET /products/warehouses */
    public function index(Request $request)
    {
        $q = trim($request->get('q', ''));

        $warehouses = Warehouse::with(['warehouseType', 'createdBy', 'updatedBy'])
            ->when($q, fn ($qr) => $qr->where('name', 'like', "%{$q}%"))
            ->orderBy('id', 'asc')
            ->paginate(12)
            ->withQueryString();

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

    /** GET /products/warehouses/create */
    public function create()
    {
        $warehouseTypes = WarehouseType::orderBy('name')->get(['id', 'name', 'status']);
        return view('products.warehouses.create', compact('warehouseTypes'));
    }

    /** POST /products/warehouses */
    public function store(Request $request)
    {
        $data = $request->validate([
            'name'              => ['required', 'string', 'max:191', 'unique:warehouses,name'],
            'warehouse_type_id' => ['nullable', 'exists:rm_warehouse_types,id'],
            'type'              => ['required', Rule::in(array_keys(self::TYPE_MAP))], // string key from UI
            'status'            => ['required', Rule::in(['0', '1'])],
        ]);

        Warehouse::create([
            'name'              => $data['name'],
            'warehouse_type_id' => $data['warehouse_type_id'] ?? null,
            'type'              => self::TYPE_MAP[$data['type']],        // ← store INT
            'status'            => (int) $data['status'],                // tinyint/bool
            'created_by'        => auth()->id() ?? 1,
            'updated_by'        => auth()->id() ?? 1,
        ]);

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

    /** GET /products/warehouses/{warehouse}/edit */
    public function edit(Warehouse $warehouse)
    {
        $warehouseTypes = WarehouseType::orderBy('name')->get(['id', 'name', 'status']);
        // Provide a UI key for preselecting the dropdown
        $warehouse->type_key = self::TYPE_REVERSE[$warehouse->type] ?? null;

        return view('products.warehouses.edit', compact('warehouse', 'warehouseTypes'));
    }

    /** PUT/PATCH /products/warehouses/{warehouse} */
    public function update(Request $request, Warehouse $warehouse)
    {
        $data = $request->validate([
            'name'              => ['required', 'string', 'max:191', Rule::unique('warehouses', 'name')->ignore($warehouse->id)],
            'warehouse_type_id' => ['nullable', 'exists:rm_warehouse_types,id'],
            'type'              => ['required', Rule::in(array_keys(self::TYPE_MAP))], // string key from UI
            'status'            => ['required', Rule::in(['0', '1'])],
        ]);

        $warehouse->update([
            'name'              => $data['name'],
            'warehouse_type_id' => $data['warehouse_type_id'] ?? null,
            'type'              => self::TYPE_MAP[$data['type']],        // ← store INT
            'status'            => (int) $data['status'],
            'updated_by'        => auth()->id() ?? $warehouse->updated_by,
        ]);

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

    /** DELETE /products/warehouses/{warehouse} */
    public function destroy(Warehouse $warehouse)
    {
        $warehouse->delete();

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