/* ================================================================
 * PRIVATE STUDENT LOAN AID — Form Handlers (Apply + Contact + Privacy)
 * v3 — Compatible con SiteMailer (Elementor's email service)
 *
 * CAMBIO v3: NO forzamos el "From:" en los headers. SiteMailer
 * usa su sender autorizado (site-xxxxx@em0001.sitemailerservice.com)
 * y nosotros solo forzamos Reply-To y Name via filtros.
 *
 * Pegar TODO este bloque al FINAL del functions.php del theme.
 *
 * Endpoints AJAX:
 *   - psla_submit_apply    → /apply/ y wizard del /home/
 *   - psla_submit_contact  → /contact/
 *   - psla_submit_privacy  → /do-not-sell-or-share/
 * ================================================================ */

if (!defined('ABSPATH')) { exit; }

// -------------------------------------------------------------
// CONFIGURACIÓN — destinatarios de leads
// -------------------------------------------------------------
if (!defined('PSLA_LEAD_RECIPIENTS')) {
    define('PSLA_LEAD_RECIPIENTS', implode(',', [
        'jross@privatestudentrelief.com',
        'jesse@privatestudentrelief.com',
        'henry@privatestudentrelief.com',
        'jpalmas28@yahoo.com',
        'jose@eliminarsudeuda.com',
    ]));
}
if (!defined('PSLA_FROM_NAME')) { define('PSLA_FROM_NAME', 'Private Student Loan Aid'); }

// -------------------------------------------------------------
// FILTROS GLOBALES — que el "Name" en los emails salga como
// "Private Student Loan Aid" (SiteMailer respeta este filter)
// -------------------------------------------------------------
add_filter('wp_mail_from_name', function($name) {
    // Sobreescribir el default "WordPress" y strings vacíos
    if ($name === 'WordPress' || empty($name)) {
        return PSLA_FROM_NAME;
    }
    return $name;
}, 20);

// -------------------------------------------------------------
// LOG de errores de wp_mail (revisar en debug.log si algo falla)
// -------------------------------------------------------------
add_action('wp_mail_failed', function($wp_error) {
    if (is_wp_error($wp_error)) {
        error_log('[PSLA wp_mail failed] ' . $wp_error->get_error_message());
    }
});

// -------------------------------------------------------------
// HELPER — IP real
// -------------------------------------------------------------
function psla_get_client_ip() {
    foreach (['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'] as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = trim(explode(',', $_SERVER[$key])[0]);
            if (filter_var($ip, FILTER_VALIDATE_IP)) { return $ip; }
        }
    }
    return '0.0.0.0';
}

// -------------------------------------------------------------
// HELPER — rate limit por IP + prefijo
// -------------------------------------------------------------
function psla_check_rate_limit($prefix, $max_per_hour = 5) {
    $ip = psla_get_client_ip();
    $rate_key = 'psla_' . $prefix . '_rate_' . md5($ip);
    $count = (int) get_transient($rate_key);
    if ($count >= $max_per_hour) {
        return false;
    }
    set_transient($rate_key, $count + 1, HOUR_IN_SECONDS);
    return true;
}

// -------------------------------------------------------------
// HELPER — guardar lead en la BD (Custom Post Type)
// -------------------------------------------------------------
function psla_save_lead_to_db($type, $data, $email_sent) {
    $first = $data['first_name'] ?? ($data['name'] ?? 'Unknown');
    $last  = $data['last_name']  ?? '';
    $state = $data['state'] ?? '';

    $title = sprintf('[%s] %s %s — %s (%s)',
        strtoupper($type),
        $first, $last, $state,
        current_time('Y-m-d H:i')
    );

    $post_id = wp_insert_post([
        'post_type'   => 'psla_lead',
        'post_status' => 'private',
        'post_title'  => $title,
    ]);
    if ($post_id && !is_wp_error($post_id)) {
        update_post_meta($post_id, 'lead_type', $type);
        foreach ($data as $key => $value) {
            update_post_meta($post_id, $key, is_array($value) ? implode(', ', $value) : $value);
        }
        update_post_meta($post_id, 'email_sent',   $email_sent ? 'yes' : 'no');
        update_post_meta($post_id, 'submitted_at', current_time('mysql'));
        update_post_meta($post_id, 'source_page',  esc_url_raw($_SERVER['HTTP_REFERER'] ?? ''));
        update_post_meta($post_id, 'ip_address',   psla_get_client_ip());
    }
    return $post_id;
}

// -------------------------------------------------------------
// CPT para todos los leads
// -------------------------------------------------------------
add_action('init', function() {
    register_post_type('psla_lead', [
        'labels' => [
            'name'          => 'PSLA Leads',
            'singular_name' => 'PSLA Lead',
        ],
        'public'          => false,
        'show_ui'         => true,
        'show_in_menu'    => true,
        'menu_icon'       => 'dashicons-forms',
        'menu_position'   => 25,
        'capability_type' => 'post',
        'supports'        => ['title', 'custom-fields'],
        'has_archive'     => false,
    ]);
});

// -------------------------------------------------------------
// Inyecta window.PSLA_AJAX.url en las páginas con form
// -------------------------------------------------------------
add_action('wp_head', function() {
    $slugs = ['apply', 'contact', 'do-not-sell-or-share'];
    $is_form_page = is_front_page() || is_home();
    foreach ($slugs as $slug) {
        if (is_page($slug)) { $is_form_page = true; break; }
    }
    if (!$is_form_page) return;
    echo '<script>window.PSLA_AJAX = ' . wp_json_encode(['url' => admin_url('admin-ajax.php')]) . ';</script>' . "\n";
});


/* ================================================================
 * 1) HANDLER — /apply/ y Home wizard
 * ================================================================ */
add_action('wp_ajax_psla_submit_apply',        'psla_handle_apply_submission');
add_action('wp_ajax_nopriv_psla_submit_apply', 'psla_handle_apply_submission');

function psla_handle_apply_submission() {

    if (!empty($_POST['website_url'])) {
        wp_send_json_success(['ok' => true]);
    }

    if (!psla_check_rate_limit('apply', 5)) {
        wp_send_json_error(['message' => 'Too many submissions. Please try again later or call (877) 866-4108.']);
    }

    $data = [
        'loan_type'       => sanitize_text_field($_POST['loan_type']       ?? ''),
        'loan_amount'     => sanitize_text_field($_POST['loan_amount']     ?? ''),
        'monthly_payment' => sanitize_text_field($_POST['monthly_payment'] ?? ''),
        'first_name'      => sanitize_text_field($_POST['first_name']      ?? ''),
        'last_name'       => sanitize_text_field($_POST['last_name']       ?? ''),
        'state'           => sanitize_text_field($_POST['state']           ?? ''),
        'email'           => sanitize_email(     $_POST['email']           ?? ''),
        'phone'           => sanitize_text_field($_POST['phone']           ?? ''),
    ];

    foreach (['loan_type', 'loan_amount', 'first_name', 'last_name', 'state', 'email', 'phone'] as $field) {
        if (empty($data[$field])) {
            wp_send_json_error(['message' => 'Please complete all required fields.']);
        }
    }
    if (!is_email($data['email'])) {
        wp_send_json_error(['message' => 'Please enter a valid email address.']);
    }
    if (in_array($data['state'], ['South Carolina', 'Mississippi'], true)) {
        wp_send_json_error(['message' => 'We are sorry — services are not available in ' . $data['state'] . '.']);
    }
    if ($data['loan_type'] === 'Federal Student Loans') {
        wp_send_json_error(['message' => 'We only assist with private student loans. Federal borrowers can access free programs at studentaid.gov.']);
    }

    $subject = sprintf('[New Lead] %s %s — %s', $data['first_name'], $data['last_name'], $data['state']);

    $body  = "A new eligibility application has been received.\n\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "CONTACT INFORMATION\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "Name:  " . $data['first_name'] . " " . $data['last_name'] . "\n";
    $body .= "Email: " . $data['email'] . "\n";
    $body .= "Phone: " . $data['phone'] . "\n";
    $body .= "State: " . $data['state'] . "\n\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "LOAN INFORMATION\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "Loan type:       " . $data['loan_type'] . "\n";
    $body .= "Loan amount:     " . $data['loan_amount'] . "\n";
    $body .= "Monthly payment: " . ($data['monthly_payment'] ?: '(not provided)') . "\n\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "METADATA\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "Submitted at: " . current_time('Y-m-d H:i:s T') . "\n";
    $body .= "IP address:   " . psla_get_client_ip() . "\n";
    $body .= "Source page:  " . esc_url_raw($_SERVER['HTTP_REFERER'] ?? 'direct') . "\n\n";
    $body .= "─────────────────────────────────────────────\n";
    $body .= "Sent from privatestudentloanaid.com";

    // SIN "From:" — SiteMailer usa su sender autorizado
    $headers = [
        'Content-Type: text/plain; charset=UTF-8',
        'Reply-To: ' . $data['first_name'] . ' ' . $data['last_name'] . ' <' . $data['email'] . '>',
    ];

    $recipients = explode(',', PSLA_LEAD_RECIPIENTS);
    $sent = wp_mail($recipients, $subject, $body, $headers);

    psla_save_lead_to_db('apply', $data, $sent);

    if ($sent) {
        wp_send_json_success([
            'ok'       => true,
            'redirect' => 'https://privatestudentloanaid.com/thank-you/',
            'message'  => 'Application received. Redirecting…',
        ]);
    } else {
        // Fallback: mostrar éxito de todos modos porque el lead SÍ quedó guardado en la BD
        // El equipo lo verá en WP Admin → PSLA Leads y podrá contactar al prospecto
        wp_send_json_success([
            'ok'       => true,
            'redirect' => 'https://privatestudentloanaid.com/thank-you/',
            'message'  => 'Application received.',
            'warning'  => 'email_failed',
        ]);
    }
}


/* ================================================================
 * 2) HANDLER — /contact/
 * ================================================================ */
add_action('wp_ajax_psla_submit_contact',        'psla_handle_contact_submission');
add_action('wp_ajax_nopriv_psla_submit_contact', 'psla_handle_contact_submission');

function psla_handle_contact_submission() {

    if (!empty($_POST['website_url'])) {
        wp_send_json_success(['ok' => true]);
    }

    if (!psla_check_rate_limit('contact', 5)) {
        wp_send_json_error(['message' => 'Too many submissions. Please try again later.']);
    }

    $data = [
        'name'         => sanitize_text_field($_POST['name']         ?? ''),
        'email'        => sanitize_email(     $_POST['email']        ?? ''),
        'phone'        => sanitize_text_field($_POST['phone']        ?? ''),
        'inquiry_type' => sanitize_text_field($_POST['inquiry_type'] ?? ''),
        'message'      => sanitize_textarea_field($_POST['message']  ?? ''),
    ];

    foreach (['name', 'email', 'inquiry_type', 'message'] as $field) {
        if (empty($data[$field])) {
            wp_send_json_error(['message' => 'Please complete all required fields.']);
        }
    }
    if (!is_email($data['email'])) {
        wp_send_json_error(['message' => 'Please enter a valid email address.']);
    }
    if (strlen($data['message']) < 20) {
        wp_send_json_error(['message' => 'Please write at least 20 characters in your message.']);
    }

    $subject = sprintf('[Contact form] %s — %s', $data['inquiry_type'], $data['name']);

    $body  = "A new contact form message has been received.\n\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "SENDER\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "Name:         " . $data['name'] . "\n";
    $body .= "Email:        " . $data['email'] . "\n";
    $body .= "Phone:        " . ($data['phone'] ?: '(not provided)') . "\n";
    $body .= "Inquiry type: " . $data['inquiry_type'] . "\n\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "MESSAGE\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= $data['message'] . "\n\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "METADATA\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "Submitted at: " . current_time('Y-m-d H:i:s T') . "\n";
    $body .= "IP address:   " . psla_get_client_ip() . "\n";
    $body .= "Source page:  " . esc_url_raw($_SERVER['HTTP_REFERER'] ?? 'direct') . "\n\n";
    $body .= "─────────────────────────────────────────────\n";
    $body .= "Sent from privatestudentloanaid.com/contact/";

    // SIN "From:" — SiteMailer usa su sender autorizado
    $headers = [
        'Content-Type: text/plain; charset=UTF-8',
        'Reply-To: ' . $data['name'] . ' <' . $data['email'] . '>',
    ];

    $recipients = explode(',', PSLA_LEAD_RECIPIENTS);
    $sent = wp_mail($recipients, $subject, $body, $headers);

    psla_save_lead_to_db('contact', $data, $sent);

    // Éxito garantizado (el lead ya está en la BD como respaldo)
    wp_send_json_success([
        'ok'      => true,
        'message' => 'Message received. We will reply within 24 business hours.',
        'warning' => $sent ? null : 'email_failed',
    ]);
}


/* ================================================================
 * 3) HANDLER — /do-not-sell-or-share/
 * ================================================================ */
add_action('wp_ajax_psla_submit_privacy',        'psla_handle_privacy_submission');
add_action('wp_ajax_nopriv_psla_submit_privacy', 'psla_handle_privacy_submission');

function psla_handle_privacy_submission() {

    if (!empty($_POST['website_url'])) {
        wp_send_json_success(['ok' => true]);
    }

    if (!psla_check_rate_limit('privacy', 3)) {
        wp_send_json_error(['message' => 'Too many submissions. Please try again later.']);
    }

    $rights_raw = $_POST['rights'] ?? '[]';
    $rights = json_decode(wp_unslash($rights_raw), true);
    if (!is_array($rights)) { $rights = []; }
    $rights = array_map('sanitize_text_field', $rights);

    $data = [
        'name'    => sanitize_text_field($_POST['name']    ?? ''),
        'email'   => sanitize_email(     $_POST['email']   ?? ''),
        'phone'   => sanitize_text_field($_POST['phone']   ?? ''),
        'state'   => sanitize_text_field($_POST['state']   ?? ''),
        'rights'  => $rights,
        'details' => sanitize_textarea_field($_POST['details'] ?? ''),
    ];

    foreach (['name', 'email', 'state'] as $field) {
        if (empty($data[$field])) {
            wp_send_json_error(['message' => 'Please complete all required fields.']);
        }
    }
    if (!is_email($data['email'])) {
        wp_send_json_error(['message' => 'Please enter a valid email address.']);
    }
    if (empty($data['rights'])) {
        wp_send_json_error(['message' => 'Please select at least one right you wish to exercise.']);
    }

    $subject = '[Privacy Request] ' . $data['name'] . ' — ' . $data['state'];

    $body  = "A new CCPA / Do Not Sell privacy request has been received.\n\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "REQUESTOR\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "Name:  " . $data['name'] . "\n";
    $body .= "Email: " . $data['email'] . "\n";
    $body .= "Phone: " . ($data['phone'] ?: '(not provided)') . "\n";
    $body .= "State: " . $data['state'] . "\n\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "RIGHTS REQUESTED\n";
    $body .= "════════════════════════════════════════════\n";
    foreach ($data['rights'] as $right) {
        $body .= "  • " . $right . "\n";
    }
    $body .= "\n════════════════════════════════════════════\n";
    $body .= "ADDITIONAL DETAILS\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= ($data['details'] ?: '(none provided)') . "\n\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "METADATA\n";
    $body .= "════════════════════════════════════════════\n";
    $body .= "Submitted at: " . current_time('Y-m-d H:i:s T') . "\n";
    $body .= "IP address:   " . psla_get_client_ip() . "\n";
    $body .= "Source page:  " . esc_url_raw($_SERVER['HTTP_REFERER'] ?? 'direct') . "\n\n";
    $body .= "─────────────────────────────────────────────\n";
    $body .= "ACTION REQUIRED: process this request within 45 days per CCPA § 1798.130.";

    // SIN "From:" — SiteMailer usa su sender autorizado
    $headers = [
        'Content-Type: text/plain; charset=UTF-8',
        'Reply-To: ' . $data['name'] . ' <' . $data['email'] . '>',
    ];

    $recipients = explode(',', PSLA_LEAD_RECIPIENTS);
    $sent = wp_mail($recipients, $subject, $body, $headers);

    psla_save_lead_to_db('privacy', $data, $sent);

    wp_send_json_success([
        'ok'      => true,
        'message' => 'Privacy request received. We will respond within 45 days per CCPA.',
        'warning' => $sent ? null : 'email_failed',
    ]);
}


/* ================================================================
 * PING ENDPOINT — para verificar si el snippet está activo.
 * Visitá: /wp-admin/admin-ajax.php?action=psla_ping
 * Debe devolver JSON con {"success":true,"data":{"pong":true,"version":"v3"}}
 * Si devuelve "0" → el snippet NO está activo en functions.php
 * ================================================================ */
add_action('wp_ajax_psla_ping',        'psla_ping_handler');
add_action('wp_ajax_nopriv_psla_ping', 'psla_ping_handler');
function psla_ping_handler() {
    wp_send_json_success([
        'pong'    => true,
        'version' => 'v3',
        'time'    => current_time('Y-m-d H:i:s T'),
        'from_name' => PSLA_FROM_NAME,
        'recipients_count' => count(explode(',', PSLA_LEAD_RECIPIENTS)),
    ]);
}


/* ================================================================
 * TEST ENDPOINT — para diagnosticar wp_mail()
 * Visita: /wp-admin/admin-ajax.php?action=psla_test_mail
 * (Debes estar logeado como admin)
 * ================================================================ */
add_action('wp_ajax_psla_test_mail', function() {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Unauthorized']);
    }
    $to = wp_get_current_user()->user_email;
    $subject = '[PSLA Test] wp_mail test — ' . current_time('H:i:s');
    $body = "Este es un email de prueba desde el snippet PSLA.\n\nSi ves esto, wp_mail() y SiteMailer están funcionando correctamente.\n\nSitio: " . home_url();
    $headers = ['Content-Type: text/plain; charset=UTF-8'];
    $sent = wp_mail($to, $subject, $body, $headers);
    wp_send_json([
        'sent' => $sent,
        'to'   => $to,
        'note' => $sent ? 'Email enviado. Revisa tu bandeja de ' . $to : 'wp_mail() retornó false. Revisa debug.log',
    ]);
});