<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';
require_once __DIR__ . '/../app/helpers/activity.php';
require_once __DIR__ . '/../app/helpers/email.php';

require_admin();

$pageTitle = 'Abandoned Carts';
$success = '';
$error = '';

if (isset($_GET['expired'])) {
    $success = 'Abandoned cart marked as expired.';
}

if (isset($_GET['queued'])) {
    $success = 'Recovery email queued successfully.';
}

if (isset($_GET['expire'])) {
    $cartId = (int) $_GET['expire'];

    $stmt = $pdo->prepare("SELECT * FROM abandoned_carts WHERE id = ? LIMIT 1");
    $stmt->execute([$cartId]);
    $cart = $stmt->fetch();

    if ($cart) {
        $stmt = $pdo->prepare("
            UPDATE abandoned_carts
            SET status = 'expired'
            WHERE id = ?
        ");
        $stmt->execute([$cartId]);

        log_admin_activity(
            'abandoned_cart_expired',
            'Abandoned cart marked expired. Cart ID: ' . $cartId . ' | Email: ' . ($cart['email'] ?? '-')
        );
    }

    redirect(ADMIN_URL . '/abandoned-carts.php?expired=1');
}

if (isset($_GET['queue_email'])) {
    $cartId = (int) $_GET['queue_email'];

    $stmt = $pdo->prepare("SELECT * FROM abandoned_carts WHERE id = ? LIMIT 1");
    $stmt->execute([$cartId]);
    $cart = $stmt->fetch();

    if ($cart && !empty($cart['email'])) {
        $recoveryUrl = BASE_URL . '/public/cart.php?recover=' . urlencode($cart['recovery_token']);

        queue_template_email(
            'abandoned_cart_recovery',
            $cart['email'],
            [
                'cart_total' => format_price($cart['cart_total']),
                'recovery_url' => $recoveryUrl,
                'site_name' => get_setting('site_name', APP_NAME),
            ],
            $cart['customer_id'] ?? null,
            null
        );

        $stmt = $pdo->prepare("
            UPDATE abandoned_carts
            SET email_sent_count = email_sent_count + 1,
                last_email_sent_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$cartId]);

        log_admin_activity(
            'abandoned_cart_email_queued',
            'Abandoned cart recovery email queued. Cart ID: ' . $cartId . ' | Email: ' . $cart['email']
        );
    }

    redirect(ADMIN_URL . '/abandoned-carts.php?queued=1');
}

$statusFilter = $_GET['status'] ?? '';
$search = trim($_GET['search'] ?? '');

$where = [];
$params = [];

if ($statusFilter !== '' && in_array($statusFilter, ['pending', 'recovered', 'expired'], true)) {
    $where[] = "ac.status = ?";
    $params[] = $statusFilter;
}

if ($search !== '') {
    $where[] = "(ac.email LIKE ? OR ac.session_id LIKE ? OR ac.recovery_token LIKE ?)";
    $searchTerm = '%' . $search . '%';
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$stmt = $pdo->prepare("
    SELECT ac.*,
           c.first_name,
           c.last_name,
           c.email AS customer_email,
           COUNT(aci.id) AS item_count
    FROM abandoned_carts ac
    LEFT JOIN customers c ON ac.customer_id = c.id
    LEFT JOIN abandoned_cart_items aci ON ac.id = aci.abandoned_cart_id
    $whereSql
    GROUP BY ac.id
    ORDER BY ac.id DESC
    LIMIT 300
");
$stmt->execute($params);
$carts = $stmt->fetchAll();

$totalPending = (int) $pdo->query("SELECT COUNT(*) FROM abandoned_carts WHERE status = 'pending'")->fetchColumn();
$totalRecovered = (int) $pdo->query("SELECT COUNT(*) FROM abandoned_carts WHERE status = 'recovered'")->fetchColumn();
$totalExpired = (int) $pdo->query("SELECT COUNT(*) FROM abandoned_carts WHERE status = 'expired'")->fetchColumn();

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>Abandoned Carts</h1>
            <div class="admin-user">Track carts that were started but not completed.</div>
        </div>
    </div>

    <?php if ($success): ?>
        <div class="admin-alert admin-alert-success"><?= e($success); ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="admin-alert admin-alert-error"><?= e($error); ?></div>
    <?php endif; ?>

    <section class="admin-cards" style="margin-bottom:24px;">
        <div class="admin-card">
            <span>Pending</span>
            <strong><?= e($totalPending); ?></strong>
        </div>

        <div class="admin-card">
            <span>Recovered</span>
            <strong><?= e($totalRecovered); ?></strong>
        </div>

        <div class="admin-card">
            <span>Expired</span>
            <strong><?= e($totalExpired); ?></strong>
        </div>
    </section>

    <section class="admin-panel" style="margin-bottom:24px;">
        <h2>Filter Carts</h2>

        <form method="GET" class="admin-form-grid">
            <div class="admin-field">
                <label>Search</label>
                <input
                    type="text"
                    name="search"
                    value="<?= e($search); ?>"
                    placeholder="Search email, session ID, recovery token">
            </div>

            <div class="admin-field">
                <label>Status</label>
                <select name="status">
                    <option value="">All Statuses</option>
                    <option value="pending" <?= $statusFilter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                    <option value="recovered" <?= $statusFilter === 'recovered' ? 'selected' : ''; ?>>Recovered</option>
                    <option value="expired" <?= $statusFilter === 'expired' ? 'selected' : ''; ?>>Expired</option>
                </select>
            </div>

            <div class="admin-field" style="align-self:end;">
                <button type="submit" class="admin-btn">Filter</button>
                <a href="<?= e(ADMIN_URL); ?>/abandoned-carts.php" class="admin-btn admin-btn-light">Reset</a>
            </div>
        </form>
    </section>

    <section class="admin-panel">
        <h2>All Abandoned Carts</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Customer / Email</th>
                    <th>Items</th>
                    <th>Total</th>
                    <th>Email Count</th>
                    <th>Last Email</th>
                    <th>Status</th>
                    <th>Created</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$carts): ?>
                    <tr>
                        <td colspan="8">No abandoned carts found.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($carts as $cart): ?>
                    <tr>
                        <td>
                            <?php if (!empty($cart['customer_id'])): ?>
                                <strong><?= e(trim(($cart['first_name'] ?? '') . ' ' . ($cart['last_name'] ?? ''))); ?></strong><br>
                                <small><?= e($cart['customer_email'] ?? $cart['email'] ?? '-'); ?></small>
                            <?php else: ?>
                                <strong><?= e($cart['email'] ?? 'Guest / Unknown'); ?></strong><br>
                                <small>Session: <?= e(substr($cart['session_id'] ?? '-', 0, 18)); ?></small>
                            <?php endif; ?>
                        </td>

                        <td><?= e($cart['item_count']); ?></td>

                        <td><strong><?= e(format_price($cart['cart_total'])); ?></strong></td>

                        <td><?= e($cart['email_sent_count'] ?? 0); ?></td>

                        <td>
                            <?= !empty($cart['last_email_sent_at'])
                                ? e(date('d M Y, h:i A', strtotime($cart['last_email_sent_at'])))
                                : '-'; ?>
                        </td>

                        <td><strong><?= e(ucfirst($cart['status'])); ?></strong></td>

                        <td><?= e(date('d M Y, h:i A', strtotime($cart['created_at']))); ?></td>

                        <td>
                            <?php if (!empty($cart['email']) && $cart['status'] === 'pending'): ?>
                                <a
                                    class="admin-btn admin-btn-light"
                                    href="<?= e(ADMIN_URL); ?>/abandoned-carts.php?queue_email=<?= e($cart['id']); ?>"
                                    onclick="return confirm('Queue recovery email for this cart?');">
                                    Queue Email
                                </a>
                                <a
    class="admin-btn admin-btn-light"
    href="<?= e(BASE_URL); ?>/public/cart.php?recover=<?= e($cart['recovery_token']); ?>"
    target="_blank"
>
    Open Recovery Link
</a>
                            <?php endif; ?>

                            <?php if ($cart['status'] === 'pending'): ?>
                                <a
                                    class="admin-btn"
                                    href="<?= e(ADMIN_URL); ?>/abandoned-carts.php?expire=<?= e($cart['id']); ?>"
                                    onclick="return confirm('Mark this abandoned cart as expired?');">
                                    Expire
                                </a>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>

<?php require_once __DIR__ . '/includes/footer.php'; ?>