<?php
/**
 * Plugin Loader class.
 *
 * @package Hugeicons
 */

namespace Hugeicons;

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

/**
 * Main loader class for the Hugeicons plugin.
 */
class Loader {

    /**
     * Blocks instance.
     *
     * @var Blocks
     */
    private $blocks;

    /**
     * License instance.
     *
     * @var License
     */
    private $license;

    /**
     * Admin instance.
     *
     * @var Admin
     */
    private $admin;

    /**
     * Initialize the plugin components.
     *
     * @return void
     */
    public function init() {
        // Initialize license management.
        $this->license = new License();

        // Initialize admin settings.
        $this->admin = new Admin();
        $this->admin->init();

        // Initialize blocks.
        $this->blocks = new Blocks( $this->license );
        $this->blocks->init();

        // Register REST API endpoints.
        add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) );
    }

    /**
     * Register REST API routes.
     *
     * @return void
     */
    public function register_rest_routes() {
        // Icon search endpoint.
        register_rest_route(
            'hugeicons/v1',
            '/search',
            array(
                'methods'             => 'GET',
                'callback'            => array( $this, 'search_icons' ),
                'permission_callback' => function () {
                    return current_user_can( 'edit_posts' );
                },
                'args'                => array(
                    'q' => array(
                        'required'          => false,
                        'type'              => 'string',
                        'default'           => 'home',
                        'sanitize_callback' => 'sanitize_text_field',
                    ),
                ),
            )
        );

        // License status endpoint.
        register_rest_route(
            'hugeicons/v1',
            '/license/status',
            array(
                'methods'             => 'GET',
                'callback'            => array( $this, 'get_license_status' ),
                'permission_callback' => function () {
                    return current_user_can( 'edit_posts' );
                },
            )
        );

        // License activation endpoint.
        register_rest_route(
            'hugeicons/v1',
            '/license/activate',
            array(
                'methods'             => 'POST',
                'callback'            => array( $this, 'activate_license' ),
                'permission_callback' => function () {
                    return current_user_can( 'manage_options' );
                },
                'args'                => array(
                    'token' => array(
                        'required'          => true,
                        'type'              => 'string',
                        'sanitize_callback' => 'sanitize_text_field',
                    ),
                ),
            )
        );

        // License deactivation endpoint.
        register_rest_route(
            'hugeicons/v1',
            '/license/deactivate',
            array(
                'methods'             => 'POST',
                'callback'            => array( $this, 'deactivate_license' ),
                'permission_callback' => function () {
                    return current_user_can( 'manage_options' );
                },
            )
        );

        // Icon SVG fetch endpoint.
        register_rest_route(
            'hugeicons/v1',
            '/icon/(?P<name>[a-zA-Z0-9-]+)',
            array(
                'methods'             => 'GET',
                'callback'            => array( $this, 'fetch_icon_svg' ),
                'permission_callback' => function () {
                    return current_user_can( 'edit_posts' );
                },
                'args'                => array(
                    'name'  => array(
                        'required'          => true,
                        'type'              => 'string',
                        'sanitize_callback' => 'sanitize_text_field',
                    ),
                    'style' => array(
                        'required'          => false,
                        'type'              => 'string',
                        'default'           => 'stroke-rounded',
                        'sanitize_callback' => 'sanitize_text_field',
                    ),
                ),
            )
        );
    }

    /**
     * Search icons via the Hugeicons API.
     *
     * @param \WP_REST_Request $request The REST request.
     * @return \WP_REST_Response
     */
    public function search_icons( $request ) {
        $query = $request->get_param( 'q' );

        $response = wp_remote_get(
            add_query_arg(
                array(
                    'q'     => $query,
                    'fuzzy' => 'true',
                ),
                HUGEICONS_API_SEARCH_URL
            ),
            array(
                'timeout' => 10,
                'headers' => array(
                    'Accept' => 'application/json',
                ),
            )
        );

        if ( is_wp_error( $response ) ) {
            return new \WP_REST_Response(
                array(
                    'error' => $response->get_error_message(),
                ),
                500
            );
        }

        $body = wp_remote_retrieve_body( $response );
        $data = json_decode( $body, true );

        if ( json_last_error() !== JSON_ERROR_NONE ) {
            return new \WP_REST_Response(
                array(
                    'error' => 'Invalid JSON response from API',
                ),
                500
            );
        }

        return new \WP_REST_Response( $data, 200 );
    }

    /**
     * Get the license status.
     *
     * @param \WP_REST_Request $request The REST request.
     * @return \WP_REST_Response
     */
    public function get_license_status( $request ) {
        return new \WP_REST_Response( $this->license->get_license_status(), 200 );
    }

    /**
     * Activate a license.
     *
     * @param \WP_REST_Request $request The REST request.
     * @return \WP_REST_Response
     */
    public function activate_license( $request ) {
        $token  = $request->get_param( 'token' );
        $result = $this->license->activate_license( $token );

        $status_code = $result['success'] ? 200 : 400;
        return new \WP_REST_Response( $result, $status_code );
    }

    /**
     * Deactivate the license.
     *
     * @param \WP_REST_Request $request The REST request.
     * @return \WP_REST_Response
     */
    public function deactivate_license( $request ) {
        $result = $this->license->deactivate_license();
        return new \WP_REST_Response( $result, 200 );
    }

    /**
     * Fetch icon SVG from the Hugeicons API.
     *
     * @param \WP_REST_Request $request The REST request.
     * @return \WP_REST_Response
     */
    public function fetch_icon_svg( $request ) {
        $icon_name = $request->get_param( 'name' );
        $style     = $request->get_param( 'style' );

        // Get the license key for Bearer auth.
        $license_key = get_option( License::OPTION_LICENSE_KEY, '' );

        if ( empty( $license_key ) ) {
            return new \WP_REST_Response(
                array(
                    'error' => 'No license key found. Please activate your license.',
                ),
                401
            );
        }

        // Fetch SVG from the Hugeicons API.
        $api_url = sprintf(
            'https://api.hugeicons.com/v1/icon/%s/svg?style=%s',
            rawurlencode( $icon_name ),
            rawurlencode( $style )
        );

        $response = wp_remote_get(
            $api_url,
            array(
                'timeout' => 15,
                'headers' => array(
                    'Accept'        => '*/*',
                    'Authorization' => 'Bearer ' . $license_key,
                ),
            )
        );

        if ( is_wp_error( $response ) ) {
            return new \WP_REST_Response(
                array(
                    'error' => $response->get_error_message(),
                ),
                500
            );
        }

        $response_code = wp_remote_retrieve_response_code( $response );
        $body          = wp_remote_retrieve_body( $response );

        if ( 200 !== $response_code ) {
            return new \WP_REST_Response(
                array(
                    'error' => 'Failed to fetch icon: ' . $response_code,
                ),
                $response_code
            );
        }

        // Process SVG to replace hardcoded colors with currentColor for CSS inheritance.
        $svg = $body;
        
        // Replace fixed width/height with 100% for CSS control.
        $svg = preg_replace( '/(<svg[^>]*)\s+width="[^"]*"/', '$1 width="100%"', $svg );
        $svg = preg_replace( '/(<svg[^>]*)\s+height="[^"]*"/', '$1 height="100%"', $svg );
        
        // Replace stroke color values with currentColor.
        $svg = preg_replace( '/stroke="[^"]*"/', 'stroke="currentColor"', $svg );
        
        // Replace fill color values with currentColor, except for "none".
        $svg = preg_replace_callback(
            '/fill="([^"]*)"/',
            function( $matches ) {
                $value = strtolower( $matches[1] );
                if ( 'none' === $value || 'transparent' === $value ) {
                    return $matches[0]; // Keep none/transparent as is.
                }
                return 'fill="currentColor"';
            },
            $svg
        );

        // Return the processed SVG content.
        return new \WP_REST_Response(
            array(
                'svg'   => $svg,
                'name'  => $icon_name,
                'style' => $style,
            ),
            200
        );
    }
}
