<?php
/**
 * Abandoned Cart Reminder Cron Job
 * Sends email reminders for abandoned carts
 * 
 * Run this script periodically (e.g., daily via cron):
 * php cron/abandoned-cart-reminder.php
 */

// Set execution time limit
set_time_limit(300);

// Include configuration
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/constants.php';
require_once __DIR__ . '/../config/email.php';
require_once __DIR__ . '/../includes/Database.php';
require_once __DIR__ . '/../includes/Cart.php';
require_once __DIR__ . '/../includes/EmailService.php';

$cart = new Cart();
$emailService = new EmailService();
$db = Database::getInstance();

// Get abandoned carts (default: 24 hours)
$hours = CART_ABANDONED_HOURS;
$abandonedCarts = $cart->getAbandonedCarts($hours);

$sentCount = 0;
$errorCount = 0;

foreach ($abandonedCarts as $abandonedCart) {
    try {
        // Get cart items
        $cartItems = $cart->getCartItems($abandonedCart['id']);
        
        if (empty($cartItems)) {
            continue;
        }

        // Get email address
        $email = null;
        if ($abandonedCart['user_id']) {
            // User is logged in - use user email
            $user = $db->fetchOne(
                "SELECT email FROM users WHERE id = ?",
                [$abandonedCart['user_id']]
            );
            $email = $user['email'] ?? null;
        } else {
            // Guest cart - skip (no email available)
            continue;
        }

        if (!$email) {
            continue;
        }

        // Check if we've already sent max emails
        if ($abandonedCart['email_count'] >= MAX_ABANDONED_CART_EMAILS) {
            continue;
        }

        // Send email
        $sent = $emailService->sendAbandonedCartReminder($email, $cartItems, $abandonedCart['id']);

        if ($sent) {
            // Update cart email tracking
            $db->execute(
                "UPDATE cart SET last_email_sent = NOW(), email_count = email_count + 1 WHERE id = ?",
                [$abandonedCart['id']]
            );

            // Log email sent
            $db->execute(
                "INSERT INTO abandoned_cart_emails (cart_id, email) VALUES (?, ?)",
                [$abandonedCart['id'], $email]
            );

            $sentCount++;
        } else {
            $errorCount++;
        }
    } catch (Exception $e) {
        error_log("Abandoned cart reminder error for cart ID {$abandonedCart['id']}: " . $e->getMessage());
        $errorCount++;
    }
}

// Log summary
echo "Abandoned cart reminder completed:\n";
echo "  - Carts processed: " . count($abandonedCarts) . "\n";
echo "  - Emails sent: {$sentCount}\n";
echo "  - Errors: {$errorCount}\n";
?>

