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

namespace ZenoChatbot\Http\Controller\Api\V1;

use ZenoChatbot\App;
use ZenoChatbot\Framework\Exceptions\HttpException;
use ZenoChatbot\Framework\Http\Request;
use ZenoChatbot\Framework\Validation\Validator;
use ZenoChatbot\Helper\Settings;
use ZenoChatbot\Support\Hooks;

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

/**
 * General Settings API Controller
 *
 * Handles general chatbot settings including system prompts
 * and error response messages.
 */
class GeneralSettingsController
{
    /**
     * Get general settings
     *
     * @return array
     */
    public function get()
    {
        try {
            // Get current settings or use defaults
            $systemPrompts = Settings::get('general.system_prompts', $this->getDefaultSystemPrompts());
            $onErrorResponse = Settings::get('general.on_error_response', $this->getDefaultErrorResponse());
            $language = Settings::get('general.language', 'en-US');

            $settings = [
                'system_prompts' => $systemPrompts,
                'on_error_response' => $onErrorResponse,
                'language' => $language,
                // Empty when unset; the prompt builder applies its own defaults at read time.
                'business_domain' => Settings::get('general.business_domain', ''),
                'contact_info' => Settings::get('general.contact_info', ''),
            ];

            $extensions = Hooks::applyFilters(Hooks::SETTINGS_GENERAL_DATA, []);

            return [
                'success' => true,
                'data' => $settings,
                'extensions' => $extensions,
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Failed to retrieve general settings',
                'error' => $e->getMessage(),
                'status' => 500
            ];
        }
    }

    /**
     * Update general settings
     *
     * @param Request $request
     * @return array
     */
    public function update(Request $request)
    {
        $countries = App::config('countries', []);
        $countries = Hooks::applyFilters(Hooks::SETTINGS_COUNTRIES, $countries);

        // Extract language_code values (e.g., 'en-US', 'fr-FR')
        $availableLanguages = array_map(function ($country) {
            return $country['language_code'];
        }, $countries);

        $availableLanguages = implode(',', $availableLanguages);

        $validator = Validator::make(
            $request->only(['system_prompts', 'on_error_response', 'language', 'business_domain', 'contact_info']),
            [
                'system_prompts'    => 'nullable|string|max:5000',
                'on_error_response' => 'nullable|string|max:1000',
                'language'          => 'nullable|string|in:' . $availableLanguages,
                'business_domain'   => 'nullable|string|max:200',
                'contact_info'      => 'nullable|string|max:200',
            ]
        );

        // Surface validation failures as a real 4xx instead of silently
        // dropping the offending field and returning 200.
        if ($validator->fails()) {
            throw new HttpException(
                422,
                esc_html__('Invalid general settings.', 'zeno-chatbot-ai'),
                ['errors' => $validator->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
            );
        }

        $data = $validator->validated();

        // Multi-line fields must keep their line breaks; sanitize_text_field()
        // would collapse newlines, so use the textarea sanitizer for those.
        $textareaFields = ['system_prompts', 'on_error_response'];
        foreach ($data as $field => $value) {
            $data[$field] = in_array($field, $textareaFields, true)
                ? sanitize_textarea_field($value)
                : sanitize_text_field($value);
        }

        Settings::update('general', $data);

        $extensionData = $request->get('extensions', []);
        if (is_array($extensionData)) {
            Hooks::doAction(Hooks::SETTINGS_GENERAL_SAVE, $extensionData);
        }

        return [
            'success' => true,
            'message' => 'General settings updated successfully'
        ];
    }

    /**
     * Get default system prompts
     *
     * @return string
     */
    private function getDefaultSystemPrompts()
    {
        return 'You are a helpful AI assistant. Provide accurate, professional, and friendly responses based on the available context. Be concise and clear in your explanations.';
    }

    /**
     * Get default error response
     *
     * @return string
     */
    private function getDefaultErrorResponse()
    {
        return 'I apologize, but I encountered an issue processing your request. Please try again or contact our support team if the problem persists.';
    }
}
