<?php

namespace Modules\Bms\Http\Controllers;

use App\Http\Controllers\Controller;

/**
 * Shared helpers for the BMS back-office controllers: business scoping,
 * permission guards and the standard JSON response envelope used by the
 * crud_scripts.blade.php AJAX handlers.
 */
abstract class BmsBaseController 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')];
    }

    /** Default catalog lists (used when nothing is configured in settings). */
    public static function defaultFnbLevels(): array
    {
        return [
            ['key' => 'high_tea',    'en' => 'High Tea',    'ar' => 'شاي راقٍ'],
            ['key' => 'drinks_only', 'en' => 'Drinks Only', 'ar' => 'مشروبات فقط'],
            ['key' => 'set_menu',    'en' => 'Set Menu',    'ar' => 'منيو محدد'],
            ['key' => 'open_buffet', 'en' => 'Open Buffet', 'ar' => 'بوفيه مفتوح'],
            ['key' => 'custom',      'en' => 'Custom',      'ar' => 'مخصص'],
        ];
    }

    public static function defaultFeatures(): array
    {
        return [
            ['key' => 'parking',          'en' => 'Parking',          'ar' => 'موقف سيارات'],
            ['key' => 'valet',            'en' => 'Valet',            'ar' => 'خدمة صف السيارات'],
            ['key' => 'stage',            'en' => 'Stage',            'ar' => 'مسرح'],
            ['key' => 'bridal_room',      'en' => 'Bridal Room',      'ar' => 'غرفة العروس'],
            ['key' => 'led_screens',      'en' => 'LED Screens',      'ar' => 'شاشات LED'],
            ['key' => 'sound_system',     'en' => 'Sound System',     'ar' => 'نظام صوت'],
            ['key' => 'garden',           'en' => 'Garden',           'ar' => 'حديقة'],
            ['key' => 'river_view',       'en' => 'River View',       'ar' => 'إطلالة على النيل'],
            ['key' => 'catering_kitchen', 'en' => 'Catering Kitchen', 'ar' => 'مطبخ تموين'],
        ];
    }

    /** A configured catalog list (or defaults) as [key => localized label]. */
    protected function catalogList(string $key, array $defaults): array
    {
        $rows = \Modules\Bms\Entities\BmsSetting::get($this->businessId(), $key, $defaults);
        $loc = app()->getLocale() === 'ar' ? 'ar' : 'en';
        $out = [];
        foreach ((array) $rows as $r) {
            if (! empty($r['key'])) {
                $out[$r['key']] = $r[$loc] ?? $r['en'] ?? $r['key'];
            }
        }
        return $out ?: collect($defaults)->mapWithKeys(fn ($r) => [$r['key'] => $r['en']])->toArray();
    }

    /** F&B levels available across the module (value => label) — settings-driven. */
    protected function fnbLevels(): array
    {
        return $this->catalogList('fnb_levels', self::defaultFnbLevels());
    }

    /** Hall feature flags (value => label) — settings-driven. */
    protected function featureKeys(): array
    {
        return $this->catalogList('hall_features', self::defaultFeatures());
    }

    /** Venue types (value => label). */
    protected function venueTypes(): array
    {
        return [
            'open'   => __('bms::lang.open_air'),
            'closed' => __('bms::lang.closed'),
            'both'   => __('bms::lang.both'),
        ];
    }

    /** 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();
    }
}
