<?php

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\MailTemplate;
use App\Models\Setting;
use App\Services\Mailer;

class MailController extends Controller
{
    /**
     * GET /admin/settings/mail
     * Show mail settings + template list (tabbed view).
     */
    public function index(Request $request, array $params = []): void
    {
        $mailConfig = mail_config();
        $templates  = MailTemplate::all('slug', 'ASC');

        $view = $this->app->service('view');
        $html = $view->renderAdmin('mail/index', [
            'pageTitle'  => __('admin.mail.title'),
            'mailConfig' => $mailConfig,
            'templates'  => $templates,
            'auth'       => $this->auth(),
            'csrf'       => $this->csrf(),
            'activeTab'  => $request->input('tab', 'settings'),
        ]);
        Response::html($html);
    }

    /**
     * POST /admin/settings/mail/save
     * Save mail transport + sender + SMTP settings.
     */
    public function save(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $fields = [
            'mail_transport'       => ['key' => 'transport',       'allowed' => ['mail', 'smtp']],
            'mail_from_address'    => ['key' => 'from_address'],
            'mail_from_name'       => ['key' => 'from_name'],
            'mail_reply_to'        => ['key' => 'reply_to'],
            'mail_smtp_host'       => ['key' => 'smtp_host'],
            'mail_smtp_port'       => ['key' => 'smtp_port'],
            'mail_smtp_username'   => ['key' => 'smtp_username'],
            'mail_smtp_password'   => ['key' => 'smtp_password'],
            'mail_smtp_encryption' => ['key' => 'smtp_encryption', 'allowed' => ['tls', 'ssl', 'none']],
        ];

        foreach ($fields as $settingKey => $meta) {
            $value = trim($request->input($meta['key'], ''));

            // Whitelist validation
            if (isset($meta['allowed']) && !in_array($value, $meta['allowed'], true)) {
                $value = $meta['allowed'][0];
            }

            Setting::set($settingKey, $value, 'mail');
        }

        set_flash('success', __('admin.mail.settings_saved'));
        Response::redirect('/admin/settings/mail');
    }

    /**
     * POST /admin/settings/mail/test
     * Send a test e-mail to the logged-in admin's address.
     */
    public function test(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $auth      = $this->auth();
        $userId    = $auth->userId();
        $user      = $userId ? \App\Models\User::find($userId) : null;
        $recipient = $user['email'] ?? '';

        if (empty($recipient) || !filter_var($recipient, FILTER_VALIDATE_EMAIL)) {
            Response::json(['ok' => false, 'error' => __('messages.invalid_email')]);
            return;
        }

        $mailConfig = mail_config();
        $mailer     = new Mailer($mailConfig);

        $siteName = setting('site_name', 'ITSWEBER CMS');
        $subject  = __('admin.mail.test_mail_subject');
        $htmlBody = '<div style="font-family:Arial,Helvetica,sans-serif;max-width:600px;margin:0 auto;background:#ffffff;">'
            . '<div style="background:linear-gradient(135deg,#0d2d3a 0%,#15779b 100%);padding:24px 32px;text-align:center;">'
            . '<h1 style="color:#ffffff;font-size:20px;margin:0;font-weight:700;">' . e($siteName) . '</h1>'
            . '</div>'
            . '<div style="padding:32px;">'
            . '<p style="color:#334155;font-size:15px;line-height:1.6;margin:0 0 16px;">' . e(__('admin.mail.test_mail_body')) . '</p>'
            . '<p style="color:#64748b;font-size:13px;line-height:1.5;margin:0;">Transport: <strong>' . e($mailConfig['transport'] ?? 'mail') . '</strong></p>'
            . '</div>'
            . '<div style="border-top:1px solid #e2e8f0;padding:20px 32px;text-align:center;">'
            . '<p style="color:#94a3b8;font-size:12px;margin:0;">' . e($siteName) . '</p>'
            . '</div></div>';

        $ok = $mailer->sendHtml($recipient, $subject, $htmlBody);

        Response::json([
            'ok'      => $ok,
            'message' => $ok ? __('admin.mail.test_success') : __('admin.mail.test_error'),
        ]);
    }

    /**
     * GET /admin/settings/mail/template/{id}
     * Show the template editor for a specific template.
     */
    public function templateEdit(Request $request, array $params = []): void
    {
        $id       = (int) ($params['id'] ?? 0);
        $template = MailTemplate::find($id);

        if (!$template) {
            set_flash('error', __('messages.not_found', ['item' => 'Template']));
            Response::redirect('/admin/settings/mail?tab=templates');
            return;
        }

        // Determine available variables for this template
        $variables = $this->getTemplateVariables($template['slug']);

        $view = $this->app->service('view');
        $html = $view->renderAdmin('mail/template_edit', [
            'pageTitle' => __('admin.mail.title') . ' – ' . e($template['name']),
            'template'  => $template,
            'variables' => $variables,
            'auth'      => $this->auth(),
            'csrf'      => $this->csrf(),
        ]);
        Response::html($html);
    }

    /**
     * POST /admin/settings/mail/template/{id}/save
     * Save a template's subject and HTML body.
     */
    public function templateSave(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $id       = (int) ($params['id'] ?? 0);
        $template = MailTemplate::find($id);

        if (!$template) {
            set_flash('error', __('messages.not_found', ['item' => 'Template']));
            Response::redirect('/admin/settings/mail?tab=templates');
            return;
        }

        $subject  = trim($request->input('subject', ''));
        $htmlBody = $request->input('html_body', '');

        if ($subject === '' || $htmlBody === '') {
            set_flash('error', __('messages.all_required'));
            Response::redirect('/admin/settings/mail/template/' . $id);
            return;
        }

        MailTemplate::updateById($id, [
            'subject'   => $subject,
            'html_body' => $htmlBody,
        ]);

        set_flash('success', __('admin.mail.template_saved'));
        Response::redirect('/admin/settings/mail/template/' . $id);
    }

    /**
     * Get the available template variables for a given template slug.
     */
    private function getTemplateVariables(string $slug): array
    {
        $common = [
            'site_name'   => __('admin.mail.var_site_name'),
            'logo_header' => __('admin.mail.var_logo_header'),
        ];

        return match ($slug) {
            'password_reset' => array_merge($common, [
                'username'          => __('admin.mail.var_username'),
                'reset_url'         => __('admin.mail.var_reset_url'),
                'token_ttl_minutes' => __('admin.mail.var_token_ttl_minutes'),
            ]),
            'contact_form' => array_merge($common, [
                'contact_name'  => __('admin.mail.var_contact_name'),
                'contact_email' => __('admin.mail.var_contact_email'),
                'subject'       => __('admin.mail.var_subject'),
                'message'       => __('admin.mail.var_message'),
            ]),
            default => $common,
        };
    }
}
