<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class ShippingGuard_Feedback_API {
    public function init() {
        add_action('rest_api_init', array($this, 'register_routes'));
    }

    public function register_routes() {
        register_rest_route('shippingguard/v1', '/feedback', array(
            'methods' => 'POST',
            'callback' => array($this, 'handle_feedback'),
            'permission_callback' => function() {
                return current_user_can('manage_options');
            }
        ));
    }

    public function handle_feedback($request) {
        $params = $request->get_params();
        $name    = sanitize_text_field($params['name'] ?? 'Admin');
        $email   = sanitize_email($params['email'] ?? '');
        $site    = esc_url_raw($params['site'] ?? '');
        $type    = sanitize_text_field($params['type'] ?? 'Feature Suggestion');
        $message = sanitize_textarea_field($params['message'] ?? '');

        if (empty($email) || empty($message)) {
            return new WP_Error('invalid_data', 'Please fill in all required fields.', array('status' => 400));
        }

        $subject = "[ShippingGuard Feedback] - " . $type;
        $body = "New feedback from ShippingGuard Admin Dashboard:\n\n";
        $body .= "Name: " . $name . "\n";
        $body .= "Email: " . $email . "\n";
        $body .= "Site: " . $site . "\n";
        $body .= "Type: " . $type . "\n\n";
        $body .= "Message:\n" . $message;

        $to = 'suggest@dominopress.com';
        $admin_email = get_option('admin_email');
        $headers = array(
            'Content-Type: text/plain; charset=UTF-8',
            'From: ShippingGuard Feedback <' . $admin_email . '>',
            'Reply-To: ' . $name . ' <' . $email . '>'
        );

        $sent = wp_mail($to, $subject, $body, $headers);

        if ($sent) {
            return rest_ensure_response(array('success' => true, 'message' => 'Feedback sent successfully!'));
        } else {
            return new WP_Error('mail_failed', 'Failed to send feedback. Please try again later.', array('status' => 500));
        }
    }
}
