<?php
/**
 * Feedback Endpoint for BoostBot REST API.
 *
 * Proxies user feedback submissions to the centralized backend.
 * No feedback data is stored locally — everything goes to the backend
 * for collection and review via the backend admin panel.
 *
 * @package BoostBot
 * @since 1.0.0
 * @updated 1.11.0 - Migrated from local DB storage to backend proxy
 */

// Prevent direct access to the file.
if (!defined('ABSPATH')) {
    exit;
}

/**
 * BoostBot_Feedback_Endpoint class.
 *
 * Proxies feedback submission from Admin panel to the centralized backend.
 *
 * @since 1.0.0
 */
class BoostBot_Feedback_Endpoint extends BoostBot_Base_Endpoint
{
    /**
     * The base path for this endpoint.
     *
     * @since 1.0.0
     * @access protected
     * @var string $rest_base
     */
    protected $rest_base = 'feedback';

    /**
     * Register the routes for this endpoint.
     *
     * @since 1.0.0
     */
    public function register()
    {
        // POST /wp-json/boostbot/v1/feedback - Submit feedback (proxied to backend)
        $this->register_route(
            '',
            'POST',
            [$this, 'submit_feedback'],
            [$this, 'admin_access']
        );
    }

    /**
     * Submit feedback by proxying it to the centralized backend.
     *
     * Collects site metadata (user info, site URL, plugin version, license)
     * and forwards everything — including an optional screenshot (base64-encoded) —
     * to the backend for centralized storage and review.
     *
     * @since 1.0.0
     * @updated 1.11.0 - Proxy to backend instead of local DB
     * @param WP_REST_Request $request The REST request object.
     * @return WP_REST_Response|WP_Error The response or error.
     */
    public function submit_feedback($request)
    {
        BoostBot_Logger::debug('Feedback submission received — proxying to backend');

        // Rate limiting: max 5 per hour
        $user_id = get_current_user_id();
        $rate_key = 'boostbot_feedback_' . $user_id;
        $count = (int) get_transient($rate_key);

        if ($count >= 5) {
            return $this->error(
                __('ניתן לשלוח עד 5 פניות בשעה. אנא נסה שוב מאוחר יותר.', 'boostbot'),
                429
            );
        }

        // Get and sanitize input
        $raw_type = sanitize_text_field($request->get_param('type'));
        $message = sanitize_textarea_field($request->get_param('message'));
        $browser_info = sanitize_text_field($request->get_param('browser_info'));

        // Handle custom "other" type — format: "other:Custom description"
        $type = $raw_type;
        if (strpos($raw_type, 'other:') === 0) {
            $type = $raw_type; // Keep the full string (e.g., "other:Partnership inquiry")
        } else {
            $allowed_types = ['bug', 'feature', 'question', 'other'];
            if (!in_array($type, $allowed_types, true)) {
                return $this->validation_error([
                    'type' => __('סוג הפנייה אינו תקין', 'boostbot'),
                ]);
            }
        }

        // Validate message
        if (empty($message) || mb_strlen($message) < 10) {
            return $this->validation_error([
                'message' => __('ההודעה צריכה להכיל לפחות 10 תווים', 'boostbot'),
            ]);
        }

        // Get user info
        $user = wp_get_current_user();
        $user_email = $user->user_email;
        $user_name = $user->display_name;

        // Get site info
        $site_url = home_url();
        $plugin_version = defined('BOOSTBOT_VERSION') ? BOOSTBOT_VERSION : '1.0.0';

        // Get license status
        $license_status = 'unknown';
        if (class_exists('BoostBot_License_Manager')) {
            $license_manager = new BoostBot_License_Manager();
            $license_status = $license_manager->is_pro() ? 'Pro' : 'Free';
        }

        // Handle screenshot — read file and convert to base64 for backend transmission
        $screenshot_base64 = null;
        $screenshot_name = null;
        $files = $request->get_file_params();

        if (!empty($files['screenshot'])) {
            $file = $files['screenshot'];

            // Validate MIME type
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            $file_type = wp_check_filetype_and_ext($file['tmp_name'], $file['name']);
            $mime = $file_type['type'] ?: $file['type'];

            if (in_array($mime, $allowed_types, true) && $file['size'] <= 5 * 1024 * 1024) {
                $contents = file_get_contents($file['tmp_name']); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- reading uploaded temp file
                if ($contents !== false) {
                    // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- encoding screenshot for data URI
                    $screenshot_base64 = 'data:' . $mime . ';base64,' . base64_encode($contents);
                    $screenshot_name = sanitize_file_name($file['name']);
                }
            }
        }

        // Build payload for backend
        $payload = array(
            'feedback_type'  => $type,
            'message'        => $message,
            'user_name'      => $user_name,
            'user_email'     => $user_email,
            'browser_info'   => $browser_info,
            'site_url'       => $site_url,
            'plugin_version' => $plugin_version,
            'license_status' => $license_status,
        );

        if ($screenshot_base64) {
            $payload['screenshot_data'] = $screenshot_base64;
            $payload['screenshot_name'] = $screenshot_name;
        }

        // Send to backend
        $backend = new BoostBot_Credits_Backend_Client();
        $site_id = $backend->ensure_site_id();

        if (is_wp_error($site_id)) {
            BoostBot_Logger::error('Cannot send feedback — backend site ID not available', [
                'error' => $site_id->get_error_message(),
            ]);
            return $this->error(
                __('שגיאה בשליחת המשוב. אנא נסה שוב מאוחר יותר.', 'boostbot'),
                500
            );
        }

        $base = $backend->get_base_url();
        $url = $base . '/api/v1/sites/' . rawurlencode($site_id) . '/feedback';

        $headers = array(
            'Accept'       => 'application/json',
            'Content-Type' => 'application/json',
        );

        $site_key = (string) BoostBot_Settings::get('backend_site_api_key', '');
        if (!empty($site_key)) {
            $headers['Authorization'] = 'Bearer ' . trim($site_key);
        }

        $response = wp_remote_post($url, array(
            'timeout' => 30,
            'headers' => $headers,
            'body'    => wp_json_encode($payload),
        ));

        if (is_wp_error($response)) {
            BoostBot_Logger::error('Failed to proxy feedback to backend', [
                'error' => $response->get_error_message(),
            ]);
            return $this->error(
                __('שגיאה בשליחת המשוב. אנא נסה שוב מאוחר יותר.', 'boostbot'),
                500
            );
        }

        $status_code = (int) wp_remote_retrieve_response_code($response);
        $body = json_decode(wp_remote_retrieve_body($response), true);

        if ($status_code >= 400 || (isset($body['success']) && $body['success'] === false)) {
            $error_msg = $body['error']['message'] ?? 'Backend error';
            BoostBot_Logger::error('Backend rejected feedback', [
                'status' => $status_code,
                'error'  => $error_msg,
            ]);
            return $this->error(
                __('שגיאה בשליחת המשוב. אנא נסה שוב מאוחר יותר.', 'boostbot'),
                500
            );
        }

        // Increment rate limit counter
        set_transient($rate_key, $count + 1, HOUR_IN_SECONDS);

        BoostBot_Logger::info('Feedback proxied to backend successfully', [
            'type' => $type,
            'user_email' => $user_email,
            'has_screenshot' => !empty($screenshot_base64),
        ]);

        return $this->success([
            'message' => __('תודה על המשוב! הפנייה נשלחה בהצלחה.', 'boostbot'),
        ]);
    }
}
