<?php

/**
 * Dynamic Variables REST API Controller
 *
 * @package ProRank\SEO\Core\RestApi
 * @since   1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\RestApi;

use ProRank\SEO\Core\DynamicVariables;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

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


/**
 * DynamicVariablesController class
 */


class DynamicVariablesController extends BaseController {
    
    /**
     * Dynamic variables parser
     *
     * @var DynamicVariables
     */
    private DynamicVariables $dynamic_variables;
    
    /**
     * Constructor
     */
    public function __construct() {
        parent::__construct();
        $this->namespace = 'prorank-seo/v1';
        $this->rest_base = 'dynamic-variables';
        
        $this->dynamic_variables = new DynamicVariables();
    }
    
    /**
     * Register routes
     *
     * @return void
     */
    public function register_routes(): void {
        // Preview endpoint
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/preview',
            [
                [
                    'methods'             => WP_REST_Server::CREATABLE,
                    'callback'            => [$this, 'preview_variables'],
                    'permission_callback' => [$this, 'check_permission'],
                    'args'                => $this->get_preview_args(),
                ],
            ]
        );
        
        // List available variables
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/list',
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'list_variables'],
                    'permission_callback' => [$this, 'check_permission'],
                    'args'                => [
                        'context' => [
                            'type'        => 'string',
                            'default'     => 'post',
                            'enum'        => ['post', 'page', 'term', 'archive', 'product', 'all'],
                            'description' => __('Context for variables', 'prorank-seo'),
                        ],
                    ],
                ],
            ]
        );
    }
    
    /**
     * Preview dynamic variables
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function preview_variables(WP_REST_Request $request) {
        
        // Sanitize inputs
        $string = sanitize_text_field($request->get_param('string'));
        $context_id = absint($request->get_param('context_id'));
        $context_type = sanitize_key($request->get_param('context_type'));
        
        // Get context object
        $context_object = null;
        
        switch ($context_type) {
            case 'post':
            case 'page':
            case 'product':
                if ($context_id) {
                    $context_object = get_post($context_id);
                }
                break;
                
            case 'term':
            case 'category':
            case 'tag':
                if ($context_id) {
                    $taxonomy = sanitize_key($request->get_param('taxonomy'));
                    if ($taxonomy) {
                        $context_object = get_term($context_id, $taxonomy);
                    }
                }
                break;
        }
        
        // Parse the string
        $parsed = $this->dynamic_variables->parse($string, $context_object, $context_type);
        
        return rest_ensure_response([
            'success' => true,
            'data' => [
                'original' => $string,
                'parsed' => $parsed,
                'context' => [
                    'type' => $context_type,
                    'id' => $context_id,
                ],
            ],
        ]);
    }
    
    /**
     * List available variables
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function list_variables(WP_REST_Request $request) {
        
        // Sanitize context parameter
        $context = sanitize_key($request->get_param('context'));
        $variables = DynamicVariables::get_available_variables($context);
        
        // Format for frontend
        $formatted = [];
        
        // Add common variables
        foreach ($variables['common'] as $var => $label) {
            $formatted[] = [
                'value' => $var,
                'label' => $label,
                'category' => __('Common', 'prorank-seo'),
            ];
        }
        
        // Add context-specific variables
        if ($context === 'all') {
            // Add all variables
            $categories = [
                'post' => __('Post', 'prorank-seo'),
                'term' => __('Term', 'prorank-seo'),
                'archive' => __('Archive', 'prorank-seo'),
                'product' => __('Product', 'prorank-seo'),
            ];
            
            foreach ($categories as $cat_key => $cat_label) {
                if (isset($variables[$cat_key])) {
                    foreach ($variables[$cat_key] as $var => $label) {
                        $formatted[] = [
                            'value' => $var,
                            'label' => $label,
                            'category' => $cat_label,
                        ];
                    }
                }
            }
        } else {
            // Add specific context variables
            if (isset($variables[$context])) {
                $category_label = ucfirst($context);
                foreach ($variables[$context] as $var => $label) {
                    $formatted[] = [
                        'value' => $var,
                        'label' => $label,
                        'category' => $category_label,
                    ];
                }
            }
        }
        
        return rest_ensure_response([
            'success' => true,
            'data' => $formatted,
        ]);
    }
    
    /**
     * Get preview endpoint arguments
     *
     * @return array
     */
    private function get_preview_args(): array {
        return [
            'string' => [
                'type'        => 'string',
                'required'    => true,
                'description' => __('String containing dynamic variables', 'prorank-seo'),
            ],
            'context_id' => [
                'type'        => 'integer',
                'default'     => 0,
                'description' => __('ID of the context object', 'prorank-seo'),
            ],
            'context_type' => [
                'type'        => 'string',
                'default'     => 'post',
                'enum'        => ['post', 'page', 'term', 'category', 'tag', 'archive', 'product'],
                'description' => __('Type of context', 'prorank-seo'),
            ],
            'taxonomy' => [
                'type'        => 'string',
                'description' => __('Taxonomy for term context', 'prorank-seo'),
            ],
        ];
    }
}