<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /includes/class-abandoned-cart.php
// Description: WooCommerce abandoned cart recovery - capture, three-email sequence, open tracking, cart restore - NUCLEAR+++
// Last Edited: 2026-05-09
// ==================================================
namespace AutoMarketerAI;

defined('ABSPATH') || exit;

final class AbandonedCart
{
    private const OPTION_ACTIVE  = 'amai_abandoned_cart_active';
    private const CRON_HOOK      = 'amai_abandoned_cart_check';
    private const TRACK_ACTION   = 'amai_cart_open';

    // Nudge timing in seconds from cart creation
    private const NUDGE_1_DELAY  = 3600;       // 1 hour
    private const NUDGE_2_DELAY  = 86400;      // 24 hours
    private const NUDGE_3_DELAY  = 259200;     // 72 hours

    // ---------------------------------------------------------------------------
    // Boot
    // ---------------------------------------------------------------------------

    public static function init(): void
    {
        if (!self::isActive()) {
            return;
        }

        if (!self::isWooActive()) {
            return;
        }

        add_action('woocommerce_checkout_init', [self::class, 'captureCart']);
        add_action('woocommerce_checkout_order_created', [self::class, 'markRecovered']);
        add_action('woocommerce_order_status_processing', [self::class, 'markRecoveredById']);
        add_action('woocommerce_order_status_completed',  [self::class, 'markRecoveredById']);
        add_action('wp_ajax_nopriv_' . self::TRACK_ACTION, [self::class, 'trackOpen']);
        add_action('wp_ajax_' . self::TRACK_ACTION,        [self::class, 'trackOpen']);
        add_action('template_redirect', [self::class, 'handleCartRestore']);
        add_action('template_redirect', [self::class, 'handleUnsubscribe']);

        if (!wp_next_scheduled(self::CRON_HOOK)) {
            wp_schedule_event(time(), 'every_five_minutes', self::CRON_HOOK);
        }

        add_action(self::CRON_HOOK, [self::class, 'processPending']);
    }

    public static function activate(): void
    {
        update_option(self::OPTION_ACTIVE, '1');
        if (!wp_next_scheduled(self::CRON_HOOK)) {
            wp_schedule_event(time(), 'every_five_minutes', self::CRON_HOOK);
        }
    }

    public static function deactivate(): void
    {
        update_option(self::OPTION_ACTIVE, '0');
        $ts = wp_next_scheduled(self::CRON_HOOK);
        if ($ts !== false) {
            wp_unschedule_event($ts, self::CRON_HOOK);
        }
    }

    // ---------------------------------------------------------------------------
    // Helpers
    // ---------------------------------------------------------------------------

    private static function isActive(): bool
    {
        return get_option(self::OPTION_ACTIVE, '0') === '1';
    }

    private static function isWooActive(): bool
    {
        return class_exists('WooCommerce');
    }

    // ---------------------------------------------------------------------------
    // Capture cart when customer reaches checkout
    // ---------------------------------------------------------------------------

    public static function captureCart(): void
    {
        if (!is_checkout()) {
            return;
        }

        $email = '';

        if (is_user_logged_in()) {
            $user  = wp_get_current_user();
            $email = (string) $user->user_email;
        }

        if ($email === '' && isset($_POST['billing_email'])) {
            $email = sanitize_email((string) wp_unslash($_POST['billing_email']));
        }

        if ($email === '' || !is_email($email)) {
            return;
        }

        $cart = WC()->cart;
        if (!$cart || $cart->is_empty()) {
            return;
        }

        $first_name = '';
        if (is_user_logged_in()) {
            $user       = wp_get_current_user();
            $first_name = (string) $user->first_name;
            if ($first_name === '') {
                $first_name = (string) $user->display_name;
            }
        }
        if ($first_name === '' && isset($_POST['billing_first_name'])) {
            $first_name = sanitize_text_field((string) wp_unslash($_POST['billing_first_name']));
        }


        $phone = '';
        if (isset($_POST['billing_phone'])) {
            $phone = sanitize_text_field((string) wp_unslash($_POST['billing_phone']));
        }
        if ($phone === '' && is_user_logged_in()) {
            $phone = (string) get_user_meta(get_current_user_id(), 'billing_phone', true);
        }
        $items = [];
        foreach ($cart->get_cart() as $item) {
            $product = $item['data'] ?? null;
            if (!$product instanceof \WC_Product) {
                continue;
            }
            $items[] = [
                'product_id' => (int) $product->get_id(),
                'name'       => $product->get_name(),
                'qty'        => (int) $item['quantity'],
                'price'      => wc_price($product->get_price()),
                'image'      => wp_get_attachment_url((int) $product->get_image_id()) ?: '',
            ];
        }

        if (empty($items)) {
            return;
        }

        $cart_total_raw = (float) $cart->get_cart_contents_total();
        $cart_total     = $cart->get_cart_total();
        $checkout_url   = wc_get_checkout_url();

        global $wpdb;
        $table = $wpdb->prefix . 'amai_abandoned_carts';

        $wpdb->query(
            $wpdb->prepare(
                "UPDATE `{$table}` SET `status` = 'cancelled' WHERE `email` = %s AND `status` = 'pending'",
                $email
            )
        );

        $wpdb->query(
            $wpdb->prepare(
                "INSERT INTO `{$table}` (`email`, `phone`, `first_name`, `cart_contents`, `cart_total`, `cart_total_raw`, `checkout_url`, `status`, `unsubscribe_token`, `created_at`)" .
                " VALUES (%s, %s, %s, %s, %s, %f, %s, 'pending', %s, %s)",
                $email,
                $phone,
                $first_name,
                (string) json_encode($items),
                strip_tags($cart_total),
                $cart_total_raw,
                $checkout_url,
                bin2hex(random_bytes(32)),
                gmdate('Y-m-d H:i:s')
            )
        );
    }

    // ---------------------------------------------------------------------------
    // Cart restore endpoint
    // Rebuilds a dead WC session from stored cart JSON, applies coupon if present,
    // then redirects straight to checkout. Used by nudge 3 CTA.
    // ---------------------------------------------------------------------------

    public static function handleCartRestore(): void
    {
        if (!isset($_GET['amai_restore_cart'])) {
            return;
        }

        $token = (string) $_GET['amai_restore_cart'];

        if ($token === '' || !preg_match('/^[0-9a-f]{64}$/', $token)) {
            wp_die('Invalid restore link.', 'Invalid Link', ['response' => 400]);
        }

        global $wpdb;
        $table = $wpdb->prefix . 'amai_abandoned_carts';

        $row = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT `id`, `email`, `cart_contents`, `status` FROM `{$table}` WHERE `unsubscribe_token` = %s LIMIT 1",
                $token
            ),
            ARRAY_A
        );

        if (!is_array($row)) {
            wp_die('Cart not found.', 'Not Found', ['response' => 404]);
        }

        $email = (string) ($row['email'] ?? '');

        // Magic login -- if a login token is present and valid, log the user in
        $login_token = isset($_GET['lt']) ? sanitize_text_field((string) $_GET['lt']) : '';
        if ($login_token !== '' && !is_user_logged_in()) {
            $stored = get_transient('amai_cart_lt_' . $login_token);
            if ($stored !== false && is_email((string) $stored)) {
                $user = get_user_by('email', (string) $stored);
                if ($user instanceof WP_User) {
                    wp_set_current_user($user->ID);
                    wp_set_auth_cookie($user->ID, true);
                }
            }
            delete_transient('amai_cart_lt_' . $login_token);
        }

        $items = json_decode((string) $row['cart_contents'], true);
        if (!is_array($items) || empty($items)) {
            wp_redirect(wc_get_checkout_url());
            exit;
        }

        WC()->cart->empty_cart();

        foreach ($items as $item) {
            $product_id = (int) ($item['product_id'] ?? 0);
            $qty        = (int) ($item['qty'] ?? 1);
            if ($product_id > 0 && $qty > 0) {
                WC()->cart->add_to_cart($product_id, $qty);
            }
        }

        $coupon = isset($_GET['coupon']) ? sanitize_text_field((string) $_GET['coupon']) : '';
        if ($coupon !== '' && preg_match('/^RECOVER-[A-F0-9]{8}$/', $coupon)) {
            WC()->cart->apply_coupon($coupon);
        }

        // Guest shoppers: pre-fill billing email at checkout so session sticks
        $checkout_url = wc_get_checkout_url();
        if (!is_user_logged_in() && $email !== '') {
            $checkout_url = add_query_arg('billing_email', rawurlencode($email), $checkout_url);
        }
        wp_redirect($checkout_url);
        exit;
    }

    // ---------------------------------------------------------------------------
    // Mark cart recovered when an order is placed
    // ---------------------------------------------------------------------------

    public static function markRecovered(): void
    {
        $email = isset($_POST['billing_email'])
            ? sanitize_email((string) wp_unslash($_POST['billing_email']))
            : '';

        if ($email === '' && is_user_logged_in()) {
            $email = (string) wp_get_current_user()->user_email;
        }

        if ($email === '') {
            return;
        }

        self::cancelByEmail($email);
    }

    public static function markRecoveredById(int $order_id): void
    {
        $order = wc_get_order($order_id);
        if (!$order instanceof \WC_Order) {
            return;
        }

        $email = $order->get_billing_email();
        if ($email === '') {
            return;
        }

        global $wpdb;
        $table = $wpdb->prefix . 'amai_abandoned_carts';

        $wpdb->query(
            $wpdb->prepare(
                "UPDATE `{$table}` SET `status` = 'recovered' WHERE `email` = %s AND `status` IN ('pending','sent')",
                $email
            )
        );
        if ($wpdb->rows_affected > 0) {
            self::sendRecoveryNotification($email, $order);
        }
    }

    // ---------------------------------------------------------------------------
    // Admin notification on cart recovery
    // ---------------------------------------------------------------------------

    public static function sendRecoveryNotification(string $customer_email, \WC_Order $order): void
    {
        $admin_email = defined('AMAI_SMTP_FROM') ? AMAI_SMTP_FROM : (string) get_option('admin_email');
        $store_name  = get_bloginfo('name');
        $first_name  = (string) $order->get_billing_first_name();
        $last_name   = (string) $order->get_billing_last_name();
        $total       = (string) $order->get_formatted_order_total();
        $order_id    = (int) $order->get_id();
        $order_url   = (string) $order->get_edit_order_url();
        $recovered   = gmdate('Y-m-d H:i:s');

        $subject = 'Recovered cart: ' . trim($first_name . ' ' . $last_name) . ' (' . $total . ')';

        $html  = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"></head><body style="margin:0;padding:32px 24px;background:#F9FAFB;font-family:Arial,sans-serif;">';
        $html .= '<table width="100%" cellpadding="0" cellspacing="0"><tr><td align="center">';
        $html .= '<table width="480" cellpadding="0" cellspacing="0" style="background:#fff;border:1.5px solid #E7DDD5;border-radius:16px;padding:32px 36px;">';
        $html .= '<tr><td>';
        $html .= '<p style="margin:0 0 6px;font-size:11px;font-weight:700;letter-spacing:.1em;color:#D97757;text-transform:uppercase;">' . esc_html($store_name) . '</p>';
        $html .= '<h2 style="margin:0 0 20px;font-size:20px;font-weight:800;color:#1C1917;">Cart recovered</h2>';
        $html .= '<p style="margin:0 0 8px;font-size:14px;color:#57534E;"><strong>Customer:</strong> ' . esc_html(trim($first_name . ' ' . $last_name)) . ' &lt;' . esc_html($customer_email) . '&gt;</p>';
        $html .= '<p style="margin:0 0 8px;font-size:14px;color:#57534E;"><strong>Order value:</strong> ' . esc_html($total) . '</p>';
        $html .= '<p style="margin:0 0 8px;font-size:14px;color:#57534E;"><strong>Order ID:</strong> #' . $order_id . '</p>';
        $html .= '<p style="margin:0 0 20px;font-size:14px;color:#57534E;"><strong>Recovered at:</strong> ' . esc_html($recovered) . ' UTC</p>';
        $html .= '<a href="' . esc_url($order_url) . '" style="display:inline-block;background:#D97757;color:#fff;font-size:14px;font-weight:700;text-decoration:none;padding:12px 28px;border-radius:8px;">View order &rarr;</a>';
        $html .= '</td></tr></table></td></tr></table></body></html>';

        wp_mail($admin_email, $subject, $html, [
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . $store_name . ' <' . $admin_email . '>',
        ]);
    }

    private static function cancelByEmail(string $email): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'amai_abandoned_carts';

        $wpdb->query(
            $wpdb->prepare(
                "UPDATE `{$table}` SET `status` = 'cancelled' WHERE `email` = %s AND `status` = 'pending'",
                $email
            )
        );
    }

    // ---------------------------------------------------------------------------
    // Nudge delay in seconds -- reads from wp_options, falls back to constants
    // ---------------------------------------------------------------------------

    private static function nudgeDelay(int $nudge): int
    {
        $map = [
            1 => ['option' => 'amai_cart_nudge_1_hours', 'default' => self::NUDGE_1_DELAY],
            2 => ['option' => 'amai_cart_nudge_2_hours', 'default' => self::NUDGE_2_DELAY],
            3 => ['option' => 'amai_cart_nudge_3_hours', 'default' => self::NUDGE_3_DELAY],
        ];
        if (!isset($map[$nudge])) {
            return 3600;
        }
        $raw = get_option($map[$nudge]['option'], '');
        if ($raw === '' || !ctype_digit((string) $raw) || (int) $raw < 1) {
            return $map[$nudge]['default'];
        }
        return (int) $raw * 3600;
    }

    // ---------------------------------------------------------------------------
    // Cron: work through the three-nudge sequence for all active carts
    // ---------------------------------------------------------------------------

    public static function processPending(): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'amai_abandoned_carts';
        $now   = time();

        $nudge1_cutoff = gmdate('Y-m-d H:i:s', $now - self::nudgeDelay(1));
        $rows1 = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM `{$table}` WHERE `status` = 'pending' AND `created_at` <= %s AND `nudge_1_sent_at` IS NULL ORDER BY `created_at` ASC LIMIT 20",
                $nudge1_cutoff
            ),
            ARRAY_A
        );
        foreach ($rows1 as $row) {
            self::sendNudge($row, 1);
        }

        $nudge2_cutoff = gmdate('Y-m-d H:i:s', $now - self::nudgeDelay(2));
        $rows2 = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM `{$table}` WHERE `status` = 'sent' AND `created_at` <= %s AND `nudge_1_sent_at` IS NOT NULL AND `nudge_2_sent_at` IS NULL ORDER BY `created_at` ASC LIMIT 20",
                $nudge2_cutoff
            ),
            ARRAY_A
        );
        foreach ($rows2 as $row) {
            self::sendNudge($row, 2);
        }

        $nudge3_cutoff = gmdate('Y-m-d H:i:s', $now - self::nudgeDelay(3));
        $rows3 = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM `{$table}` WHERE `status` = 'sent' AND `created_at` <= %s AND `nudge_2_sent_at` IS NOT NULL AND `nudge_3_sent_at` IS NULL ORDER BY `created_at` ASC LIMIT 20",
                $nudge3_cutoff
            ),
            ARRAY_A
        );
        foreach ($rows3 as $row) {
            self::sendNudge($row, 3);
        }
    }

    // ---------------------------------------------------------------------------
    // Dispatch the correct nudge email and update DB state
    // ---------------------------------------------------------------------------

    private static function sendNudge(array $row, int $nudge): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'amai_abandoned_carts';
        $id    = (int) $row['id'];

        $sent = match ($nudge) {
            1 => self::sendNudge1($row),
            2 => self::sendNudge2($row),
            3 => self::sendNudge3($row),
            default => false,
        };

        if (!$sent) {
            return;
        }

        // Fire SMS nudge alongside email if module is active and phone is available
        $phone = isset($row['phone']) ? (string) $row['phone'] : '';
        if ($phone !== '' && \AutoMarketerAI\SmsProvider::is_ready()) {
            self::sendSmsnudge($row, $nudge);
        }

        $now_str   = gmdate('Y-m-d H:i:s');
        $nudge_col = "nudge_{$nudge}_sent_at";

        if ($nudge === 1) {
            $wpdb->query(
                $wpdb->prepare(
                    "UPDATE `{$table}` SET `status` = 'sent', `sent_at` = %s, `{$nudge_col}` = %s WHERE `id` = %d",
                    $now_str,
                    $now_str,
                    $id
                )
            );
        } else {
            $wpdb->query(
                $wpdb->prepare(
                    "UPDATE `{$table}` SET `{$nudge_col}` = %s WHERE `id` = %d",
                    $now_str,
                    $id
                )
            );
        }
    }

    // ---------------------------------------------------------------------------
    // URL builders
    // ---------------------------------------------------------------------------

    private static function buildUnsubUrl(string $token): string
    {
        return add_query_arg(['amai_cart_unsub' => '1', 'token' => $token], home_url('/'));
    }

    private static function buildRestoreUrl(string $token, string $coupon = '', string $email = ''): string
    {
        $args = ['amai_restore_cart' => $token];
        if ($coupon !== '') {
            $args['coupon'] = $coupon;
        }
        // Generate magic login token for known WP users
        if ($email !== '') {
            $user = get_user_by('email', $email);
            if ($user instanceof WP_User) {
                $lt = bin2hex(random_bytes(16));
                set_transient('amai_cart_lt_' . $lt, $email, 15 * MINUTE_IN_SECONDS);
                $args['lt'] = $lt;
            }
        }
        return add_query_arg($args, home_url('/'));
    }

    // ---------------------------------------------------------------------------
    // Unsubscribe -- cart-specific opt-out only
    // ---------------------------------------------------------------------------

    public static function handleUnsubscribe(): void
    {
        if (!isset($_GET['amai_cart_unsub']) || $_GET['amai_cart_unsub'] !== '1') {
            return;
        }

        $token = isset($_GET['token']) ? (string) $_GET['token'] : '';

        if ($token === '' || !preg_match('/^[0-9a-f]{64}$/', $token)) {
            wp_die('Invalid unsubscribe link.', 'Invalid Link', ['response' => 400]);
        }

        global $wpdb;
        $table = $wpdb->prefix . 'amai_abandoned_carts';

        $row = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT `id`, `status` FROM `{$table}` WHERE `unsubscribe_token` = %s LIMIT 1",
                $token
            ),
            ARRAY_A
        );

        if ($row !== null && (string) $row['status'] === 'pending') {
            $wpdb->query(
                $wpdb->prepare(
                    "UPDATE `{$table}` SET `status` = 'cancelled' WHERE `id` = %d",
                    (int) $row['id']
                )
            );
        }

        $store_name = get_bloginfo('name');

        ?><!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Unsubscribed</title>
<style>body{margin:0;padding:48px 24px;background:#F9FAFB;font-family:Arial,sans-serif;text-align:center;}
.card{display:inline-block;background:#fff;border:1.5px solid #E7DDD5;border-radius:20px;padding:48px 40px;max-width:460px;}
h1{margin:0 0 12px;font-size:24px;font-weight:800;color:#1C1917;}
p{margin:0;font-size:15px;color:#78716C;line-height:1.6;}
.eyebrow{font-size:11px;font-weight:700;letter-spacing:.1em;color:#D97757;text-transform:uppercase;margin:0 0 16px;}
</style></head>
<body><div class="card">
<p class="eyebrow"><?php echo esc_html($store_name); ?></p>
<h1>You're all set.</h1>
<p>We won't send any more cart reminders. If you ever want to come back, you're always welcome.</p>
</div></body></html><?php
        exit;
    }

    // ---------------------------------------------------------------------------
    // Nudge 1 — 1 hour: "Still thinking it over?"
    // ---------------------------------------------------------------------------

    private static function sendNudge1(array $row): bool
    {
        $id           = (int) $row['id'];
        $email        = (string) $row['email'];
        $first_name   = $row['first_name'] !== '' ? (string) $row['first_name'] : 'there';
        $cart_total   = (string) $row['cart_total'];
        $email      = (string) $row['email'];
        $items      = json_decode((string) $row['cart_contents'], true);
        $store_name = get_bloginfo('name');
        $subject    = 'You left something behind';
        $token      = isset($row['unsubscribe_token']) ? (string) $row['unsubscribe_token'] : '';
        $cta_url    = $token !== '' ? self::buildRestoreUrl($token, '', $email) : wc_get_checkout_url();
        $track_url  = add_query_arg(['action' => self::TRACK_ACTION, 'cid' => $id], admin_url('admin-ajax.php'));
        $unsub_url  = $token !== '' ? self::buildUnsubUrl($token) : '';

        if (!is_array($items)) {
            $items = [];
        }

        ob_start();
        ?><!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?php echo esc_html($subject); ?></title></head>
<body style="margin:0;padding:0;background:#F9FAFB;font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#F9FAFB;padding:48px 0;">
  <tr><td align="center">
    <table width="520" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:20px;border:1.5px solid #E7DDD5;overflow:hidden;">
      <tr><td style="padding:40px 40px 28px;text-align:center;">
        <p style="margin:0 0 14px;font-size:11px;font-weight:700;letter-spacing:.1em;color:#D97757;text-transform:uppercase;"><?php echo esc_html($store_name); ?></p>
        <h1 style="margin:0 0 12px;font-size:26px;font-weight:800;color:#1C1917;line-height:1.2;">Still thinking it over?</h1>
        <p style="margin:0;font-size:15px;color:#78716C;line-height:1.6;">Hi <?php echo esc_html($first_name); ?>, looks like you got distracted - no worries. Your cart is saved and ready whenever you are.</p>
      </td></tr>
      <tr><td style="padding:0 40px;"><div style="height:1px;background:#E7DDD5;"></div></td></tr>
      <?php if (!empty($items)): ?>
      <tr><td style="padding:28px 40px 0;">
        <p style="margin:0 0 16px;font-size:11px;font-weight:700;letter-spacing:.08em;color:#A8A29E;text-transform:uppercase;">Your cart</p>
        <table width="100%" cellpadding="0" cellspacing="0">
          <?php foreach ($items as $item): ?>
          <tr><td style="padding:0 0 14px;vertical-align:top;">
            <table width="100%" cellpadding="0" cellspacing="0"><tr>
              <?php if (!empty($item['image'])): ?>
              <td style="width:52px;padding-right:14px;vertical-align:top;"><img src="<?php echo esc_url($item['image']); ?>" width="52" height="52" style="border-radius:8px;object-fit:cover;display:block;" alt=""></td>
              <?php endif; ?>
              <td style="vertical-align:middle;">
                <p style="margin:0 0 3px;font-size:14px;font-weight:600;color:#1C1917;"><?php echo esc_html($item['name']); ?></p>
                <p style="margin:0;font-size:13px;color:#78716C;">Qty: <?php echo (int) $item['qty']; ?> &nbsp;&middot;&nbsp; <?php echo wp_kses_post($item['price']); ?></p>
              </td>
            </tr></table>
          </td></tr>
          <?php endforeach; ?>
        </table>
      </td></tr>
      <?php endif; ?>
      <tr><td style="padding:16px 40px 28px;">
        <table width="100%" cellpadding="0" cellspacing="0" style="background:#F9FAFB;border:1.5px solid #E7DDD5;border-radius:12px;padding:14px 18px;">
          <tr>
            <td><p style="margin:0;font-size:13px;color:#78716C;">Cart total</p></td>
            <td align="right"><p style="margin:0;font-size:15px;font-weight:700;color:#1C1917;"><?php echo esc_html($cart_total); ?></p></td>
          </tr>
        </table>
      </td></tr>
      <tr><td style="padding:0 40px;"><div style="height:1px;background:#E7DDD5;"></div></td></tr>
      <tr><td style="padding:32px 40px;text-align:center;">
        <p style="margin:0 0 20px;font-size:15px;color:#57534E;line-height:1.6;">Whenever you're ready, your cart is right where you left it.</p>
        <a href="<?php echo esc_url($cta_url); ?>" style="display:inline-block;background:#D97757;color:#ffffff;font-size:15px;font-weight:700;text-decoration:none;padding:14px 36px;border-radius:10px;">Return to your cart &rarr;</a>
      </td></tr>
      <tr><td style="padding:24px 40px;border-top:1.5px solid #E7DDD5;text-align:center;">
        <p style="margin:0 0 12px;font-size:13px;color:#78716C;">Questions? Reply to this email - we're happy to help.</p>
        <?php if ($unsub_url !== ''): ?>
        <p style="margin:8px 0 4px;"><a href="<?php echo esc_url($unsub_url); ?>" style="font-size:13px;color:#A8A29E;text-decoration:underline;">Don't want cart reminders? Unsubscribe here.</a></p>
        <?php endif; ?>
        <p style="margin:0;font-size:12px;color:#A8A29E;"><?php echo esc_html($store_name); ?></p>
      </td></tr>
    </table>
  </td></tr>
</table>
<img src="<?php echo esc_url($track_url); ?>" width="1" height="1" alt="" style="display:none;">
</body></html><?php
        $html = (string) ob_get_clean();
        return self::mail($email, $subject, $html, $store_name);
    }

    // ---------------------------------------------------------------------------
    // Nudge 2 — 24 hours: "In case life got busy"
    // ---------------------------------------------------------------------------

    private static function sendNudge2(array $row): bool
    {
        $id           = (int) $row['id'];
        $email        = (string) $row['email'];
        $first_name   = $row['first_name'] !== '' ? (string) $row['first_name'] : 'there';
        $cart_total   = (string) $row['cart_total'];
        $email      = (string) $row['email'];
        $items      = json_decode((string) $row['cart_contents'], true);
        $store_name = get_bloginfo('name');
        $opened     = ((int) $row['open_count']) > 0;
        $subject    = $opened ? 'We saw you come back - still thinking it over?' : 'Your cart is still here';
        $token      = isset($row['unsubscribe_token']) ? (string) $row['unsubscribe_token'] : '';
        $cta_url    = $token !== '' ? self::buildRestoreUrl($token, '', $email) : wc_get_checkout_url();
        $track_url  = add_query_arg(['action' => self::TRACK_ACTION, 'cid' => $id], admin_url('admin-ajax.php'));
        $unsub_url  = $token !== '' ? self::buildUnsubUrl($token) : '';

        if (!is_array($items)) {
            $items = [];
        }

        ob_start();
        ?><!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?php echo esc_html($subject); ?></title></head>
<body style="margin:0;padding:0;background:#F9FAFB;font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#F9FAFB;padding:48px 0;">
  <tr><td align="center">
    <table width="520" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:20px;border:1.5px solid #E7DDD5;overflow:hidden;">
      <tr><td style="padding:40px 40px 28px;text-align:center;">
        <p style="margin:0 0 14px;font-size:11px;font-weight:700;letter-spacing:.1em;color:#D97757;text-transform:uppercase;"><?php echo esc_html($store_name); ?></p>
        <h1 style="margin:0 0 12px;font-size:26px;font-weight:800;color:#1C1917;line-height:1.2;"><?php echo $opened ? 'Good to see you again' : 'In case life got busy'; ?></h1>
        <p style="margin:0;font-size:15px;color:#78716C;line-height:1.6;">Hi <?php echo esc_html($first_name); ?>, <?php echo $opened ? 'you came back for a look - we noticed. Your cart is still right here whenever you\'re ready to pull the trigger.' : 'your cart is still saved from yesterday. Totally fine if you need more time - just didn\'t want it to disappear on you.'; ?></p>
      </td></tr>
      <tr><td style="padding:0 40px;"><div style="height:1px;background:#E7DDD5;"></div></td></tr>
      <?php if (!empty($items)): ?>
      <tr><td style="padding:28px 40px 0;">
        <p style="margin:0 0 16px;font-size:11px;font-weight:700;letter-spacing:.08em;color:#A8A29E;text-transform:uppercase;">Still in your cart</p>
        <table width="100%" cellpadding="0" cellspacing="0">
          <?php foreach ($items as $item): ?>
          <tr><td style="padding:0 0 14px;vertical-align:top;">
            <table width="100%" cellpadding="0" cellspacing="0"><tr>
              <?php if (!empty($item['image'])): ?>
              <td style="width:52px;padding-right:14px;vertical-align:top;"><img src="<?php echo esc_url($item['image']); ?>" width="52" height="52" style="border-radius:8px;object-fit:cover;display:block;" alt=""></td>
              <?php endif; ?>
              <td style="vertical-align:middle;">
                <p style="margin:0 0 3px;font-size:14px;font-weight:600;color:#1C1917;"><?php echo esc_html($item['name']); ?></p>
                <p style="margin:0;font-size:13px;color:#78716C;">Qty: <?php echo (int) $item['qty']; ?> &nbsp;&middot;&nbsp; <?php echo wp_kses_post($item['price']); ?></p>
              </td>
            </tr></table>
          </td></tr>
          <?php endforeach; ?>
        </table>
      </td></tr>
      <?php endif; ?>
      <tr><td style="padding:16px 40px 28px;">
        <table width="100%" cellpadding="0" cellspacing="0" style="background:#F9FAFB;border:1.5px solid #E7DDD5;border-radius:12px;padding:14px 18px;">
          <tr>
            <td><p style="margin:0;font-size:13px;color:#78716C;">Cart total</p></td>
            <td align="right"><p style="margin:0;font-size:15px;font-weight:700;color:#1C1917;"><?php echo esc_html($cart_total); ?></p></td>
          </tr>
        </table>
      </td></tr>
      <tr><td style="padding:0 40px;"><div style="height:1px;background:#E7DDD5;"></div></td></tr>
      <tr><td style="padding:32px 40px;text-align:center;">
        <p style="margin:0 0 8px;font-size:15px;color:#57534E;line-height:1.6;">Have a question before you decide? Just reply - we read every one.</p>
        <p style="margin:0 0 20px;font-size:15px;color:#57534E;line-height:1.6;">Otherwise, your cart is ready when you are.</p>
        <a href="<?php echo esc_url($cta_url); ?>" style="display:inline-block;background:#D97757;color:#ffffff;font-size:15px;font-weight:700;text-decoration:none;padding:14px 36px;border-radius:10px;">Pick up where you left off &rarr;</a>
      </td></tr>
      <tr><td style="padding:24px 40px;border-top:1.5px solid #E7DDD5;text-align:center;">
        <p style="margin:0 0 12px;font-size:13px;color:#78716C;">Questions? Just reply to this email.</p>
        <?php if ($unsub_url !== ''): ?>
        <p style="margin:8px 0 4px;"><a href="<?php echo esc_url($unsub_url); ?>" style="font-size:13px;color:#A8A29E;text-decoration:underline;">Don't want cart reminders? Unsubscribe here.</a></p>
        <?php endif; ?>
        <p style="margin:0;font-size:12px;color:#A8A29E;"><?php echo esc_html($store_name); ?></p>
      </td></tr>
    </table>
  </td></tr>
</table>
<img src="<?php echo esc_url($track_url); ?>" width="1" height="1" alt="" style="display:none;">
</body></html><?php
        $html = (string) ob_get_clean();
        return self::mail($email, $subject, $html, $store_name);
    }

    // ---------------------------------------------------------------------------
    // Generate a single-use WooCommerce recovery coupon
    // ---------------------------------------------------------------------------

    private static function generateRecoveryCoupon(string $email, int $pct, int $days): string
    {
        $code   = 'RECOVER-' . strtoupper(substr(md5($email . microtime()), 0, 8));
        $expiry = gmdate('Y-m-d', strtotime('+' . $days . ' days'));
        $coupon = new \WC_Coupon();
        $coupon->set_code($code);
        $coupon->set_discount_type('percent');
        $coupon->set_amount((float) $pct);
        $coupon->set_usage_limit(1);
        $coupon->set_usage_limit_per_user(1);
        $coupon->set_date_expires(strtotime($expiry));
        $coupon->set_email_restrictions([$email]);
        $coupon->set_individual_use(true);
        $coupon->save();
        return $code;
    }

    // ---------------------------------------------------------------------------
    // Nudge 3 — 72 hours: "We'll get out of your hair after this"
    // CTA uses restore URL to rebuild the dead WC session and apply any coupon.
    // ---------------------------------------------------------------------------

    private static function sendNudge3(array $row): bool
    {
        $id               = (int) $row['id'];
        $email            = (string) $row['email'];
        $first_name       = $row['first_name'] !== '' ? (string) $row['first_name'] : 'there';
        $cart_total       = (string) $row['cart_total'];
        $items            = json_decode((string) $row['cart_contents'], true);
        $store_name       = get_bloginfo('name');
        $token            = isset($row['unsubscribe_token']) ? (string) $row['unsubscribe_token'] : '';
        $opened           = ((int) $row['open_count']) > 0;
        $subject          = $opened ? 'One last thing before we go' : 'Last one from us - promise';
        $discount_enabled = get_option('amai_cart_recovery_discount_enabled', '0') === '1';
        $discount_pct     = (int) get_option('amai_cart_recovery_discount_pct', '10');
        $discount_days    = (int) get_option('amai_cart_recovery_discount_days', '3');
        $coupon_code      = '';
        $coupon_expiry    = '';

        if ($discount_enabled && $email !== '' && function_exists('wc_get_order')) {
            $coupon_code   = self::generateRecoveryCoupon($email, $discount_pct, $discount_days);
            $coupon_expiry = gmdate('F j, Y', strtotime('+' . $discount_days . ' days'));
        }

        $cta_url   = $token !== '' ? self::buildRestoreUrl($token, $coupon_code, $email) : wc_get_checkout_url();
        $track_url = add_query_arg(['action' => self::TRACK_ACTION, 'cid' => $id], admin_url('admin-ajax.php'));
        $unsub_url = $token !== '' ? self::buildUnsubUrl($token) : '';

        if (!is_array($items)) {
            $items = [];
        }

        ob_start();
        ?><!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?php echo esc_html($subject); ?></title></head>
<body style="margin:0;padding:0;background:#F9FAFB;font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#F9FAFB;padding:48px 0;">
  <tr><td align="center">
    <table width="520" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:20px;border:1.5px solid #E7DDD5;overflow:hidden;">
      <tr><td style="padding:40px 40px 28px;text-align:center;">
        <p style="margin:0 0 14px;font-size:11px;font-weight:700;letter-spacing:.1em;color:#D97757;text-transform:uppercase;"><?php echo esc_html($store_name); ?></p>
        <h1 style="margin:0 0 12px;font-size:26px;font-weight:800;color:#1C1917;line-height:1.2;"><?php echo $opened ? 'You looked. We noticed.' : 'Last one from us - promise'; ?></h1>
        <p style="margin:0;font-size:15px;color:#78716C;line-height:1.6;">Hi <?php echo esc_html($first_name); ?>, <?php echo $opened ? 'you stopped by but didn\'t finish - and that\'s completely okay. This is the last note we\'ll send. If something held you back, just reply and we\'ll help.' : 'we won\'t keep nudging you after this. If the timing wasn\'t right, that\'s completely fine - no hard feelings at all.'; ?></p>
      </td></tr>
      <tr><td style="padding:0 40px;"><div style="height:1px;background:#E7DDD5;"></div></td></tr>
      <?php if (!empty($items)): ?>
      <tr><td style="padding:28px 40px 0;">
        <p style="margin:0 0 16px;font-size:11px;font-weight:700;letter-spacing:.08em;color:#A8A29E;text-transform:uppercase;">Still saved for you</p>
        <table width="100%" cellpadding="0" cellspacing="0">
          <?php foreach ($items as $item): ?>
          <tr><td style="padding:0 0 14px;vertical-align:top;">
            <table width="100%" cellpadding="0" cellspacing="0"><tr>
              <?php if (!empty($item['image'])): ?>
              <td style="width:52px;padding-right:14px;vertical-align:top;"><img src="<?php echo esc_url($item['image']); ?>" width="52" height="52" style="border-radius:8px;object-fit:cover;display:block;" alt=""></td>
              <?php endif; ?>
              <td style="vertical-align:middle;">
                <p style="margin:0 0 3px;font-size:14px;font-weight:600;color:#1C1917;"><?php echo esc_html($item['name']); ?></p>
                <p style="margin:0;font-size:13px;color:#78716C;">Qty: <?php echo (int) $item['qty']; ?> &nbsp;&middot;&nbsp; <?php echo wp_kses_post($item['price']); ?></p>
              </td>
            </tr></table>
          </td></tr>
          <?php endforeach; ?>
        </table>
      </td></tr>
      <?php endif; ?>
      <tr><td style="padding:16px 40px 28px;">
        <table width="100%" cellpadding="0" cellspacing="0" style="background:#F9FAFB;border:1.5px solid #E7DDD5;border-radius:12px;padding:14px 18px;">
          <tr>
            <td><p style="margin:0;font-size:13px;color:#78716C;">Cart total</p></td>
            <td align="right"><p style="margin:0;font-size:15px;font-weight:700;color:#1C1917;"><?php echo esc_html($cart_total); ?></p></td>
          </tr>
        </table>
      </td></tr>
      <tr><td style="padding:0 40px;"><div style="height:1px;background:#E7DDD5;"></div></td></tr>
      <?php if ($coupon_code !== ''): ?>
      <tr><td style="padding:28px 40px;">
        <table width="100%" cellpadding="0" cellspacing="0" style="background:#FFF8F5;border:1.5px solid #D97757;border-radius:12px;padding:20px 24px;">
          <tr><td style="text-align:center;">
            <p style="margin:0 0 6px;font-size:11px;font-weight:700;letter-spacing:.08em;color:#D97757;text-transform:uppercase;">Your discount</p>
            <p style="margin:0 0 10px;font-size:28px;font-weight:900;color:#1C1917;letter-spacing:.04em;font-family:monospace;"><?php echo esc_html($coupon_code); ?></p>
            <p style="margin:0 0 4px;font-size:14px;color:#57534E;"><?php echo (int) $discount_pct; ?>% off your order - applied automatically at checkout.</p>
            <p style="margin:0;font-size:12px;color:#A8A29E;">Expires <?php echo esc_html($coupon_expiry); ?>. Single use, registered to this email address.</p>
          </td></tr>
        </table>
      </td></tr>
      <?php endif; ?>
      <tr><td style="padding:32px 40px;text-align:center;">
        <p style="margin:0 0 20px;font-size:15px;color:#57534E;line-height:1.6;">If you do want to come back, everything is right where you left it. And if not - thanks for stopping by either way.</p>
        <a href="<?php echo esc_url($cta_url); ?>" style="display:inline-block;background:#D97757;color:#ffffff;font-size:15px;font-weight:700;text-decoration:none;padding:14px 36px;border-radius:10px;"><?php echo $coupon_code !== '' ? 'Use my discount &rarr;' : 'Complete your order &rarr;'; ?></a>
      </td></tr>
      <tr><td style="padding:24px 40px;border-top:1.5px solid #E7DDD5;text-align:center;">
        <p style="margin:0 0 12px;font-size:13px;color:#78716C;">This is the last email we'll send about this cart.</p>
        <?php if ($unsub_url !== ''): ?>
        <p style="margin:8px 0 4px;"><a href="<?php echo esc_url($unsub_url); ?>" style="font-size:13px;color:#A8A29E;text-decoration:underline;">Don't want cart reminders? Unsubscribe here.</a></p>
        <?php endif; ?>
        <p style="margin:0;font-size:12px;color:#A8A29E;"><?php echo esc_html($store_name); ?></p>
      </td></tr>
    </table>
  </td></tr>
</table>
<img src="<?php echo esc_url($track_url); ?>" width="1" height="1" alt="" style="display:none;">
</body></html><?php
        $html = (string) ob_get_clean();
        return self::mail($email, $subject, $html, $store_name);
    }

    // ---------------------------------------------------------------------------
    // Shared mailer
    // ---------------------------------------------------------------------------

    private static function mail(string $to, string $subject, string $html, string $store_name): bool
    {
        return wp_mail($to, $subject, $html, [
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . $store_name . ' <' . (defined('AMAI_SMTP_FROM') ? AMAI_SMTP_FROM : get_option('admin_email')) . '>',
        ]);
    }

    // ---------------------------------------------------------------------------
    // Open tracking pixel
    // ---------------------------------------------------------------------------

    public static function trackOpen(): void
    {
        $cid = isset($_GET['cid']) ? (int) $_GET['cid'] : 0;

        if ($cid > 0) {
            global $wpdb;
            $table = $wpdb->prefix . 'amai_abandoned_carts';

            $row = $wpdb->get_row(
                $wpdb->prepare("SELECT `opened_at`, `open_count` FROM `{$table}` WHERE `id` = %d", $cid),
                ARRAY_A
            );

            if (is_array($row)) {
                if ($row['opened_at'] === null) {
                    $wpdb->query(
                        $wpdb->prepare(
                            "UPDATE `{$table}` SET `opened_at` = %s, `open_count` = 1 WHERE `id` = %d",
                            gmdate('Y-m-d H:i:s'),
                            $cid
                        )
                    );
                } else {
                    $wpdb->query(
                        $wpdb->prepare(
                            "UPDATE `{$table}` SET `open_count` = `open_count` + 1 WHERE `id` = %d",
                            $cid
                        )
                    );
                }
            }
        }

        header('Content-Type: image/gif');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Pragma: no-cache');
        echo "\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00\x21\xf9\x04\x00\x00\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3b";
        exit;
    }

    // ---------------------------------------------------------------------------
    // Stats summary for the stats page header bar
    // ---------------------------------------------------------------------------

    public static function getStats(): array
    {
        global $wpdb;
        $table = $wpdb->prefix . 'amai_abandoned_carts';

        $total_captured = (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$table}`");
        $sent           = (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$table}` WHERE `status` = 'sent'");
        $opened         = (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$table}` WHERE `open_count` > 0");
        $recovered      = (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$table}` WHERE `status` = 'recovered'");
        $revenue_raw    = (float) $wpdb->get_var("SELECT COALESCE(SUM(`cart_total_raw`), 0) FROM `{$table}` WHERE `status` = 'recovered'");

        $open_rate     = $sent > 0 ? round(($opened / $sent) * 100, 1) : 0.0;
        $recovery_rate = $sent > 0 ? round(($recovered / $sent) * 100, 1) : 0.0;

        return [
            'total_captured' => $total_captured,
            'sent'           => $sent,
            'opened'         => $opened,
            'recovered'      => $recovered,
            'open_rate'      => $open_rate,
            'recovery_rate'  => $recovery_rate,
            'revenue_raw'    => $revenue_raw,
        ];
    }

    // ---------------------------------------------------------------------------
    // Paginated record list for the stats page table
    // ---------------------------------------------------------------------------

    public static function getRecords(string $status_filter = 'all', string $date_filter = 'all', int $page = 1, int $per_page = 25): array
    {
        global $wpdb;
        $table  = $wpdb->prefix . 'amai_abandoned_carts';
        $offset = ($page - 1) * $per_page;

        $where_parts = [];
        $args        = [];

        if ($status_filter !== 'all' && in_array($status_filter, ['pending', 'sent', 'opened', 'recovered', 'cancelled'], true)) {
            if ($status_filter === 'opened') {
                $where_parts[] = '`open_count` > 0';
            } else {
                $where_parts[] = '`status` = %s';
                $args[]        = $status_filter;
            }
        }

        if ($date_filter === 'week') {
            $where_parts[] = '`created_at` >= %s';
            $args[]        = gmdate('Y-m-d H:i:s', strtotime('-7 days'));
        } elseif ($date_filter === 'month') {
            $where_parts[] = '`created_at` >= %s';
            $args[]        = gmdate('Y-m-d H:i:s', strtotime('-30 days'));
        }

        $where_sql = !empty($where_parts) ? 'WHERE ' . implode(' AND ', $where_parts) : '';

        $count_sql = "SELECT COUNT(*) FROM `{$table}` {$where_sql}";
        $total     = (int) (!empty($args) ? $wpdb->get_var($wpdb->prepare($count_sql, ...$args)) : $wpdb->get_var($count_sql));

        $args_with_limit   = $args;
        $args_with_limit[] = $per_page;
        $args_with_limit[] = $offset;

        $rows_sql = "SELECT `id`, `email`, `first_name`, `cart_total`, `cart_total_raw`, `status`, `open_count`, `sent_at`, `opened_at`, `created_at`" .
                    " FROM `{$table}` {$where_sql} ORDER BY `created_at` DESC LIMIT %d OFFSET %d";

        $rows = $wpdb->get_results(
            !empty($args_with_limit) ? $wpdb->prepare($rows_sql, ...$args_with_limit) : $wpdb->prepare($rows_sql, $per_page, $offset),
            ARRAY_A
        );

        return [
            'rows'       => is_array($rows) ? $rows : [],
            'total'      => $total,
            'page'       => $page,
            'per_page'   => $per_page,
            'page_count' => (int) ceil($total / $per_page),
        ];
    }

    // ---------------------------------------------------------------------------
    // Test: send a sample nudge email to the given address
    // ---------------------------------------------------------------------------

    public static function sendTestEmail(string $to, string $first_name, int $nudge = 1, bool $opened = false): void
    {
        $checkout_url = home_url('/shop/');
        $row = [
            'id'                => 0,
            'email'             => $to,
            'phone'             => '',
            'first_name'        => $first_name,
            'cart_total'        => '$49.99',
            'checkout_url'      => $checkout_url,
            'unsubscribe_token' => bin2hex(random_bytes(32)),
            'open_count'        => $opened ? 1 : 0,
            'cart_contents'     => json_encode([
                ['product_id' => 0, 'name' => 'Sample Product', 'qty' => 1, 'price' => '$49.99', 'image' => ''],
            ]),
        ];

        match ($nudge) {
            2       => self::sendNudge2($row),
            3       => self::sendNudge3($row),
            default => self::sendNudge1($row),
        };
    }

    // ---------------------------------------------------------------------------
    // Send SMS nudge via Twilio
    // ---------------------------------------------------------------------------

    private static function sendSmsnudge(array $row, int $nudge): void
    {
        $phone      = (string) ($row['phone'] ?? '');
        $first_name = $row['first_name'] !== '' ? (string) $row['first_name'] : 'there';
        $store_name = get_bloginfo('name');
        $email      = (string) ($row['email'] ?? '');
        $token      = isset($row['unsubscribe_token']) ? (string) $row['unsubscribe_token'] : '';

        // Nudge 3 -- apply recovery discount if enabled
        $coupon_code = '';
        if ($nudge === 3) {
            $discount_enabled = get_option('amai_cart_recovery_discount_enabled', '0') === '1';
            $discount_pct     = (int) get_option('amai_cart_recovery_discount_pct', '10');
            $discount_days    = (int) get_option('amai_cart_recovery_discount_days', '3');
            if ($discount_enabled && $email !== '' && function_exists('wc_get_order')) {
                $coupon_code = self::generateRecoveryCoupon($email, $discount_pct, $discount_days);
            }
        }

        $cta_url = $token !== '' ? self::buildRestoreUrl($token, $coupon_code, $email) : wc_get_checkout_url();

        $body = match ($nudge) {
            1 => "{$store_name}: Hi {$first_name}, you left something behind. Tap to finish your order: {$cta_url}",
            2 => "{$store_name}: Still thinking it over, {$first_name}? Your cart is saved: {$cta_url}",
            3 => $coupon_code !== ''
                ? "{$store_name}: Last one, {$first_name}. Here's {$coupon_code} for " . (int) get_option('amai_cart_recovery_discount_pct', '10') . "% off - tap to use it: {$cta_url}"
                : "{$store_name}: Last one, {$first_name}. Your cart is still here: {$cta_url}",
            default => '',
        };

        if ($body === '') {
            return;
        }

        \AutoMarketerAI\SmsProvider::send($phone, $body);
    }
}