<?php

namespace App\Http\Controllers\Company\Inventory;

use App\Http\Controllers\Controller;
use App\Models\{AuditLog, Warehouse};
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class WarehousesController extends Controller
{
    public function index()
    {
        $this->gate('view');

        $companyId  = auth()->user()->company_id;
        $warehouses = Warehouse::withoutGlobalScopes()
            ->where('company_id', $companyId)
            ->whereNull('deleted_at')
            ->orderBy('name')
            ->get();

        $tree = $this->buildTree($warehouses);

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

    public function store(Request $request)
    {
        $this->gate('create');
        $companyId = auth()->user()->company_id;

        $validated = $request->validate([
            'name'      => 'required|string|max:150',
            'code'      => 'nullable|string|max:30',
            'type'      => 'required|in:warehouse,zone,rack,bin',
            'parent_id' => 'nullable|integer',
            'address'   => 'nullable|string|max:500',
        ]);

        $parentId = null;
        $depth    = 0;

        if (!empty($validated['parent_id'])) {
            $parent = Warehouse::withoutGlobalScopes()
                ->where('company_id', $companyId)
                ->find($validated['parent_id']);
            if ($parent) {
                $parentId = $parent->id;
                $depth    = $parent->depth + 1;
            }
        }

        $wh = Warehouse::withoutGlobalScopes()->create([
            'company_id' => $companyId,
            'parent_id'  => $parentId,
            'code'       => $validated['code'] ?? null,
            'name'       => $validated['name'],
            'type'       => $validated['type'],
            'address'    => $validated['address'] ?? null,
            'depth'      => $depth,
            'is_active'  => true,
        ]);

        AuditLog::record('create', 'warehouses', (string) $wh->id, null,
            ['name' => $wh->name], "Warehouse created: {$wh->name}");

        return back()->with('success', "'{$wh->name}' created.");
    }

    public function update(Request $request, Warehouse $warehouse)
    {
        $this->gate('edit');
        $this->sameCompany($warehouse);

        $request->validate([
            'name'      => 'required|string|max:150',
            'code'      => 'nullable|string|max:30',
            'type'      => 'required|in:warehouse,zone,rack,bin',
            'address'   => 'nullable|string|max:500',
            'is_active' => 'boolean',
        ]);

        $warehouse->update([
            'name'      => $request->name,
            'code'      => $request->code,
            'type'      => $request->type,
            'address'   => $request->address,
            'is_active' => $request->boolean('is_active', true),
        ]);

        AuditLog::record('update', 'warehouses', (string) $warehouse->id,
            null, ['name' => $warehouse->name], "Warehouse updated: {$warehouse->name}");

        return back()->with('success', "'{$warehouse->name}' updated.");
    }

    public function destroy(Warehouse $warehouse)
    {
        $this->gate('delete');
        $this->sameCompany($warehouse);

        $guard = app(\App\Services\MasterDeletionGuard::class);
        if ($message = $guard->blockingMessage($warehouse)) {
            return back()->withErrors(['error' => $message]);
        }

        $name = $warehouse->name;
        $id = $warehouse->id;
        $guard->hardDelete($warehouse);

        AuditLog::record('hard_delete', 'warehouses', (string) $id,
            null, null, "Warehouse permanently deleted: {$name}");

        return back()->with('success', "'{$name}' permanently deleted.");
    }

    // ── AJAX search ───────────────────────────────────────────────────────────
    public function search(Request $request)
    {
        $companyId = auth()->user()->company_id;
        $q         = $request->input('q', '');

        $warehouses = Warehouse::withoutGlobalScopes()
            ->where('company_id', $companyId)
            ->whereNull('deleted_at')
            ->where('is_active', true)
            ->when($q, fn($query) => $query->where(fn($qq) =>
                $qq->where('name', 'like', "%{$q}%")->orWhere('code', 'like', "%{$q}%")
            ))
            ->orderBy('name')
            ->limit(50)
            ->get(['id','code','name','type']);

        return response()->json([
            'results' => $warehouses->map(fn($w) => [
                'id'   => $w->id,
                'text' => ($w->code ? "[{$w->code}] " : '') . $w->name,
                'type' => $w->type,
            ])
        ]);
    }

    private function buildTree($warehouses, $parentId = null): array
    {
        $tree = [];
        foreach ($warehouses->where('parent_id', $parentId) as $wh) {
            $wh->children_tree = $this->buildTree($warehouses, $wh->id);
            $tree[] = $wh;
        }
        return $tree;
    }

    private function gate(string $action): void
    {
        if (!auth()->user()->hasPermission('inventory', $action)) abort(403);
    }

    private function sameCompany(Warehouse $wh): void
    {
        if ($wh->company_id !== auth()->user()->company_id) abort(403);
    }
}
