<?php
/**
 * License REST API Controller
 *
 * Handles license activation, deactivation, and status endpoints.
 *
 * @package VariationHub
 * @since 1.0.0
 */

namespace VariationHub\API;

use VariationHub\Core\License_Manager;
use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

defined('ABSPATH') || exit;

class License_Controller extends WP_REST_Controller {
    
    /**
     * Namespace
     */
    protected $namespace = 'variation-hub/v1';
    
    /**
     * Rest base
     */
    protected $rest_base = 'license';
    
    /**
     * Register routes
     */
    public function register_routes() {
        // GET /license/info
        register_rest_route($this->namespace, '/' . $this->rest_base . '/info', [
            [
                'methods' => WP_REST_Server::READABLE,
                'callback' => [$this, 'get_license_info'],
                'permission_callback' => [$this, 'check_permission'],
            ],
        ]);
        
        // POST /license/activate
        register_rest_route($this->namespace, '/' . $this->rest_base . '/activate', [
            [
                'methods' => WP_REST_Server::CREATABLE,
                'callback' => [$this, 'activate_license'],
                'permission_callback' => [$this, 'check_permission'],
                'args' => [
                    'license_key' => [
                        'required' => true,
                        'type' => 'string',
                        'sanitize_callback' => 'sanitize_text_field',
                        'validate_callback' => function($value) {
                            return !empty($value) && strlen($value) >= 10;
                        },
                    ],
                ],
            ],
        ]);
        
        // POST /license/deactivate
        register_rest_route($this->namespace, '/' . $this->rest_base . '/deactivate', [
            [
                'methods' => WP_REST_Server::CREATABLE,
                'callback' => [$this, 'deactivate_license'],
                'permission_callback' => [$this, 'check_permission'],
            ],
        ]);
        
        // GET /license/check-feature
        register_rest_route($this->namespace, '/' . $this->rest_base . '/check-feature', [
            [
                'methods' => WP_REST_Server::READABLE,
                'callback' => [$this, 'check_feature'],
                'permission_callback' => [$this, 'check_permission'],
                'args' => [
                    'feature' => [
                        'required' => true,
                        'type' => 'string',
                        'sanitize_callback' => 'sanitize_text_field',
                    ],
                ],
            ],
        ]);
    }
    
    /**
     * Check permission
     *
     * @param WP_REST_Request $request Request object
     * @return bool
     */
    public function check_permission($request) {
        return current_user_can('manage_woocommerce');
    }
    
    /**
     * Get license info
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response
     */
    public function get_license_info($request) {
        $info = License_Manager::get_license_info();
        
        return new WP_REST_Response([
            'success' => true,
            'data' => $info,
        ], 200);
    }
    
    /**
     * Activate license
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response|WP_Error
     */
    public function activate_license($request) {
        // 🔒 SECURITY: Rate limiting - prevent brute-force license key guessing
        $user_id = get_current_user_id();
        $transient_key = 'varihu_license_attempts_' . $user_id;
        $attempts = get_transient($transient_key);

        // Initialize attempts counter if not set
        if ($attempts === false) {
            $attempts = 0;
        }

        // Check if rate limit exceeded (5 attempts per 15 minutes)
        if ($attempts >= 5) {
            return new WP_Error(
                'too_many_attempts',
                __('Too many activation attempts. Please try again in 15 minutes.', 'variation-hub'),
                ['status' => 429] // 429 Too Many Requests
            );
        }

        $license_key = $request->get_param('license_key');

        $result = License_Manager::activate_license($license_key);

        if (!$result['success']) {
            // Increment failed attempts counter
            set_transient($transient_key, $attempts + 1, 15 * MINUTE_IN_SECONDS);

            return new WP_Error(
                'activation_failed',
                $result['message'],
                ['status' => 400]
            );
        }

        // Success - clear attempts counter
        delete_transient($transient_key);

        return new WP_REST_Response([
            'success' => true,
            'message' => $result['message'],
            'data' => [
                'tier' => $result['tier'],
            ],
        ], 200);
    }
    
    /**
     * Deactivate license
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response
     */
    public function deactivate_license($request) {
        $result = License_Manager::deactivate_license();
        
        return new WP_REST_Response([
            'success' => $result['success'],
            'message' => $result['message'],
        ], 200);
    }
    
    /**
     * Check if feature is available
     *
     * @param WP_REST_Request $request Request object
     * @return WP_REST_Response
     */
    public function check_feature($request) {
        $feature = $request->get_param('feature');
        $has_feature = License_Manager::has_feature($feature);
        
        return new WP_REST_Response([
            'success' => true,
            'data' => [
                'feature' => $feature,
                'available' => $has_feature,
                'tier' => License_Manager::get_tier(),
            ],
        ], 200);
    }
}
