<?php
/**
 * Admin Bar Settings API
 *
 * Handles admin bar styling settings endpoints.
 *
 * @package FleekDash\API
 */

namespace FleekDash\API;

use FleekDash\Core\AuthMiddleware;

defined('ABSPATH') || exit;

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

        // Update admin bar settings
        \register_rest_route('fleekdash/v1', '/settings/admin-bar', [
            '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 admin bar settings
     *
     * @param \WP_REST_Request $request
     * @return \WP_REST_Response
     */
    public function get_settings($request)
    {
        try {
            $auth_check = AuthMiddleware::check('authenticated');
            if (!$auth_check['authenticated']) {
                // Graceful fallback - return default values
                return \rest_ensure_response([
                    'success' => false,
                    'message' => 'Not authenticated',
                    'data' => [
                        'style' => 'modern',
                        'positionAtBottom' => false,
                        'themeColor' => 'auto',
                    ],
                ]);
            }
        } catch (\Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('FleekDash Admin Bar Settings API: AuthMiddleware error - ' . $e->getMessage());
            }
            return \rest_ensure_response([
                'success' => false,
                'message' => 'Authentication error',
                'data' => [
                    'style' => 'modern',
                    'positionAtBottom' => false,
                    'themeColor' => 'auto',
                ],
            ]);
        }

    $style = \get_option('fleekdash_admin_bar_style', 'modern');
    $position_at_bottom = (bool) \get_option('fleekdash_admin_bar_position_bottom', false);
    $theme_color = \get_option('fleekdash_admin_bar_theme_color', 'auto');

    // Validate values
    if (!in_array($style, ['classic', 'modern', 'fleek'], true)) {
        $style = 'modern';
    }
    if (!in_array($theme_color, ['auto', 'light', 'dark'], true)) {
        $theme_color = 'auto';
    }

    return \rest_ensure_response([
        'success' => true,
        'data' => [
            'style' => $style,
            'positionAtBottom' => $position_at_bottom,
            'themeColor' => $theme_color,
        ],
    ]);
}

    /**
     * Update admin bar settings
     *
     * @param \WP_REST_Request $request
     * @return \WP_REST_Response
     */
    public function update_settings($request)
    {
        try {
            $auth_check = AuthMiddleware::check('authenticated');
            if (!$auth_check['authenticated']) {
                // Graceful fallback - return error without blocking
                return \rest_ensure_response([
                    'success' => false,
                    'message' => 'Not authenticated',
                ]);
            }
        } catch (\Exception $e) {
            // Graceful fallback on error
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('FleekDash Admin Bar Settings API: AuthMiddleware error - ' . $e->getMessage());
            }
            return \rest_ensure_response([
                'success' => false,
                'message' => 'Authentication error',
            ]);
        }

        $params = $request->get_json_params();

        $style = isset($params['style']) ? \sanitize_text_field($params['style']) : 'modern';
        $position_at_bottom = isset($params['positionAtBottom']) ? (bool) $params['positionAtBottom'] : false;
        $theme_color = isset($params['themeColor']) ? \sanitize_text_field($params['themeColor']) : 'auto';

        // Validate values
        if (!in_array($style, ['classic', 'modern', 'fleek'], true)) {
            $style = 'modern';
        }
        if (!in_array($theme_color, ['auto', 'light', 'dark'], true)) {
            $theme_color = 'auto';
        }

        // Save settings
        \update_option('fleekdash_admin_bar_style', $style);
        \update_option('fleekdash_admin_bar_position_bottom', $position_at_bottom);
        \update_option('fleekdash_admin_bar_theme_color', $theme_color);

        $saved_style = \get_option('fleekdash_admin_bar_style', 'modern');
        $saved_position = (bool) \get_option('fleekdash_admin_bar_position_bottom', false);
        $saved_theme_color = \get_option('fleekdash_admin_bar_theme_color', 'auto');

        if ($saved_style !== $style || $saved_position !== $position_at_bottom || $saved_theme_color !== $theme_color) {
            return \rest_ensure_response([
                'success' => false,
                'message' => 'Failed to update settings',
                'error' => 'Settings were not saved correctly',
                'data' => [
                    'style' => $saved_style,
                    'positionAtBottom' => $saved_position,
                    'themeColor' => $saved_theme_color,
                ],
            ]);
        }

        return \rest_ensure_response([
            'success' => true,
            'data' => [
                'style' => $style,
                'positionAtBottom' => $position_at_bottom,
                'themeColor' => $theme_color,
            ],
        ]);
    }
}

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