<?php

namespace CouponsPlus\App\Handlers;

use CouponsPlus\Original\Environment\Env;
use CouponsPlus\Original\Events\Handler\EventHandler;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
use WP_Error;

use const COUPONS_PLUS_API_BASE_URL;

class PresetsAPIHandler extends EventHandler
{
    protected $numberOfArguments = 1;
    protected $priority = 10;

    public function execute()
    {
        register_rest_route('coupons-plus/v1', '/presets/steps', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'get_preset_steps'],
            'permission_callback' => [$this, 'check_permissions'],
        ]);

        register_rest_route('coupons-plus/v1', '/presets/(?P<id>[a-zA-Z0-9_-]+)', [
            'methods' => WP_REST_Server::READABLE,
            'callback' => [$this, 'get_preset_by_id'],
            'permission_callback' => [$this, 'check_permissions'],
            'args' => [
                'id' => [
                    'type' => 'string',
                    'required' => true,
                    'description' => 'The preset ID to retrieve',
                    'sanitize_callback' => 'sanitize_text_field',
                    'validate_callback' => function($param, $request, $key) {
                        return preg_match('/^[a-zA-Z0-9_-]+$/', $param) === 1;
                    },
                ]
            ]
        ]);
    }

    /**
     * Get preset steps data
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response|WP_Error
     */
    public function get_preset_steps(WP_REST_Request $request)
    {
        $api_url = $this->get_api_url('presets/steps');
        
        $response = wp_remote_get($api_url, [
            'timeout' => 15,
            'sslverify' => $this->should_verify_ssl(),
            'headers' => [
                'Accept' => 'application/json',
            ]
        ]);

        if (is_wp_error($response)) {
            return new WP_Error(
                'preset_fetch_error',
                __('Failed to fetch preset steps from API', 'coupons-plus-for-woocommerce'),
                ['status' => 500]
            );
        }

        $status_code = wp_remote_retrieve_response_code($response);
        if ($status_code !== 200) {
            return new WP_Error(
                'preset_fetch_error',
                __('Failed to fetch preset steps from API', 'coupons-plus-for-woocommerce'),
                ['status' => $status_code]
            );
        }

        $body = wp_remote_retrieve_body($response);
        
        // Verify it's valid JSON
        $data = json_decode($body);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return new WP_Error(
                'invalid_json',
                __('Invalid response from preset API', 'coupons-plus-for-woocommerce'),
                ['status' => 500]
            );
        }

        return new WP_REST_Response($data, 200);
    }

    /**
     * Get preset by ID
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response|WP_Error
     */
    public function get_preset_by_id(WP_REST_Request $request)
    {
        $preset_id = $request->get_param('id');
        $api_url = $this->get_api_url("presets/{$preset_id}");

        $response = wp_remote_get($api_url, [
            'timeout' => 15,
            'sslverify' => $this->should_verify_ssl(),
            'headers' => [
                'Accept' => 'application/json',
            ]
        ]);

        if (is_wp_error($response)) {
            return new WP_Error(
                'preset_fetch_error',
                __('Failed to fetch preset from API', 'coupons-plus-for-woocommerce'),
                ['status' => 500]
            );
        }

        $status_code = wp_remote_retrieve_response_code($response);
        if ($status_code !== 200) {
            return new WP_Error(
                'preset_fetch_error',
                __('Failed to fetch preset from API', 'coupons-plus-for-woocommerce'),
                ['status' => $status_code]
            );
        }

        $body = wp_remote_retrieve_body($response);
        
        // Verify it's valid JSON and decode it
        $data = json_decode($body, true); // Decode to array
        if (json_last_error() !== JSON_ERROR_NONE) {
            return new WP_Error(
                'invalid_json',
                __('Invalid response from preset API', 'coupons-plus-for-woocommerce'),
                ['status' => 500]
            );
        }

        // Return the decoded data - WordPress will re-encode it properly as JSON
        return new WP_REST_Response($data, 200);
    }

    /**
     * Check if user has permission to access presets
     *
     * @return bool
     */
    public function check_permissions(): bool
    {
        return current_user_can('manage_woocommerce') || current_user_can('manage_options');
    }

    /**
     * Get the API base URL
     * Can be overridden with a filter or constant for production
     *
     * @param string $endpoint
     * @return string
     */
    private function get_api_url(string $endpoint): string
    {
        return rtrim($this->getBaseUrl(), '/') . '/' . ltrim($endpoint, '/');
    }

    /**
     * SSL verification required on production domains
     */
    private function should_verify_ssl(): bool
    {
        $api_url = $this->getBaseUrl();

        // Disable SSL verification for local development domains ONLY
        if (strpos($api_url, '.test') !== false || strpos($api_url, '.local') !== false || strpos($api_url, 'localhost') !== false) {
            return false;
        }

        // Enable SSL verification for production domains
        return true;
    }

    /**
     * @return mixed|string|null
     */
    private function getBaseUrl()
    {
        return Env::settings()->environment === 'production' ? 'https://api.couponspluspro.com' : COUPONS_PLUS_API_BASE_URL;
    }
}
