<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Session;
use App\Services\MailService;
use App\Services\SmtpConfigurationService;
use Throwable;

final class ParametreMailController extends Controller
{
    public function index(): void
    {
        $service = new SmtpConfigurationService();

        $this->view('parametres/smtp', [
            'title' => 'Configuration e-mail / SMTP',
            'settings' => $service->getForForm(),
            'errors' => [],
            'phpMailerAvailable' => class_exists(\PHPMailer\PHPMailer\PHPMailer::class),
        ]);
    }

    public function save(): void
    {
        $service = new SmtpConfigurationService();
        $data = Request::all();

        try {
            $service->save($data);
            Session::flash('success', 'Configuration SMTP enregistrée.');
            $this->redirect('parametres_mail');
        } catch (Throwable $exception) {
            $this->view('parametres/smtp', [
                'title' => 'Configuration e-mail / SMTP',
                'settings' => array_replace($service->getForForm(), $data),
                'errors' => ['general' => $exception->getMessage()],
                'phpMailerAvailable' => class_exists(\PHPMailer\PHPMailer\PHPMailer::class),
            ]);
        }
    }

    public function test(): void
    {
        try {
            (new MailService())->sendTest(
                trim((string)Request::post('test_email', '')) ?: null
            );
            Session::flash('success', 'E-mail de test envoyé avec succès.');
        } catch (Throwable $exception) {
            Session::flash('error', 'Test SMTP impossible : ' . $exception->getMessage());
        }

        $this->redirect('parametres_mail');
    }
}
