<?php
/**
 * Built-in contact form for Co-pilot designed pages.
 *
 * Designed pages frequently contain CTA buttons like "Book now", "Contact us",
 * "Get in touch", "Sign up" — but they don't ship a real form behind them
 * because the AI just generates the visual. This module wires those buttons
 * to a single modal with an email field, and submissions are emailed to the
 * site's admin via wp_mail().
 *
 * The detection runs on every designed page (frontend, logged out or in).
 * Buttons are matched by:
 *   - href value: #contact, #book, #booking, #signup, #join, mailto:
 *   - link/button text: "book", "contact", "get in touch", "sign up", "join", "schedule"
 *   - data attribute: data-swcp-contact (preferred way for Co-pilot to mark them)
 *
 * Rate-limit: 5 submissions per IP per hour, tracked in a transient.
 * Honeypot: hidden field "website" must stay empty.
 */
if (!defined('ABSPATH')) exit;

/* ---------------------------------------------------------------------------
 * REST endpoint: POST /wp-json/sailwp-copilot/v1/contact
 * Public (no auth). Validates email, rate-limits per IP, sends mail.
 * ------------------------------------------------------------------------ */
add_action('rest_api_init', function () {
    register_rest_route('sailwp-copilot/v1', '/contact', [
        'methods'             => 'POST',
        'callback'            => 'swcp_handle_contact_submission',
        'permission_callback' => '__return_true',
    ]);
});

function swcp_handle_contact_submission(WP_REST_Request $req) {
    // Honeypot — bots fill every field they find.
    if (trim((string) $req->get_param('website')) !== '') {
        return new WP_Error('spam', 'Submission rejected.', ['status' => 400]);
    }

    $email = sanitize_email((string) $req->get_param('email'));
    if (!$email || !is_email($email)) {
        return new WP_Error('bad_email', 'Please enter a valid email address.', ['status' => 400]);
    }

    $message  = sanitize_textarea_field((string) $req->get_param('message'));
    $page_url = esc_url_raw((string) $req->get_param('page_url'));
    $source   = sanitize_text_field((string) $req->get_param('source_button'));

    // Rate-limit: 5 submissions per IP per hour.
    $ip   = swcp_contact_client_ip();
    $key  = 'swcp_contact_rate_' . md5($ip);
    $hits = (int) get_transient($key);
    if ($hits >= 5) {
        return new WP_Error('rate_limited', 'Too many submissions. Try again later.', ['status' => 429]);
    }
    set_transient($key, $hits + 1, HOUR_IN_SECONDS);

    $admin_email = get_option('admin_email');
    $site_name   = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);

    $subject = sprintf('[%s] New contact from %s', $site_name, $email);
    $body    = "A visitor just reached out via your site:\n\n";
    $body   .= "Email:   $email\n";
    if ($source)   $body .= "Button:  $source\n";
    if ($page_url) $body .= "Page:    $page_url\n";
    $body   .= "Time:    " . wp_date('Y-m-d H:i', current_time('timestamp')) . "\n";
    if ($message) {
        $body .= "\nMessage:\n" . $message . "\n";
    } else {
        $body .= "\nNo message — they left their email so you can follow up.\n";
    }

    $headers = [
        'Reply-To: ' . $email,
        'From: ' . sprintf('%s <%s>', $site_name, $admin_email),
    ];

    $sent = wp_mail($admin_email, $subject, $body, $headers);
    if (!$sent) {
        // wp_mail failed — typical on fresh SpinupWP / mail-less installs.
        // Fall back to the SailWP proxy which uses Resend so submissions
        // still land even when the host site has no SMTP configured.
        $sent = swcp_contact_forward_via_proxy($admin_email, $email, $subject, $body, $site_name);
    }
    if (!$sent) {
        return new WP_Error('mail_failed', 'Something went wrong on our side. Please try again later.', ['status' => 500]);
    }

    return rest_ensure_response([
        'ok'      => true,
        'message' => "Thanks! We'll be in touch.",
    ]);
}

/**
 * Fallback delivery via the SailWP proxy. Used when wp_mail() returns false
 * — typical on hosts without SMTP. Proxy sends via Resend.
 *
 * Returns true on successful send, false otherwise.
 */
function swcp_contact_forward_via_proxy($to, $reply_to, $subject, $body, $from_name) {
    if (!class_exists('SailWP_Copilot_Plugin')) return false;
    $license = SailWP_Copilot_Plugin::get_license_key();
    if (!$license) return false;
    $proxy_url = rtrim(SailWP_Copilot_Plugin::get_ai_proxy_url(), '/');
    if (!$proxy_url) return false;

    $r = wp_remote_post($proxy_url . '/api/v1/copilot/forward-contact', [
        'timeout' => 15,
        'headers' => [
            'Content-Type'  => 'application/json',
            'X-License-Key' => $license,
        ],
        'body' => wp_json_encode([
            'admin_email' => $to,
            'reply_to'    => $reply_to,
            'subject'     => $subject,
            'body'        => $body,
            'from_name'   => $from_name,
        ]),
    ]);
    if (is_wp_error($r)) {
        error_log('[swcp contact] proxy fallback failed: ' . $r->get_error_message());
        return false;
    }
    $code = (int) wp_remote_retrieve_response_code($r);
    $data = json_decode((string) wp_remote_retrieve_body($r), true);
    if ($code !== 200 || empty($data['ok'])) {
        error_log('[swcp contact] proxy fallback non-ok: ' . $code . ' ' . wp_remote_retrieve_body($r));
        return false;
    }
    return true;
}

function swcp_contact_client_ip() {
    foreach (['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'] as $h) {
        if (!empty($_SERVER[$h])) {
            $ip = explode(',', (string) $_SERVER[$h])[0];
            return trim($ip);
        }
    }
    return '0.0.0.0';
}

/* ---------------------------------------------------------------------------
 * Enqueue the modal CSS + JS only on designed pages (frontend).
 * ------------------------------------------------------------------------ */
add_action('wp_enqueue_scripts', 'swcp_enqueue_contact_form', 100);

function swcp_enqueue_contact_form() {
    if (is_admin()) return;
    if (!is_singular()) return;
    $post = get_queried_object();
    if (!$post instanceof WP_Post) return;
    if (!get_post_meta($post->ID, '_swcp_designed', true)) return;

    $css_path = SAILWP_COPILOT_DIR . 'assets/css/contact-form.css';
    $js_path  = SAILWP_COPILOT_DIR . 'assets/js/contact-form.js';
    $css_ver  = SAILWP_COPILOT_VERSION . '.' . (file_exists($css_path) ? filemtime($css_path) : 0);
    $js_ver   = SAILWP_COPILOT_VERSION . '.' . (file_exists($js_path)  ? filemtime($js_path)  : 0);

    wp_enqueue_style(
        'sailwp-copilot-contact-form',
        SAILWP_COPILOT_URL . 'assets/css/contact-form.css',
        [],
        $css_ver
    );
    wp_enqueue_script(
        'sailwp-copilot-contact-form',
        SAILWP_COPILOT_URL . 'assets/js/contact-form.js',
        [],
        $js_ver,
        true
    );
    wp_localize_script('sailwp-copilot-contact-form', 'SailWPContactForm', [
        'restUrl' => esc_url_raw(rest_url('sailwp-copilot/v1/contact')),
        'pageUrl' => esc_url_raw(get_permalink($post->ID)),
        'labels'  => [
            'title'        => __('Leave your email — we\'ll be in touch.', 'sailwp-ai-copilot'),
            'emailLabel'   => __('Your email', 'sailwp-ai-copilot'),
            'emailPh'      => 'you@example.com',
            'messageLabel' => __('Anything you want us to know? (optional)', 'sailwp-ai-copilot'),
            'send'         => __('Send', 'sailwp-ai-copilot'),
            'sending'      => __('Sending…', 'sailwp-ai-copilot'),
            'close'        => __('Close', 'sailwp-ai-copilot'),
        ],
    ]);
}
