<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Models\SmtpSettingsModel;
use App\Services\ActivityLogger;
use App\Services\MailService;

final class SmtpSettingsController extends BaseController
{
    public function show(Request $request): Response
    {
        $model = new SmtpSettingsModel();
        $settings = $model->get();

        if ($settings !== null) {
            unset($settings['password'], $settings['password_encrypted']);
        }

        if ($request->isAjax() || $request->isJson()) {
            return AjaxResponse::success($settings);
        }

        return $this->view('marketing/smtp-settings', [
            'title' => 'SMTP Settings',
            'activeNav' => 'marketing-settings',
            'breadcrumbs' => [['Home', 'dashboard'], ['Marketing', 'campaigns'], ['SMTP Settings', 'settings/smtp']],
            'settings' => $settings,
        ]);
    }

    public function update(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'host' => 'required|string|max:191',
            'port' => 'required|integer',
            'encryption' => 'required|in:tls,ssl,none',
            'username' => 'nullable|string|max:191',
            'password' => 'nullable|string',
            'from_address' => 'required|email|max:191',
            'from_name' => 'required|string|max:191',
        ]);

        (new SmtpSettingsModel())->save($data, $this->currentUserId());
        ActivityLogger::logAction('SMTP settings updated', 'admin');

        return AjaxResponse::success(null, 'SMTP settings saved.');
    }

    public function sendTestEmail(Request $request): Response
    {
        $data = $this->validateOrFail($request, ['test_email' => 'required|email']);

        $user = $this->currentUser();
        $ok = (new MailService())->send(
            $data['test_email'],
            '',
            'A&B Hub — Test Email',
            '<p>This is a test email confirming your SMTP settings are working correctly.</p><p>Sent by ' . e($user['first_name']) . '.</p>'
        );

        return $ok
            ? AjaxResponse::success(null, 'Test email sent successfully.')
            : AjaxResponse::error('Could not send the test email — check storage/logs for the SMTP error, and confirm PHPMailer is installed (composer require phpmailer/phpmailer).', 422);
    }
}
