<?php

/**
 * Font Optimization REST API Controller
 *
 * @package ProRank\SEO\Core\RestApi
 * @since   1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\RestApi;

use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


/**
 * FontOptimizationController class
 */


class FontOptimizationController extends \WP_REST_Controller {
    
    /**
     * Module instance
     *
     * @var \ProRank\SEO\Modules\Performance\FontOptimizationModule|null
     */
    private $module = null;
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->namespace = 'prorank-seo/v1';
        $this->rest_base = 'font-optimization';
    }
    
    /**
     * Register routes
     *
     * @return void
     */
    public function register_routes(): void {
        // Get font statistics
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/stats',
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'get_stats'],
                    'permission_callback' => [$this, 'get_items_permissions_check'],
                ],
            ]
        );
        
        // Download Google Fonts
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/download',
            [
                [
                    'methods'             => WP_REST_Server::CREATABLE,
                    'callback'            => [$this, 'download_fonts'],
                    'permission_callback' => [$this, 'create_item_permissions_check'],
                ],
            ]
        );
    }
    
    /**
     * Get module instance
     *
     * @return \ProRank\SEO\Modules\Performance\FontOptimizationModule|null
     */
    private function get_module() {
        if (null === $this->module) {
            $plugin = \ProRank\SEO\Plugin::get_instance();
            if (!$plugin || !$plugin->is_initialized()) {
                return null;
            }
            
            $module_manager = $plugin->modules();
            if (!$module_manager) {
                return null;
            }
            
            $module = $module_manager->get_module('font_optimization');
            if ($module && $module instanceof \ProRank\SEO\Modules\Performance\FontOptimizationModule) {
                $this->module = $module;
            }
        }
        
        return $this->module;
    }
    
    /**
     * Check permissions for reading
     *
     * @param WP_REST_Request $request Request object
     * @return bool|WP_Error
     */
    public function get_items_permissions_check($request) {
        if (!current_user_can('manage_options')) {
            return new WP_Error(
                'rest_forbidden',
                __('Sorry, you are not allowed to view font optimization data.', 'prorank-seo'),
                ['status' => 403]
            );
        }
        
        return true;
    }
    
    /**
     * Check permissions for creating
     *
     * @param WP_REST_Request $request Request object
     * @return bool|WP_Error
     */
    public function create_item_permissions_check($request) {
        if (!current_user_can('manage_options')) {
            return new WP_Error(
                'rest_forbidden',
                __('Sorry, you are not allowed to manage font optimization.', 'prorank-seo'),
                ['status' => 403]
            );
        }
        
        return true;
    }
    
    /**
     * Get font optimization statistics
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error
     */
    public function get_stats(WP_REST_Request $request) {
        $module = $this->get_module();
        if (!$module) {
            return new WP_Error(
                'module_not_found',
                __('Font optimization module not found.', 'prorank-seo'),
                ['status' => 404]
            );
        }
        
        $stats = $module->get_stats();
        
        return rest_ensure_response([
            'success' => true,
            'stats' => $stats,
        ]);
    }
    
    /**
     * Download Google Fonts
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error
     */
    public function download_fonts(WP_REST_Request $request) {
        $module = $this->get_module();
        if (!$module) {
            return new WP_Error(
                'module_not_found',
                __('Font optimization module not found.', 'prorank-seo'),
                ['status' => 404]
            );
        }
        
        if (!$module->is_enabled()) {
            return new WP_Error(
                'module_disabled',
                __('Font optimization module is disabled.', 'prorank-seo'),
                ['status' => 400]
            );
        }
        
        // Trigger AJAX handler
        $_REQUEST['nonce'] = wp_create_nonce('prorank_font_optimization');
        $module->handle_font_download();
        
        // WordPress will handle the response
        die();
    }
}
