<?php

namespace App\Modules\Dashboard\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\Models\Module;
use Illuminate\View\View;

class ModulePlaceholderController extends Controller
{
    public function inventory(): View
    {
        $this->authorizeAnyAbility(
            'inventory.catalog.view',
            'inventory.warehouses.view',
            'inventory.stock.view',
        );

        return $this->placeholder('inventory');
    }

    public function finance(): View
    {
        $this->authorize('accounting.hub');

        return $this->placeholder('finance');
    }

    public function crm(): View
    {
        $this->authorize('dashboard.company');

        return $this->placeholder('crm');
    }

    public function sales(): View
    {
        $this->authorizeAnyAbility('sales.orders.view');

        return $this->placeholder('sales');
    }

    private function authorizeAnyAbility(string ...$abilities): void
    {
        $user = auth()->user();
        abort_if($user === null, 403);
        if ($user->isAdmin() || $user->isTenantOwner()) {
            return;
        }
        foreach ($abilities as $ability) {
            if ($user->can($ability)) {
                return;
            }
        }
        abort(403);
    }

    private function placeholder(string $slug): View
    {
        $module = Module::query()->where('slug', $slug)->first();

        return view('pages.dashboard.placeholder', [
            'slug' => $slug,
            'moduleName' => $module?->name,
        ]);
    }
}
