<?php

namespace SoftminalB2B\Http\Controllers;

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

/**
 * Optional, user-initiated feedback — currently the deactivation survey.
 *
 * Feedback is only ever sent when the user explicitly clicks "Submit & Deactivate"
 * in the survey modal, never silently. The payload is forwarded to the Softminal
 * feedback endpoint via wp_remote_post(). A remote failure never blocks the user:
 * the modal proceeds to the real deactivation URL regardless of the response.
 */
class FeedbackController extends Controller
{
    /** Plugin slug the remote endpoint keys feedback by. */
    private const PLUGIN_SLUG = 'softminal-b2b-wholesale-for-woocommerce';

    /**
     * Allowed reason keys — must match the survey's radio values. Anything
     * outside this list is rejected so the endpoint only receives known values.
     */
    private const ALLOWED_REASONS = [
        'temporary',
        'not_working',
        'better_found',
        'too_complex',
        'no_longer',
        'other',
    ];

    /**
     * Receive a deactivation survey response and forward it to Softminal.
     */
    public function deactivation(\WP_REST_Request $request, $params = [])
    {
        $body = $request->get_json_params();

        $reason = sanitize_text_field($body['reason'] ?? '');
        if (!in_array($reason, self::ALLOWED_REASONS, true)) {
            return $this->error(__('Invalid feedback reason.', 'softminal-b2b-wholesale-for-woocommerce'), 400);
        }

        $message = sanitize_textarea_field($body['message'] ?? '');
        if (strlen($message) > 2000) {
            $message = substr($message, 0, 2000);
        }

        $payload = [
            'plugin_slug'    => self::PLUGIN_SLUG,
            'action'         => 'deactivate',
            'reason'         => $reason,
            'message'        => $message,
            'site_url'       => home_url(),
            'plugin_version' => substr((string) (defined('SMB2B_VERSION') ? SMB2B_VERSION : ''), 0, 32),
            'wp_version'     => substr((string) get_bloginfo('version'), 0, 32),
            'php_version'    => substr(PHP_VERSION, 0, 32),
        ];

        $forwarded = $this->forwardToRemote($payload);

        // Always report success — feedback is best-effort and must never prevent
        // the user from completing the deactivation they asked for.
        return $this->success(['forwarded' => $forwarded], __('Thanks for your feedback.', 'softminal-b2b-wholesale-for-woocommerce'));
    }

    /**
     * POST the payload to the Softminal endpoint. Overridable via the
     * SMB2B_FEEDBACK_ENDPOINT constant or the `smb2b_feedback_endpoint` filter.
     * Returns true only on a 2xx response.
     */
    private function forwardToRemote(array $payload): bool
    {
        $endpoint = defined('SMB2B_FEEDBACK_ENDPOINT')
            ? SMB2B_FEEDBACK_ENDPOINT
            : 'https://admin.softminal.com/wp-json/softminal/v1/feedback';

        /**
         * Filters the deactivation-feedback endpoint URL.
         *
         * @param string $endpoint The remote URL feedback is posted to.
         */
        $endpoint = apply_filters('smb2b_feedback_endpoint', $endpoint);

        if (empty($endpoint) || !wp_http_validate_url($endpoint)) {
            return false;
        }

        $response = wp_remote_post($endpoint, [
            'timeout'    => 5,
            'blocking'   => true,
            'headers'    => ['Content-Type' => 'application/json'],
            'body'       => wp_json_encode($payload),
            'user-agent' => 'SoftminalB2B/' . (defined('SMB2B_VERSION') ? SMB2B_VERSION : '0') . '; ' . home_url(),
        ]);

        if (is_wp_error($response)) {
            return false;
        }

        $code = (int) wp_remote_retrieve_response_code($response);

        return $code >= 200 && $code < 300;
    }
}
