<?php

namespace App\Livewire\Settings;

use App\Domain\Shared\Models\Academy;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('إعدادات الأكاديمية')]
class AcademySettings extends Component
{
    public string $name = '';
    public string $name_ar = '';
    public string $phone = '';
    public string $email = '';
    public string $address = '';
    public string $timezone = 'Africa/Cairo';
    public string $currency = 'EGP';

    public function mount(): void
    {
        // Every sibling settings screen authorizes; this one did not, so any
        // authenticated user who reached the route could rename the academy.
        $this->authorize('settings.manage');

        $academy = app('current_academy');
        if ($academy) {
            $this->name = $academy->name ?? '';
            $this->name_ar = $academy->name_ar ?? '';
            $this->phone = $academy->phone ?? '';
            $this->email = $academy->email ?? '';
            $this->address = $academy->address ?? '';
            $this->timezone = $academy->timezone ?? 'Africa/Cairo';
            $this->currency = $academy->currency ?? 'EGP';
        }
    }

    public function save(): void
    {
        $this->validate([
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'address' => 'nullable|string',
        ]);

        $this->authorize('settings.manage');

        $academy = app('current_academy');
        $academy->update([
            'name' => $this->name,
            'name_ar' => $this->name_ar,
            'phone' => $this->phone ?: null,
            'email' => $this->email ?: null,
            'address' => $this->address ?: null,
            'timezone' => $this->timezone,
            'currency' => $this->currency,
        ]);

        // The academy name and address feed the resolved brand profile.
        app(\App\Domain\Shared\Services\BrandingService::class)->bump($academy->id);

        session()->flash('success', __('تم حفظ الإعدادات بنجاح'));
    }

    public function render()
    {
        return view('livewire.settings.academy-settings');
    }
}
