<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /templates/abandoned-cart-stats.php
// Description: Abandoned Cart Emails stats page - summary metrics and per-record table - NUCLEAR+++
// Last Edited: 2026-04-21
// ==================================================

defined('ABSPATH') || exit;

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

$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() : '$';

$base_url = admin_url('admin.php?page=automarketer-ai-cart-stats');

wp_enqueue_style(
    'amai-abandoned-cart-stats',
    plugins_url('assets/css/abandoned-cart-stats.css', dirname(__FILE__)),
    [],
    filemtime(plugin_dir_path(dirname(__FILE__)) . 'assets/css/abandoned-cart-stats.css')
);
?>
<div class="wrap" id="amai-cart-stats-root">

    <div class="acs-header">
        <div class="acs-header-left">
            <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-modules')); ?>" class="acs-back-link">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="acs-back-icon"><path d="M19 12H5M12 5l-7 7 7 7"/></svg>
                Modules
            </a>
            <h1>Abandoned Cart Stats</h1>
            <p class="acs-subtitle">See how your follow-up emails are performing and how much revenue you're bringing back.</p>
        </div>
    </div>

    <!-- Summary bar -->
    <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>

    <!-- Filters -->
    <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], $base_url));
            ?>
            <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], $base_url));
            ?>
            <a href="<?php echo $href; ?>" class="acs-filter-btn <?php echo $active; ?>"><?php echo esc_html($label); ?></a>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Table -->
    <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>

        <!-- Pagination -->
        <?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], $base_url)); ?>" 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], $base_url)); ?>" class="acs-page-btn">Next &rarr;</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <?php endif; ?>
    </div>

</div>