<?php
/**
 * Fleek Docs Settings API
 *
 * Handles Fleek Docs feature settings endpoints.
 * Controls the registration of the fleekdash_document CPT.
 *
 * @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 FleekDocsSettingsAPI
{
    /**
     * Option name for Fleek Docs enabled setting
     */
    const OPTION_ENABLED = 'fleekdash_fleek_docs_enabled';

    /**
     * Register REST API routes
     */
    public function register_routes()
    {
        // Get Fleek Docs settings
        \register_rest_route('fleekdash/v1', '/fleek-docs/settings', [
            'methods' => 'GET',
            'callback' => [$this, 'get_settings'],
            'permission_callback' => [$this, 'check_permissions'],
        ]);

        // Update Fleek Docs settings
        \register_rest_route('fleekdash/v1', '/fleek-docs/settings', [
            'methods' => 'POST',
            'callback' => [$this, 'update_settings'],
            'permission_callback' => [$this, 'check_permissions'],
        ]);
    }

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

    /**
     * Get Fleek Docs settings
     *
     * @param \WP_REST_Request $request
     * @return \WP_REST_Response
     */
    public function get_settings($request)
    {
        try {
            $auth_check = AuthMiddleware::check('admin');
            if (!$auth_check['authenticated']) {
                return \rest_ensure_response([
                    'success' => false,
                    'message' => 'Not authenticated',
                    'data' => self::get_default_settings(),
                ]);
            }
        } catch (\Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('FleekDash Fleek Docs API: AuthMiddleware error - ' . $e->getMessage());
            }
            return \rest_ensure_response([
                'success' => false,
                'message' => 'Authentication error',
                'data' => self::get_default_settings(),
            ]);
        }

        return \rest_ensure_response([
            'success' => true,
            'data' => self::get_current_settings(),
        ]);
    }

    /**
     * Update Fleek Docs settings
     *
     * @param \WP_REST_Request $request
     * @return \WP_REST_Response
     */
    public function update_settings($request)
    {
        try {
            $auth_check = AuthMiddleware::check('admin');
            if (!$auth_check['authenticated']) {
                return \rest_ensure_response([
                    'success' => false,
                    'message' => 'Not authenticated',
                    'data' => self::get_current_settings(),
                ]);
            }
        } catch (\Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('FleekDash Fleek Docs API: AuthMiddleware error - ' . $e->getMessage());
            }
            return \rest_ensure_response([
                'success' => false,
                'message' => 'Authentication error',
                'data' => self::get_current_settings(),
            ]);
        }

        $params = $request->get_json_params();
        $enabled = isset($params['enabled']) ? (bool) $params['enabled'] : false;

        // Update the setting
        $result = \update_option(self::OPTION_ENABLED, $enabled);

        // If enabling, flush rewrite rules to register the CPT
        if ($enabled) {
            // The CPT will be registered on next page load via PostTypeManager
            // We need to flush rewrite rules after CPT registration
            \update_option('fleekdash_flush_rewrite_rules', true);

            // Invalidate menu cache so new CPT appears in menu on next load
            \FleekDash\Admin\MenuChangeNotifier::invalidateMenuAndToolbarSnapshots();
            \update_option('fleekdash_invalidate_frontend_cache', time(), false);
        }

        // Graceful fallback
        if (!$result) {
            $current_settings = self::get_current_settings();
            // Check if value is already the same (update_option returns false if no change)
            if ($current_settings['enabled'] === $enabled) {
                return \rest_ensure_response([
                    'success' => true,
                    'data' => $current_settings,
                ]);
            }
            return \rest_ensure_response([
                'success' => false,
                'message' => 'Failed to update setting',
                'data' => $current_settings,
            ]);
        }

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

    /**
     * Get default settings
     *
     * @return array
     */
    public static function get_default_settings(): array
    {
        return [
            'enabled' => false,
        ];
    }

    /**
     * Get current settings from database
     *
     * @return array
     */
    public static function get_current_settings(): array
    {
        return [
            'enabled' => (bool) \get_option(self::OPTION_ENABLED, false),
        ];
    }

    /**
     * Check if Fleek Docs feature is enabled
     *
     * @return bool
     */
    public static function is_enabled(): bool
    {
        return (bool) \get_option(self::OPTION_ENABLED, false);
    }
}

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