<?php

namespace App\Filament\Pages;

use Filament\Forms;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Illuminate\Support\Facades\Crypt;
use PragmaRX\Google2FA\Google2FA;

class TwoFactorSetup extends Page
{
    protected static ?string $navigationIcon = 'heroicon-o-shield-check';
    protected static ?string $navigationLabel = '2FA';
    protected static ?string $title = 'Autentificare în doi pași';
    protected static ?string $navigationGroup = 'Cont';
    protected static ?int $navigationSort = 90;
    protected static string $view = 'filament.pages.two-factor-setup';

    public bool $enabled = false;
    public ?string $qrCodeUrl = null;
    public ?string $secret = null;
    public ?string $code = '';

    public function mount(): void
    {
        $user = auth()->user();
        $this->enabled = $user->two_factor_enabled ?? false;
    }

    public function generateSecret(): void
    {
        $google2fa = new Google2FA();
        $this->secret = $google2fa->generateSecretKey();

        $user = auth()->user();
        $this->qrCodeUrl = $google2fa->getQRCodeUrl(
            config('app.name', 'Catalog Scolar'),
            $user->email,
            $this->secret
        );
    }

    public function enable(): void
    {
        if (empty($this->code) || empty($this->secret)) {
            Notification::make()->title('Introdu codul din aplicație')->danger()->send();
            return;
        }

        $google2fa = new Google2FA();

        if (!$google2fa->verifyKey($this->secret, $this->code)) {
            Notification::make()->title('Cod invalid. Încearcă din nou.')->danger()->send();
            return;
        }

        $user = auth()->user();
        $user->update([
            'two_factor_enabled' => true,
            'two_factor_secret' => Crypt::encryptString($this->secret),
            'two_factor_confirmed_at' => now(),
        ]);

        $this->enabled = true;
        $this->qrCodeUrl = null;
        $this->secret = null;
        $this->code = '';

        session(['2fa_verified' => true]);

        Notification::make()->title('2FA activat cu succes!')->success()->send();
    }

    public function disable(): void
    {
        $user = auth()->user();
        $user->update([
            'two_factor_enabled' => false,
            'two_factor_secret' => null,
            'two_factor_confirmed_at' => null,
        ]);

        $this->enabled = false;
        session()->forget('2fa_verified');

        Notification::make()->title('2FA dezactivat')->success()->send();
    }
}
