<?php

namespace Modules\MedWorkforce\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * Shared helpers for the MedWorkforce back-office controllers: business scoping,
 * permission guards, the JSON response envelope, and the fail-soft lookups the
 * roster/compliance screens reuse (staff, departments, locations). Mirrors
 * Modules\MedBilling\Http\Controllers\MedBillingBaseController.
 */
abstract class MedWorkforceBaseController extends Controller
{
    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.');
        }
    }

    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')];
    }

    /** Staff dropdown for this business (id => full name), no "none" row. */
    protected function staff(): array
    {
        return \App\User::forDropdown($this->businessId(), false)->toArray();
    }

    /**
     * Departments for this business from ClinicCore (clc_departments). Fail-soft:
     * empty when ClinicCore is not installed.
     *
     * @return array<int, string>
     */
    protected function departments(): array
    {
        if (! Schema::hasTable('clc_departments')) {
            return [];
        }

        return DB::table('clc_departments')
            ->where('business_id', $this->businessId())
            ->when(Schema::hasColumn('clc_departments', 'status'), fn ($q) => $q->where('status', 'active'))
            ->orderBy('name')
            ->pluck('name', 'id')
            ->toArray();
    }

    /**
     * Business locations (id => name) for this business.
     *
     * @return array<int, string>
     */
    protected function locations(): array
    {
        if (! Schema::hasTable('business_locations')) {
            return [];
        }

        return DB::table('business_locations')
            ->where('business_id', $this->businessId())
            ->whereNull('deleted_at')
            ->orderBy('name')
            ->pluck('name', 'id')
            ->toArray();
    }
}
