<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/templates/woocommerce.php
// Description: WooCommerce Tools hub -- Cart Stats and Settings tabs - NUCLEAR+++
// Last Edited: 2026-05-09
// ==================================================

defined('ABSPATH') || exit;

if (!current_user_can('manage_automarketer_ai')) {
    wp_die('Unauthorized');
}

$tab = sanitize_key((string) ($_GET['tab'] ?? 'stats'));
if (!in_array($tab, ['stats', 'settings', 'store'], true)) {
    $tab = 'stats';
}

$base_url = admin_url('admin.php?page=automarketer-ai-woocommerce');
if ($tab === 'store') {
    wp_enqueue_style(
        'amai-store',
        AMAI_PLUGIN_URL . 'assets/css/store.css',
        [],
        (string) filemtime(AMAI_PLUGIN_DIR . 'assets/css/store.css')
    );
}
?>
<div class="wrap amai-woo-hub-wrap">

    <div class="amai-woo-hub-header">
        <div>
            <h1 class="amai-woo-hub-title">WooCommerce</h1>
            <p class="amai-woo-hub-subtitle">Abandoned cart recovery, product promotion, and store automation.</p>
        </div>
    </div>

    <div class="amai-woo-hub-tabs-wrap">
    <div class="amai-woo-hub-tabs">
        <a href="<?php echo esc_url($base_url . '&tab=stats'); ?>"
           class="amai-woo-hub-tab<?php echo $tab === 'stats' ? ' amai-woo-hub-tab--active' : ''; ?>">
            Cart Stats
        </a>
        <a href="<?php echo esc_url($base_url . '&tab=store'); ?>"
           class="amai-woo-hub-tab<?php echo $tab === 'store' ? ' amai-woo-hub-tab--active' : ''; ?>">
            Product Promotion
        </a>
    </div>
    <a href="<?php echo esc_url($base_url . '&tab=settings'); ?>"
       class="amai-woo-hub-tab amai-woo-hub-tab--right<?php echo $tab === 'settings' ? ' amai-woo-hub-tab--active' : ''; ?>">
        Settings
    </a>
    </div>
    </div>

    <div class="amai-woo-hub-body">

    <?php if (\AutoMarketerAI\Mailer::getActiveProviderId() === '' && (!defined('AMAI_INTERNAL_INSTALL') || !AMAI_INTERNAL_INSTALL)): ?>
    <div class="am-ov-nudge am-ov-nudge--email" style="margin-bottom:24px;">
        <div class="am-ov-nudge-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="20" height="20"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" stroke-linecap="round" stroke-linejoin="round"/><path d="M22 6l-10 7L2 6" stroke-linecap="round" stroke-linejoin="round"/></svg>
        </div>
        <div class="am-ov-nudge-body">
            <strong>No email provider connected</strong>
            <span>Abandoned cart reminders won't send until you connect an email provider. Takes about 2 minutes.</span>
        </div>
        <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-modules')); ?>" class="am-ov-nudge-cta">Set up email &rarr;</a>
    </div>
    <?php endif; ?>

    <?php if ($tab === 'stats'): ?>
        <?php
        $status_filter = isset($_GET['status']) ? sanitize_key((string) $_GET['status']) : 'all';
        $date_filter   = isset($_GET['date'])   ? sanitize_key((string) $_GET['date'])   : 'all';
        $page_num      = isset($_GET['paged'])  ? max(1, (int) $_GET['paged'])           : 1;

        $valid_statuses = ['all', 'pending', 'sent', 'opened', 'recovered', 'cancelled'];
        $valid_dates    = ['all', 'week', 'month'];

        if (!in_array($status_filter, $valid_statuses, true)) { $status_filter = 'all'; }
        if (!in_array($date_filter, $valid_dates, true))       { $date_filter = 'all'; }

        $stats           = AutoMarketerAI\AbandonedCart::getStats();
        $records         = AutoMarketerAI\AbandonedCart::getRecords($status_filter, $date_filter, $page_num);
        $currency_symbol = function_exists('get_woocommerce_currency_symbol') ? get_woocommerce_currency_symbol() : '$';
        $filter_base     = $base_url . '&tab=stats';
        ?>

        <div class="acs-summary-bar">
            <div class="acs-stat-card">
                <div class="acs-stat-value"><?php echo number_format($stats['total_captured']); ?></div>
                <div class="acs-stat-label">Carts Abandoned</div>
            </div>
            <div class="acs-stat-card">
                <div class="acs-stat-value"><?php echo number_format($stats['sent']); ?></div>
                <div class="acs-stat-label">Shoppers Reached</div>
            </div>
            <div class="acs-stat-card">
                <div class="acs-stat-value"><?php echo $stats['open_rate']; ?>%</div>
                <div class="acs-stat-label">Open Rate</div>
                <div class="acs-stat-sub"><?php echo number_format($stats['opened']); ?> opened</div>
            </div>
            <div class="acs-stat-card acs-stat-card--accent">
                <div class="acs-stat-value"><?php echo $stats['recovery_rate']; ?>%</div>
                <div class="acs-stat-label">Recovery Rate</div>
                <div class="acs-stat-sub"><?php echo number_format($stats['recovered']); ?> recovered</div>
            </div>
            <div class="acs-stat-card acs-stat-card--revenue">
                <div class="acs-stat-value"><?php echo esc_html($currency_symbol . number_format($stats['revenue_raw'], 2)); ?></div>
                <div class="acs-stat-label">Revenue Recovered</div>
            </div>
        </div>

        <div class="acs-filters">
            <div class="acs-filter-group">
                <span class="acs-filter-label">Status</span>
                <?php
                $status_options = [
                    'all'       => 'All',
                    'pending'   => 'Pending',
                    'sent'      => 'Sent',
                    'opened'    => 'Email Opened',
                    'recovered' => 'Recovered',
                    'cancelled' => 'Cancelled',
                ];
                foreach ($status_options as $val => $label):
                    $active = $status_filter === $val ? 'acs-filter-btn--active' : '';
                    $href   = esc_url(add_query_arg(['status' => $val, 'date' => $date_filter, 'paged' => 1], $filter_base));
                ?>
                <a href="<?php echo $href; ?>" class="acs-filter-btn <?php echo $active; ?>"><?php echo esc_html($label); ?></a>
                <?php endforeach; ?>
            </div>
            <div class="acs-filter-group">
                <span class="acs-filter-label">Period</span>
                <?php
                $date_options = [
                    'all'   => 'All Time',
                    'month' => 'Last 30 Days',
                    'week'  => 'Last 7 Days',
                ];
                foreach ($date_options as $val => $label):
                    $active = $date_filter === $val ? 'acs-filter-btn--active' : '';
                    $href   = esc_url(add_query_arg(['status' => $status_filter, 'date' => $val, 'paged' => 1], $filter_base));
                ?>
                <a href="<?php echo $href; ?>" class="acs-filter-btn <?php echo $active; ?>"><?php echo esc_html($label); ?></a>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="acs-table-wrap">
            <?php if (empty($records['rows'])): ?>
            <div class="acs-empty">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="acs-empty-icon"><path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4zM3 6h18M16 10a4 4 0 01-8 0" stroke-linecap="round" stroke-linejoin="round"/></svg>
                <p>Nothing here yet - records will show up once shoppers start abandoning carts.</p>
            </div>
            <?php else: ?>
            <table class="acs-table">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Cart Value</th>
                        <th>Status</th>
                        <th>Email Opened</th>
                        <th>Sent</th>
                        <th>Captured</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($records['rows'] as $row):
                        $name     = trim((string) $row['first_name']) !== '' ? esc_html($row['first_name']) : '-';
                        $cart_val = $row['cart_total_raw'] !== null
                                  ? esc_html($currency_symbol . number_format((float) $row['cart_total_raw'], 2))
                                  : esc_html($row['cart_total']);
                        $status      = (string) $row['status'];
                        $opened      = (int) $row['open_count'] > 0;
                        $sent_at     = $row['sent_at']    ? gmdate('M j, Y', strtotime((string) $row['sent_at']))         : '-';
                        $captured_at = $row['created_at'] ? gmdate('M j, Y g:ia', strtotime((string) $row['created_at'])) : '-';
                    ?>
                    <tr>
                        <td class="acs-col-name"><?php echo $name; ?></td>
                        <td class="acs-col-email"><?php echo esc_html($row['email']); ?></td>
                        <td class="acs-col-value"><?php echo $cart_val; ?></td>
                        <td>
                            <span class="acs-status-pill acs-status-pill--<?php echo esc_attr($status); ?>">
                                <?php echo esc_html(ucfirst($status)); ?>
                            </span>
                        </td>
                        <td>
                            <?php if ($opened): ?>
                                <span class="acs-check">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M5 13l4 4L19 7" stroke-linecap="round" stroke-linejoin="round"/></svg>
                                </span>
                            <?php else: ?>
                                <span class="acs-dash">-</span>
                            <?php endif; ?>
                        </td>
                        <td class="acs-col-date"><?php echo $sent_at; ?></td>
                        <td class="acs-col-date"><?php echo $captured_at; ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <?php if ($records['page_count'] > 1): ?>
            <div class="acs-pagination">
                <span class="acs-page-info">
                    Page <?php echo $records['page']; ?> of <?php echo $records['page_count']; ?>
                    &middot; <?php echo number_format($records['total']); ?> records
                </span>
                <div class="acs-page-btns">
                    <?php if ($records['page'] > 1): ?>
                    <a href="<?php echo esc_url(add_query_arg(['status' => $status_filter, 'date' => $date_filter, 'paged' => $records['page'] - 1], $filter_base)); ?>" class="acs-page-btn">&larr; Previous</a>
                    <?php endif; ?>
                    <?php if ($records['page'] < $records['page_count']): ?>
                    <a href="<?php echo esc_url(add_query_arg(['status' => $status_filter, 'date' => $date_filter, 'paged' => $records['page'] + 1], $filter_base)); ?>" class="acs-page-btn">Next &rarr;</a>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <?php endif; ?>
        </div>

    <?php endif; ?>

    <?php if ($tab === 'store'): ?>
        <?php
        $store = new \AutoMarketerAI\StoreChannel();
        $store->handle_actions();
        $store->render();
        ?>
    <?php endif; ?>
    <?php if ($tab === 'settings'): ?>
        <?php if (class_exists('\\AutoMarketerAI\\AbandonedCart')): ?>
        <div class="amai-settings-section">
            <div class="amai-settings-section__head">
                <h2 class="amai-settings-section__title">Abandoned Cart Reminders</h2>
                <p class="amai-settings-section__desc">The defaults are research-backed. Send the first reminder within an hour while the purchase is still top of mind -- studies show this window gets the best conversion rates. Wait 24 hours for the second, giving shoppers time to reconsider without feeling pressured. The third at 72 hours catches anyone still on the fence before they move on for good. Adjust these to match your store's rhythm.</p>
            </div>
            <div class="amai-settings-section__body">
                <div class="amai-nudge-thresholds">
                    <div class="amai-nudge-threshold-row">
                        <label class="amai-nudge-threshold-row__label" for="amai-nudge-1-hours">First reminder</label>
                        <div class="amai-nudge-threshold-row__input-wrap">
                            <input type="number" id="amai-nudge-1-hours" class="amai-nudge-hours-input" min="1" max="720" step="1"
                                value="<?php echo esc_attr((string) (int) get_option('amai_cart_nudge_1_hours', '1')); ?>" />
                            <span class="amai-nudge-threshold-row__unit">hours after abandonment</span>
                        </div>
                    </div>
                    <div class="amai-nudge-threshold-row">
                        <label class="amai-nudge-threshold-row__label" for="amai-nudge-2-hours">Second reminder</label>
                        <div class="amai-nudge-threshold-row__input-wrap">
                            <input type="number" id="amai-nudge-2-hours" class="amai-nudge-hours-input" min="1" max="720" step="1"
                                value="<?php echo esc_attr((string) (int) get_option('amai_cart_nudge_2_hours', '24')); ?>" />
                            <span class="amai-nudge-threshold-row__unit">hours after abandonment</span>
                        </div>
                    </div>
                    <div class="amai-nudge-threshold-row">
                        <label class="amai-nudge-threshold-row__label" for="amai-nudge-3-hours">Third reminder</label>
                        <div class="amai-nudge-threshold-row__input-wrap">
                            <input type="number" id="amai-nudge-3-hours" class="amai-nudge-hours-input" min="1" max="720" step="1"
                                value="<?php echo esc_attr((string) (int) get_option('amai_cart_nudge_3_hours', '72')); ?>" />
                            <span class="amai-nudge-threshold-row__unit">hours after abandonment</span>
                        </div>
                    </div>
                    <div class="amai-nudge-thresholds__footer">
                        <button id="amai-save-nudge-thresholds-btn" class="amai-btn amai-btn--primary">Save</button>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
        <?php if (class_exists('\\AutoMarketerAI\\AbandonedCart')): ?>
        <div class="amai-settings-section">
            <div class="amai-settings-section__head">
                <h2 class="amai-settings-section__title">Recovery Discount</h2>
                <p class="amai-settings-section__desc">Automatically generate a unique discount code and include it in the third cart reminder. Studies show a 10% discount in the final nudge recovers significantly more carts than a plain reminder alone. The code is single-use, tied to the shopper's email address, and expires automatically.</p>
            </div>
            <div class="amai-settings-section__body">
                <div class="amai-recovery-discount">
                    <div class="amai-recovery-discount__toggle-row">
                        <label class="amai-recovery-discount__toggle-label" for="amai-recovery-discount-enabled">
                            <input type="checkbox" id="amai-recovery-discount-enabled" <?php echo get_option('amai_cart_recovery_discount_enabled', '0') === '1' ? 'checked' : ''; ?> />
                            Include a discount code in the third reminder
                        </label>
                    </div>
                    <div class="amai-recovery-discount__fields">
                        <div class="amai-recovery-discount__row">
                            <label class="amai-recovery-discount__label" for="amai-recovery-discount-pct">Discount amount</label>
                            <div class="amai-recovery-discount__input-wrap">
                                <input type="number" id="amai-recovery-discount-pct" class="amai-recovery-discount__input" min="1" max="100" step="1"
                                    value="<?php echo esc_attr((string) (int) get_option('amai_cart_recovery_discount_pct', '10')); ?>" />
                                <span class="amai-recovery-discount__unit">% off</span>
                            </div>
                        </div>
                        <div class="amai-recovery-discount__row">
                            <label class="amai-recovery-discount__label" for="amai-recovery-discount-days">Code expires after</label>
                            <div class="amai-recovery-discount__input-wrap">
                                <input type="number" id="amai-recovery-discount-days" class="amai-recovery-discount__input" min="1" max="30" step="1"
                                    value="<?php echo esc_attr((string) (int) get_option('amai_cart_recovery_discount_days', '3')); ?>" />
                                <span class="amai-recovery-discount__unit">days</span>
                            </div>
                        </div>
                    </div>
                    <div class="amai-recovery-discount__footer">
                        <button id="amai-save-recovery-discount-btn" class="amai-btn amai-btn--primary">Save</button>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
        <div id="amai-settings-toast" class="amai-toast" style="display:none;"></div>
    <?php endif; ?>

    </div>

</div>