<?php
/**
 * Abandoned Cart Email Cron Job
 * 
 * This script should be run periodically (e.g., every hour) to:
 * 1. Detect abandoned carts (inactive for X hours)
 * 2. Send reminder emails to users
 * 
 * Setup: Add to crontab:
 * 0 * * * * /usr/bin/php /path/to/cron/abandoned-cart.php >> /path/to/logs/cron.log 2>&1
 */

// Set error reporting
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Include required files
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

// Configuration
$ABANDONED_HOURS = 24; // Consider cart abandoned after 24 hours of inactivity
$REMINDER_HOURS = [24, 48, 72]; // Send reminders at 24, 48, and 72 hours

echo "[" . date('Y-m-d H:i:s') . "] Starting abandoned cart check...\n";

try {
    // Get all abandoned carts that haven't been converted
    $stmt = $pdo->prepare("
        SELECT ct.*, u.name, u.email
        FROM cart_tracking ct
        JOIN users u ON ct.user_id = u.id
        WHERE ct.status = 'active'
        AND ct.last_activity < DATE_SUB(NOW(), INTERVAL ? HOUR)
        AND ct.reminder_sent < ?
        ORDER BY ct.last_activity ASC
    ");
    
    foreach ($REMINDER_HOURS as $hours) {
        echo "[" . date('Y-m-d H:i:s') . "] Checking for {$hours} hour reminders...\n";
        
        $stmt->execute([$hours, $hours]);
        $abandoned_carts = $stmt->fetchAll();
        
        echo "[" . date('Y-m-d H:i:s') . "] Found " . count($abandoned_carts) . " carts for {$hours}h reminder\n";
        
        foreach ($abandoned_carts as $cart) {
            // Get cart items
            $cart_items = json_decode($cart['cart_data'], true);
            
            if (empty($cart_items)) {
                continue;
            }
            
            // Calculate cart total
            $cart_total = 0;
            $item_count = 0;
            foreach ($cart_items as $item) {
                $cart_total += $item['price'] * $item['quantity'];
                $item_count += $item['quantity'];
            }
            
            // Prepare email data
            $email_data = [
                'user_name' => $cart['name'],
                'user_email' => $cart['email'],
                'cart_items' => $cart_items,
                'cart_total' => $cart_total,
                'item_count' => $item_count,
                'cart_id' => $cart['id'],
                'hours_abandoned' => $hours
            ];
            
            // Send abandoned cart email
            $result = send_abandoned_cart_email($pdo, $cart['user_id'], $email_data);
            
            if ($result) {
                // Update reminder_sent count
                $update_stmt = $pdo->prepare("
                    UPDATE cart_tracking 
                    SET reminder_sent = reminder_sent + 1 
                    WHERE id = ?
                ");
                $update_stmt->execute([$cart['id']]);
                
                echo "[" . date('Y-m-d H:i:s') . "] Sent reminder to {$cart['email']} ({$hours}h)\n";
            } else {
                echo "[" . date('Y-m-d H:i:s') . "] FAILED to send reminder to {$cart['email']}\n";
            }
            
            // Small delay to avoid overwhelming the mail server
            usleep(100000); // 100ms delay
        }
    }
    
    // Mark very old carts as expired (after 7 days)
    $expired_stmt = $pdo->prepare("
        UPDATE cart_tracking 
        SET status = 'expired' 
        WHERE status = 'active' 
        AND last_activity < DATE_SUB(NOW(), INTERVAL 7 DAY)
    ");
    $expired_stmt->execute();
    $expired_count = $expired_stmt->rowCount();
    
    if ($expired_count > 0) {
        echo "[" . date('Y-m-d H:i:s') . "] Marked {$expired_count} old carts as expired\n";
    }
    
    echo "[" . date('Y-m-d H:i:s') . "] Abandoned cart check completed\n";
    
} catch (Exception $e) {
    echo "[" . date('Y-m-d H:i:s') . "] ERROR: " . $e->getMessage() . "\n";
    error_log("Abandoned cart cron error: " . $e->getMessage());
}

/**
 * Send abandoned cart email
 */
function send_abandoned_cart_email($pdo, $user_id, $data) {
    $subject = "Don't forget your items! Complete your purchase";
    
    // Build cart items HTML
    $items_html = '';
    foreach ($data['cart_items'] as $item) {
        $item_total = $item['price'] * $item['quantity'];
        $items_html .= "
            <tr>
                <td style='padding: 10px; border-bottom: 1px solid #eee;'>
                    <strong>" . htmlspecialchars($item['name']) . "</strong>
                </td>
                <td style='padding: 10px; border-bottom: 1px solid #eee; text-align: center;'>
                    {$item['quantity']}
                </td>
                <td style='padding: 10px; border-bottom: 1px solid #eee; text-align: right;'>
                    $" . number_format($item_total, 2) . "
                </td>
            </tr>
        ";
    }
    
    $body = "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'>
            <title>Complete Your Purchase</title>
        </head>
        <body style='font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto;'>
            <div style='background: #4e73df; padding: 20px; text-align: center;'>
                <h1 style='color: white; margin: 0;'>Don't Miss Out!</h1>
            </div>
            
            <div style='padding: 30px; background: #f9f9f9;'>
                <p>Hi " . htmlspecialchars($data['user_name']) . ",</p>
                
                <p>We noticed you left some items in your cart. Don't worry, we've saved them for you!</p>
                
                <h3 style='color: #4e73df; margin-top: 30px;'>Your Cart ({$data['item_count']} items)</h3>
                
                <table style='width: 100%; border-collapse: collapse; background: white; margin: 20px 0;'>
                    <thead>
                        <tr style='background: #f0f0f0;'>
                            <th style='padding: 10px; text-align: left;'>Product</th>
                            <th style='padding: 10px; text-align: center;'>Qty</th>
                            <th style='padding: 10px; text-align: right;'>Price</th>
                        </tr>
                    </thead>
                    <tbody>
                        {$items_html}
                    </tbody>
                    <tfoot>
                        <tr style='background: #f0f0f0; font-weight: bold;'>
                            <td style='padding: 10px;' colspan='2'>Total</td>
                            <td style='padding: 10px; text-align: right;'>$" . number_format($data['cart_total'], 2) . "</td>
                        </tr>
                    </tfoot>
                </table>
                
                <div style='text-align: center; margin: 30px 0;'>
                    <a href='" . get_base_url() . "cart.php' 
                       style='background: #4e73df; color: white; padding: 15px 30px; text-decoration: none; border-radius: 5px; display: inline-block;'>
                        Complete My Purchase
                    </a>
                </div>
                
                <p style='color: #666; font-size: 14px;'>
                    Need help? Reply to this email or contact our support team.
                </p>
                
                <hr style='border: none; border-top: 1px solid #ddd; margin: 30px 0;'>
                
                <p style='color: #999; font-size: 12px; text-align: center;'>
                    If you no longer wish to receive these emails, you can <a href='" . get_base_url() . "unsubscribe.php?type=cart'>unsubscribe</a>.
                </p>
            </div>
        </body>
        </html>
    ";
    
    return send_email($pdo, $data['user_email'], $subject, $body);
}
?>