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

namespace ZenoChatbot\Http\Controller\Api\V1;

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

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

/**
 * Chat Settings API Controller
 */
class ChatSettingsController
{
    /**
     * Get chat settings
     *
     * @return array
     */
    public function get()
    {
        return [
            'success' => true,
            'data' => Settings::getChatSettings()
        ];
    }

    /**
     * Update chat settings
     *
     * @param Request $request
     * @return array
     */
    public function update(Request $request)
    {
        // Sanitizers are derived from the single canonical schema in Settings so
        // the field list cannot drift between save, defaults, and the widget.
        $sanitizers = array_map(
            static function ($field) {
                return $field[1];
            },
            Settings::chatSettingsSchema()
        );

        $data = [];
        foreach ($sanitizers as $field => $sanitizer) {
            if (!$request->has($field)) {
                continue;
            }

            $value = $request->input($field);
            if (is_string($sanitizer) && function_exists($sanitizer)) {
                $data[$field] = call_user_func($sanitizer, $value);
            } else {
                $data[$field] = sanitize_text_field($value);
            }
        }

        $toggleFields = [
            'floating_widget_enabled',
            'online_indicator',
            'auto_open',
            'auto_close_enabled',
            'auto_summary_enabled',
        ];

        foreach ($toggleFields as $field) {
            if (!array_key_exists($field, $data)) {
                continue;
            }

            $data[$field] = $data[$field] === 'yes' ? 'yes' : 'no';
        }

        if (array_key_exists('auto_close_after_hours', $data)) {
            $hours = (int) $data['auto_close_after_hours'];
            if ($hours < 1) {
                $hours = 1;
            }
            if ($hours > 720) {
                $hours = 720;
            }
            $data['auto_close_after_hours'] = $hours;
        }

        Settings::updateChatSettings($data);

        return [
            'success' => true,
            'message' => __('Chat settings updated successfully', 'zeno-chatbot-ai'),
            'data' => Settings::getChatSettings()
        ];
    }
}
