<?php
/**
 * Email Settings Controller V1
 *
 * @package ZenoChatbot\Http\Controller\Api\V1
 */

namespace ZenoChatbot\Http\Controller\Api\V1;

use ZenoChatbot\Framework\Exceptions\HttpException;
use ZenoChatbot\Framework\Http\Request;
use ZenoChatbot\Helper\Settings;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Email Settings API Controller
 */
class EmailSettingsController
{
    /**
     * Get email settings
     *
     * @return array
     */
    public function get()
    {
        return [
            'success' => true,
            'settings' => Settings::getEmailSettings()
        ];
    }

    /**
     * Update email settings
     *
     * @param Request $request
     * @return array
     */
    public function update(Request $request)
    {
        $data = $request->getSafe([
            'from_name'     => 'sanitize_text_field',
            'from_email'    => 'sanitize_email',
            'reply_to'      => 'sanitize_email',
            'reply_to_name' => 'sanitize_text_field',
        ]);

        // Reject invalid input with a real 4xx instead of silently saving a blank
        // sender, which would produce a malformed "From: Name <>" header.
        $errors = [];
        if ($data['from_email'] === '' || !is_email($data['from_email'])) {
            $errors['from_email'] = [__('Please enter a valid From Email address.', 'zeno-chatbot-ai')];
        }
        if ($data['reply_to'] !== '' && !is_email($data['reply_to'])) {
            $errors['reply_to'] = [__('Reply-To must be a valid email address.', 'zeno-chatbot-ai')];
        }

        if (!empty($errors)) {
            throw new HttpException(
                422,
                esc_html__('Invalid email settings.', 'zeno-chatbot-ai'),
                ['errors' => $errors] // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- structured payload of translated strings rendered as a JSON REST error by the exception handler, never echoed as HTML
            );
        }

        Settings::updateEmailSettings($data);

        return [
            'success' => true,
            'message' => 'Email settings updated successfully',
            'data' => Settings::getEmailSettings()
        ];
    }
}
