<?php

/**
 * Redirect Settings REST API Controller
 *
 * @package ProRank\SEO\Core\RestApi
 * @since   0.1.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\RestApi;

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

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


/**
 * Class RedirectSettingsController
 *
 * Handles REST API endpoints for redirect settings
 */


class RedirectSettingsController extends WP_REST_Controller {
    /**
     * Namespace
     *
     * @var string
     */
    protected $namespace = 'prorank-seo/v1';

    /**
     * Rest base
     *
     * @var string
     */
    protected $rest_base = 'settings/redirects';

    /**
     * Register routes
     *
     * @return void
     */
    public function register_routes(): void {
        register_rest_route($this->namespace, '/' . $this->rest_base, [
            [
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => [$this, 'get_settings'],
                'permission_callback' => [$this, 'permissions_check'],
            ],
            [
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => [$this, 'update_settings'],
                'permission_callback' => [$this, 'permissions_check'],
            ],
            'schema' => [$this, 'get_public_item_schema'],
        ]);
    }

    /**
     * Check permissions
     *
     * @return bool
     */
    public function permissions_check(): bool {
        return current_user_can('manage_options');
    }

    /**
     * Get redirect settings
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function get_settings(WP_REST_Request $request) {
        $settings = [
            'auto_redirects_enabled' => get_option('prorank_auto_redirects_enabled', true),
            'redirect_deleted_posts' => get_option('prorank_redirect_deleted_posts', false),
            'default_redirect_type' => get_option('prorank_default_redirect_type', '301'),
            'alert_threshold' => get_option('prorank_404_alert_threshold', '50'),
            'enable_caching' => get_option('prorank_redirect_caching_enabled', true),
            'cache_expiry' => get_option('prorank_redirect_cache_expiry', '3600'),
            'max_chain_depth' => get_option('prorank_max_redirect_chain_depth', '3'),
            'enable_404_monitoring' => get_option('prorank_404_monitoring_enabled', true),
            'monitor_404_errors' => get_option('prorank_404_monitoring_enabled', true),
            'retention_days' => get_option('prorank_404_retention_days', '90'),
            'auto_suggest_redirects' => get_option('prorank_auto_suggest_redirects', false),
        ];

        return rest_ensure_response($settings);
    }

    /**
     * Update redirect settings
     *
     * @param WP_REST_Request $request Request object.
     * @return WP_REST_Response|WP_Error
     */
    public function update_settings(WP_REST_Request $request) {
        $params = $request->get_params();
        $updated = [];

        // Map of setting keys to option names
        $settings_map = [
            'auto_redirects_enabled' => 'prorank_auto_redirects_enabled',
            'redirect_deleted_posts' => 'prorank_redirect_deleted_posts',
            'default_redirect_type' => 'prorank_default_redirect_type',
            'alert_threshold' => 'prorank_404_alert_threshold',
            'enable_caching' => 'prorank_redirect_caching_enabled',
            'cache_expiry' => 'prorank_redirect_cache_expiry',
            'max_chain_depth' => 'prorank_max_redirect_chain_depth',
            'enable_404_monitoring' => 'prorank_404_monitoring_enabled',
            'monitor_404_errors' => 'prorank_404_monitoring_enabled',
            'retention_days' => 'prorank_404_retention_days',
            'auto_suggest_redirects' => 'prorank_auto_suggest_redirects',
        ];

        foreach ($settings_map as $key => $option_name) {
            if (isset($params[$key])) {
                $value = $params[$key];

                // Sanitize based on type
                if (is_bool($value)) {
                    $value = (bool) $value;
                } elseif (is_numeric($value)) {
                    $value = (string) $value;
                } else {
                    $value = sanitize_text_field($value);
                }

                update_option($option_name, $value);
                $updated[$key] = $value;
            }
        }

        // Clear redirect cache if caching settings changed
        if (isset($updated['enable_caching']) || isset($updated['cache_expiry'])) {
            wp_cache_flush_group('prorank_redirects');
        }

        return rest_ensure_response([
            'success' => true,
            'updated' => $updated,
        ]);
    }

    /**
     * Get item schema
     *
     * @return array
     */
    public function get_public_item_schema(): array {
        if ($this->schema) {
            return $this->add_additional_fields_schema($this->schema);
        }

        $this->schema = [
            '$schema' => 'http://json-schema.org/draft-04/schema#',
            'title' => 'redirect-settings',
            'type' => 'object',
            'properties' => [
                'auto_redirects_enabled' => [
                    'description' => __('Enable automatic redirect creation', 'prorank-seo'),
                    'type' => 'boolean',
                    'default' => true,
                ],
                'redirect_deleted_posts' => [
                    'description' => __('Redirect deleted posts to home', 'prorank-seo'),
                    'type' => 'boolean',
                    'default' => false,
                ],
                'default_redirect_type' => [
                    'description' => __('Default redirect type', 'prorank-seo'),
                    'type' => 'string',
                    'enum' => ['301', '302', '307', '308'],
                    'default' => '301',
                ],
                'alert_threshold' => [
                    'description' => __('404 alert threshold', 'prorank-seo'),
                    'type' => 'string',
                    'default' => '50',
                ],
                'enable_caching' => [
                    'description' => __('Enable redirect caching', 'prorank-seo'),
                    'type' => 'boolean',
                    'default' => true,
                ],
                'cache_expiry' => [
                    'description' => __('Cache expiry in seconds', 'prorank-seo'),
                    'type' => 'string',
                    'default' => '3600',
                ],
                'max_chain_depth' => [
                    'description' => __('Maximum redirect chain depth', 'prorank-seo'),
                    'type' => 'string',
                    'default' => '3',
                ],
                'enable_404_monitoring' => [
                    'description' => __('Enable 404 monitoring', 'prorank-seo'),
                    'type' => 'boolean',
                    'default' => true,
                ],
                'retention_days' => [
                    'description' => __('404 retention days', 'prorank-seo'),
                    'type' => 'string',
                    'default' => '90',
                ],
                'auto_suggest_redirects' => [
                    'description' => __('Auto-suggest redirects', 'prorank-seo'),
                    'type' => 'boolean',
                    'default' => false,
                ],
            ],
        ];

        return $this->add_additional_fields_schema($this->schema);
    }
}
