<?php

namespace App\Filament\Pages;

use Filament\Pages\Page;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Form;
use Filament\Forms;
use App\Models\Setting;
use Filament\Notifications\Notification;

class ManageSystemSettings extends Page implements HasForms
{
    use InteractsWithForms;

    protected static ?string $navigationIcon = 'heroicon-o-cog-6-tooth';
    protected static ?string $navigationLabel = 'Tetapan Sistem';
    protected static ?string $title = 'Tetapan Aplikasi';
    protected static ?string $navigationGroup = 'Sistem';

    protected static string $view = 'filament.pages.manage-system-settings';

    public ?array $data = [];

    public function mount(): void
    {
        $setting = Setting::first();
        if ($setting) {
            $this->form->fill($setting->toArray());
        } else {
            $this->form->fill();
        }
    }

    public static function canAccess(): bool
    {
        return auth()->user()?->role === 'admin';
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Maklumat Aplikasi')
                    ->schema([
                        Forms\Components\TextInput::make('app_name')
                            ->label('Nama Pendek Aplikasi')
                            ->required()
                            ->maxLength(255),
                        Forms\Components\TextInput::make('app_full_name')
                            ->label('Nama Penuh Aplikasi')
                            ->maxLength(255),
                        Forms\Components\Textarea::make('app_description')
                            ->label('Penerangan Aplikasi')
                            ->columnSpanFull(),
                        Forms\Components\FileUpload::make('app_logo')
                            ->label('Logo Aplikasi')
                            ->image()
                            ->directory('logos')
                            ->columnSpanFull(),
                    ])
            ])
            ->statePath('data');
    }

    public function save(): void
    {
        $data = $this->form->getState();

        $setting = Setting::firstOrCreate(['id' => 1]);
        $setting->update($data);

        Notification::make()
            ->title('Berjaya disimpan')
            ->success()
            ->send();
    }
}
