<?php

namespace Modules\MedRegistry\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Utils\ModuleUtil;

/**
 * Shared helpers for the MedRegistry back-office controllers: business
 * scoping, permission/admin/subscription guards. Mirrors VrcBaseController.
 */
abstract class MedRegistryBaseController extends Controller
{
    /** @var ModuleUtil */
    protected $moduleUtil;

    public function __construct()
    {
        $this->moduleUtil = new ModuleUtil();
    }

    protected function businessId(): int
    {
        return (int) request()->session()->get('user.business_id');
    }

    protected function userId(): ?int
    {
        return request()->session()->get('user.id');
    }

    protected function guard(string $permission): void
    {
        if (! auth()->user()->can($permission)) {
            abort(403, 'Unauthorized action.');
        }
    }

    /**
     * Admin-only gate (same check other modules use:
     * ModuleUtil::is_admin → role Admin#<business_id>).
     */
    protected function guardAdmin(): void
    {
        if (! $this->moduleUtil->is_admin(auth()->user(), $this->businessId())) {
            abort(403, 'Unauthorized action.');
        }
    }

    /**
     * Superadmin subscription gate for the registry itself — reuses
     * ModuleUtil::hasThePermissionInSubscription (never reimplemented).
     */
    protected function guardSubscription(): void
    {
        if (! $this->moduleUtil->hasThePermissionInSubscription($this->businessId(), 'medreg_module')) {
            abort(403, 'Unauthorized action.');
        }
    }

    protected function ok(string $msg, array $extra = []): array
    {
        return array_merge(['success' => true, 'msg' => $msg], $extra);
    }

    protected function fail(?string $msg = null): array
    {
        return ['success' => false, 'msg' => $msg ?: __('messages.something_went_wrong')];
    }

    /** ERP business locations for the current business (id => name). */
    protected function locations(): array
    {
        return \App\BusinessLocation::where('business_id', $this->businessId())
            ->pluck('name', 'id')
            ->toArray();
    }

    /**
     * ClinicCore departments (id => name) when that module's table exists —
     * department granularity is optional and never assumed.
     */
    protected function departments(): array
    {
        if (! \Illuminate\Support\Facades\Schema::hasTable('clc_departments')) {
            return [];
        }

        return \Illuminate\Support\Facades\DB::table('clc_departments')
            ->where('business_id', $this->businessId())
            ->pluck('name', 'id')
            ->toArray();
    }
}
