/*
Theme Name: OwnersAtlas
Theme URI: https://ownersatlas.com
Description: OwnersAtlas child theme for Divi. Adds one page template, "OwnersAtlas — Raw Page (full width)" (page-oa-raw.php), which renders a page's content exactly as entered — no Divi header, footer, wrappers, front-end CSS, Theme Options CSS, or content filters. Built to GJ ruling R-0916-E (September 16, 2026). This stylesheet is intentionally empty: every raw page carries its own <style>.
Author: Gravity Junction
Author URI: https://gravityjunction.com
Template: Divi
Version: 1.1.0
Requires at least: 6.0
Requires PHP: 7.4
License: Proprietary — Gravity Junction / OwnersAtlas
Text Domain: ownersatlas
*/

/*
 * Built September 16, 2026 by Bob (Gravity Junction) — R-0916-E.
 * 1.0.2, September 19, 2026 — functions.php §3 only: removes WooCommerce's empty-catalog sentence
 * on /shop (R-0916-L §2). No CSS, no template change, nothing about raw pages touched.
 * 1.1.0, September 20, 2026 — WooCommerce customer email overrides (woocommerce/emails/ + plain/) + functions.php §4 hooks, R-0920-I. Raw-page machinery untouched.
 *
 * DO NOT ADD RULES HERE.
 * R-0916-E §3 (WIDE): nothing outside a Desk-gated design may narrow or restyle a raw page.
 * Store pages (shop, cart, checkout, my-account) render on Divi's own templates with Divi's
 * own stylesheet; they need nothing from this file either.
 */


/**
 * OA-15 — safe lead capture for both email-capture forms (homepage #free
 * section, and /free-deal-check). Forge, Sep 22 2026 — read-only diagnosis,
 * pasted in by Sharla's own hand per R-0922-A. Does not touch page content;
 * only adds a new AJAX endpoint and a footer-hooked script.
 */

add_action( 'wp_ajax_oa_leadcapture', 'oa_leadcapture_handle' );
add_action( 'wp_ajax_nopriv_oa_leadcapture', 'oa_leadcapture_handle' );
function oa_leadcapture_handle() {
    check_ajax_referer( 'oa_leadcapture', 'nonce' );

    // Honeypot — silently accept and drop anything that filled in the hidden field.
    if ( ! empty( $_POST['oa_hp'] ) ) {
        wp_send_json_success( array( 'ok' => true ) );
    }

    $email  = isset( $_POST['email'] )  ? sanitize_email( wp_unslash( $_POST['email'] ) )  : '';
    $timing = isset( $_POST['timing'] ) ? sanitize_text_field( wp_unslash( $_POST['timing'] ) ) : '';
    $source = isset( $_POST['source'] ) ? sanitize_text_field( wp_unslash( $_POST['source'] ) ) : 'unknown';

    if ( ! is_email( $email ) ) {
        wp_send_json_error( array( 'message' => 'Enter a valid email address.' ), 400 );
    }

    if ( ! in_array( $source, array( 'homepage', 'free-deal-check' ), true ) ) {
        $source = 'unknown';
    }

    $to      = 'ownersatlas@gravityjunction.com';
    $subject = 'OwnersAtlas lead — ' . $source;
    $body    = "New OwnersAtlas email-capture lead.\n\n"
             . "Email: {$email}\n"
             . 'Where they are: ' . ( $timing ? $timing : '(not given)' ) . "\n"
             . "Source: {$source}\n"
             . 'Page: ' . ( wp_get_referer() ? wp_get_referer() : '(unknown)' ) . "\n"
             . 'Time: ' . current_time( 'mysql' ) . "\n";

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

    if ( ! $sent ) {
        wp_send_json_error( array( 'message' => 'Something went wrong. Try again in a moment.' ), 500 );
    }

    wp_send_json_success( array( 'ok' => true ) );
}

add_action( 'wp_enqueue_scripts', 'oa_leadcapture_localize' );
function oa_leadcapture_localize() {
    wp_register_script( 'oa-leadcapture', false, array(), '1.0', true );
    wp_enqueue_script( 'oa-leadcapture' );
    wp_localize_script( 'oa-leadcapture', 'oaLeadCapture', array(
        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
        'nonce'   => wp_create_nonce( 'oa_leadcapture' ),
    ) );
}

add_action( 'wp_footer', 'oa_leadcapture_script' );
function oa_leadcapture_script() {
    ?>
    <script>
    (function(){
      function wireForm(selector, source, confirmHtml){
        var form = document.querySelector(selector);
        if (!form) return;

        // Dynamic honeypot — created here, never saved into page content.
        var hp = document.createElement('input');
        hp.type = 'text';
        hp.name = 'oa_hp_field';
        hp.tabIndex = -1;
        hp.autocomplete = 'off';
        hp.style.cssText = 'position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;';
        form.appendChild(hp);

        // /free-deal-check's email field ships live with no `required` attribute (the homepage
        // field already has one) — set here, dynamically, so an empty submit is blocked the same
        // way on both forms without editing the saved page content.
        var emailInputForRequired = form.querySelector('input[type=email]');
        if (emailInputForRequired) { emailInputForRequired.required = true; }

        // /free-deal-check's button ships live as type="button" (the homepage button is already
        // type="submit") — a type="button" element never fires the form's submit event on its own,
        // by spec, no matter what listener is attached below. This is the literal root cause named
        // in this file's own §2(a) for that form; without this line the submit handler below would
        // simply never run for /free-deal-check and the button would stay completely inert.
        var submitBtn = form.querySelector('button');
        if (submitBtn && submitBtn.type !== 'submit') { submitBtn.type = 'submit'; }

        form.addEventListener('submit', function(e){
          e.preventDefault(); // structurally rules out a native GET submission from here on

          var emailInput = form.querySelector('input[type=email]');
          if (!emailInput || !emailInput.checkValidity()) {
            if (emailInput) { emailInput.reportValidity(); }
            return;
          }

          var btn = form.querySelector('button');
          var originalText = btn ? btn.textContent : '';
          if (btn) { btn.disabled = true; btn.textContent = 'Sending…'; }

          var timingSel = form.querySelector('select');
          var data = new URLSearchParams();
          data.set('action', 'oa_leadcapture');
          data.set('nonce', window.oaLeadCapture.nonce);
          data.set('email', emailInput.value);
          data.set('timing', timingSel ? timingSel.value : '');
          data.set('source', source);
          data.set('oa_hp', hp.value);

          fetch(window.oaLeadCapture.ajaxUrl, {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: data.toString()
          }).then(function(r){ return r.json(); }).then(function(res){
            if (res && res.success) {
              form.outerHTML = confirmHtml;
            } else {
              if (btn) { btn.disabled = false; btn.textContent = originalText; }
              alert((res && res.data && res.data.message) || 'Something went wrong. Try again.');
            }
          }).catch(function(){
            if (btn) { btn.disabled = false; btn.textContent = originalText; }
            alert('Something went wrong. Try again in a moment.');
          });
        });
      }

      wireForm('form.fform', 'homepage',
        '<div class="fform-done" role="status"><h3>You\'re on the list.</h3>' +
        '<p>We\'ll be in touch at the address you gave us. <a href="/privacy-policy">Privacy Policy</a></p></div>');

      wireForm('form.oa-form', 'free-deal-check',
        '<div class="oa-form-done" role="status"><h3>You\'re on the list.</h3>' +
        '<p>We\'ll email you the moment the free deal check opens — nothing else, and you can unsubscribe ' +
        'any time before then. <a href="/privacy-policy">Privacy Policy</a></p></div>');
    })();
    </script>
    <?php
}


