<?php
/**
 * AI Settings API
 *
 * Handles AI-related settings endpoints.
 *
 * @package FleekDash\API
 */

namespace FleekDash\API;

use FleekDash\Core\AuthMiddleware;

defined('ABSPATH') || exit;

// Load debug helpers
if (!function_exists('fleekdash_log_debug')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

class AISettingsAPI
{
    /**
     * Register REST API routes
     */
    public function registerRoutes()
    {
        // Get AI uninstall setting
        \register_rest_route('fleekdash/v1', '/ai/uninstall-setting', [
            'methods' => 'GET',
            'callback' => [$this, 'getUninstallSetting'],
            'permission_callback' => [$this, 'checkPermissions'],
        ]);

        // Update AI uninstall setting
        \register_rest_route('fleekdash/v1', '/ai/uninstall-setting', [
            'methods' => 'POST',
            'callback' => [$this, 'updateUninstallSetting'],
            'permission_callback' => [$this, 'checkPermissions'],
        ]);
    }

    /**
     * Check permissions - always return true, let AuthMiddleware handle auth
     *
     * @return bool Always returns true for graceful fallback
     */
    public function checkPermissions()
    {
        // Always return true - let AuthMiddleware handle auth
        return true;
    }

    /**
     * Get AI uninstall setting
     *
     * @return \WP_REST_Response
     */
    public function getUninstallSetting()
    {
        try {
            $auth_check = AuthMiddleware::check('admin');
            if (!$auth_check['authenticated']) {
                // Graceful fallback: default payload when not authenticated
                return \rest_ensure_response([
                    'success' => false,
                    'message' => 'Not authenticated',
                    'value' => false, // Default value
                ]);
            }
        } catch (\Exception $e) {
            // Graceful fallback on middleware error
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('FleekDash AI Settings API: AuthMiddleware error - ' . $e->getMessage());
            }
            return \rest_ensure_response([
                'success' => false,
                'message' => 'Authentication error',
                'value' => false, // Default value
            ]);
        }

        $value = \get_option('fleekdash_ai_delete_drafts_on_uninstall', false);

        return \rest_ensure_response([
            'success' => true,
            'value' => (bool) $value,
        ]);
    }

    /**
     * Update AI uninstall setting
     *
     * @param \WP_REST_Request $request
     * @return \WP_REST_Response
     */
    public function updateUninstallSetting(\WP_REST_Request $request)
    {
        $responsePayload = null;

        try {
            $auth_check = AuthMiddleware::check('admin');
            if (!$auth_check['authenticated']) {
                // Graceful fallback: structured response instead of hard failure
                $responsePayload = [
                    'success' => false,
                    'message' => 'Not authenticated',
                    'value' => false, // Return current value as fallback
                ];
            }
        } catch (\Exception $e) {
            // Graceful fallback on middleware error
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('FleekDash AI Settings API: AuthMiddleware error - ' . $e->getMessage());
            }
            $responsePayload = [
                'success' => false,
                'message' => 'Authentication error',
                'value' => false, // Return current value as fallback
            ];
        }

        if ($responsePayload === null) {
            $params = $request->get_json_params();
            $value = isset($params['value']) ? (bool) $params['value'] : false;

            $result = \update_option('fleekdash_ai_delete_drafts_on_uninstall', $value);

            // Graceful fallback - even if update fails, return response (not WP_Error)
            if (!$result) {
                // Get current value as fallback
                $current_value = \get_option('fleekdash_ai_delete_drafts_on_uninstall', false);
                $responsePayload = [
                    'success' => false,
                    'message' => 'Failed to update setting',
                    'value' => (bool) $current_value, // Return current value
                ];
            } else {
                $responsePayload = [
                    'success' => true,
                    'value' => $value,
                ];
            }
        }

        return \rest_ensure_response($responsePayload);
    }
}

// Register routes on REST API init
\add_action('rest_api_init', function () {
    $api = new AISettingsAPI();
    $api->registerRoutes();
});
