<?php

namespace App\Filament\Pages;

use Filament\Actions\MountableAction;
use Filament\Pages\Page;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\ColorPicker;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Form;
use App\Models\Setting;
use Filament\Actions;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\File;



class SettingPage extends Page implements HasForms
{
    use InteractsWithForms;
    public $logo;
    public $description;
    public $primary_color;
    public $secondary_color;

    protected static ?string $navigationIcon = 'heroicon-o-document-text';
    protected static string $view = 'filament.pages.settings';
    protected static ?string $title = 'Configuraciones del Sistema';
    protected static ?string $navigationGroup = 'Administración'; // 

    protected static ?string $navigationLabel = 'Ajustes';


    public ?array $data = [];

    public function mount()
    {
        // Obtener la configuración existente o valores predeterminados
        $setting = Setting::first();

        $this->form->fill($setting?->toArray() ?? [
            'logo' => null,
            'description' => null,
            'primary_color' => '#3498db',
            'secondary_color' => '#2ecc71',
        ]);
    }

    protected function getFormSchema(): array
    {
        return [
            FileUpload::make('logo')
                ->image()
                ->label('Logo')
                ->directory('settings/logos')
                ->required(),

            Textarea::make('description')
                ->label('Descripción')
                ->maxLength(500)
                ->required(),

            ColorPicker::make('primary_color')
                ->label('Color Primario')
                ->required(),

            ColorPicker::make('secondary_color')
                ->label('Color Secundario')
                ->required(),
        ];
    }

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

        Setting::updateOrCreate(['id' => 1], $data);

        // Enviar notificación de éxito
        Notification::make()
            ->title('Éxito')
            ->body('Configuraciones guardadas exitosamente.')
            ->success()
            ->send();

        //$this->notify('success', 'Configuraciones guardadas exitosamente.');
    }

    protected function makeForm(): Form
    {
        return Form::make($this)
            ->schema($this->getFormSchema())
            ->statePath('data');
    }


    protected function getHeaderActions(): array
    {
        return [
            Actions\Action::make('Cerrar todas las sesiones')
                ->color('danger')
                ->requiresConfirmation()
                ->action(function () {
                    if (config('session.driver') === 'file') {
                        // Eliminar todos los archivos de sesión
                        $files = File::files(storage_path('framework/sessions'));
                        foreach ($files as $file) {
                            File::delete($file);
                        }
                    } elseif (config('session.driver') === 'database') {
                        DB::table('sessions')->truncate();
                    }
                    // Limpia tu propia sesión para desconectarte también
                    Session::flush();
                    
            
    
                    Notification::make()
                        ->title('Sesiones cerradas')
                        ->body('Todas las sesiones han sido cerradas exitosamente.')
                        ->success()
                        ->send();
                }),
        ];
    }
    

}
