<?php
/**
 * Tool: wire_contact_form_to_email
 *
 * Find a Kadence Form block on a page and set its email recipient. After
 * saving, send a test email so the user can verify reception.
 *
 * v1 limit: supports kadence/form blocks (most common in Cadence-themed
 * sites). Returns a helpful message for other form types.
 */
if (!defined('ABSPATH')) exit;

function swcp_tool_wire_contact_form_to_email($input, $ctx) {
    $email_raw = isset($input['email']) ? trim((string) $input['email']) : '';
    if (!is_email($email_raw)) {
        return ['ok' => false, 'message' => 'The email address "' . esc_html($email_raw) . '" does not look valid. Ask the user for a correct address.'];
    }
    $email = sanitize_email($email_raw);

    $page_arg = isset($input['page']) ? $input['page'] : '';
    $post = null;
    if ($page_arg) {
        $resolved = swcp_resolve_or_error($page_arg, $ctx['post_id'] ?? 0);
        if (is_array($resolved) && isset($resolved['ok']) && !$resolved['ok']) return $resolved;
        $post = $resolved;
    } else {
        $post = swcp_resolve_page('contact');
        if (!$post) {
            $post = swcp_find_first_page_with_form();
        }
        if (!$post) {
            return ['ok' => false, 'message' => 'Could not find a page with a contact form on this site. Tell the user which page contains the form.'];
        }
    }

    $blocks = swcp_get_blocks($post);
    $found_kadence    = false;
    $found_other      = '';
    $current_email    = '';

    $blocks = swcp_walk_blocks($blocks, function (&$b) use (&$found_kadence, &$found_other, &$current_email, $email) {
        if (!isset($b['blockName'])) return null;
        if ($b['blockName'] === 'kadence/form') {
            $found_kadence = true;
            if (!isset($b['attrs']) || !is_array($b['attrs'])) $b['attrs'] = [];
            if (!isset($b['attrs']['email']) || !is_array($b['attrs']['email'])) $b['attrs']['email'] = [];
            if (!empty($b['attrs']['email']['emailTo'])) {
                $current_email = (string) $b['attrs']['email']['emailTo'];
            }
            $b['attrs']['email']['emailTo'] = $email;
            return $b;
        }
        if (in_array($b['blockName'], ['gravityforms/form', 'jetpack/contact-form', 'contact-form-7/contact-form-selector'], true)) {
            $found_other = $b['blockName'];
        }
        return null;
    });

    if (!$found_kadence) {
        if ($found_other) {
            return [
                'ok' => false,
                'message' => 'The form on "' . esc_html(get_the_title($post)) . '" is a ' . esc_html($found_other) . ' form. SailWP Co-pilot v1 only configures Kadence Form blocks. The user can set the recipient from the form\'s own settings panel.',
            ];
        }
        return ['ok' => false, 'message' => 'Could not find a Kadence Form block on "' . esc_html(get_the_title($post)) . '".'];
    }

    $saved = swcp_save_blocks($post->ID, $blocks);
    if (!$saved) return ['ok' => false, 'message' => 'Found and updated the form, but failed to save the page.'];

    // Send a test email so the user knows it works.
    $sent = wp_mail(
        $email,
        'SailWP Co-pilot — contact form is wired up',
        "This is a test message from SailWP Co-pilot.\n\n" .
        "I just connected the contact form on your '" . get_the_title($post) . "' page to this email address. " .
        "When someone fills in the form, you will receive their message at: " . $email . "\n\n" .
        "If you can read this, you're all set."
    );

    $msg_parts = ['Wired the contact form on "' . esc_html(get_the_title($post)) . '" to send submissions to ' . esc_html($email) . '.'];
    if ($current_email && $current_email !== $email) {
        $msg_parts[] = '(Previous recipient: ' . esc_html($current_email) . '.)';
    }
    $msg_parts[] = $sent
        ? 'A test email has been sent — ask the user to check their inbox.'
        : 'However, the test email could not be queued. The form is configured but mail delivery may need attention (SMTP plugin or hosting setup).';

    return [
        'ok'           => true,
        'message'      => implode(' ', $msg_parts),
        'page_id'      => $post->ID,
        'view_url'     => swcp_view_url_for($post->ID),
        'edit_url'     => swcp_edit_url_for($post->ID),
        'email'        => $email,
        'test_sent'    => (bool) $sent,
    ];
}

/**
 * Walk all published pages, return first one containing a known form block.
 */
function swcp_find_first_page_with_form() {
    $pages = get_posts([
        'post_type'      => 'page',
        'posts_per_page' => 50,
        'post_status'    => 'publish',
    ]);
    foreach ($pages as $p) {
        if (preg_match('/<!--\s+wp:(kadence|gravityforms|jetpack|contact-form-7)/i', $p->post_content)) {
            return $p;
        }
    }
    return null;
}
