<?php
/**
 * Cron Job Handler - PRODUCTION VERSION
 * Digital Marketplace
 * 
 * This file handles scheduled tasks:
 * - Email campaigns
 * - Scheduled promotions
 * - Background tasks
 * - Cleanup operations
 * 
 * Usage: Run via cron job every minute
 * * * * * * /usr/bin/php /path/to/cron.php
 */

// Prevent direct browser access
if (php_sapi_name() !== 'cli' && !isset($_GET['secret'])) {
    http_response_code(403);
    die('Access denied');
}

// Validate secret key if accessed via browser
if (isset($_GET['secret']) && $_GET['secret'] !== 'your-cron-secret-key') {
    http_response_code(403);
    die('Invalid secret key');
}

require_once __DIR__ . '/config/database.php';

// Set unlimited execution time
set_time_limit(0);

// Log start
log_cron_activity('Cron job started');

$tasks_run = [];
$errors = [];

// ============================================
// TASK 1: Process Email Queue
// ============================================
try {
    $stmt = $pdo->query("SELECT * FROM email_queue WHERE status = 'pending' AND send_at <= NOW() ORDER BY created_at ASC LIMIT 50");
    $emails = $stmt->fetchAll();
    
    $sent_count = 0;
    foreach ($emails as $email) {
        $result = send_email($email['to_email'], $email['subject'], $email['body'], json_decode($email['attachments'] ?? '[]', true));
        
        if ($result) {
            $stmt = $pdo->prepare("UPDATE email_queue SET status = 'sent', sent_at = NOW() WHERE id = ?");
            $sent_count++;
        } else {
            $stmt = $pdo->prepare("UPDATE email_queue SET status = 'failed', attempts = attempts + 1, error_message = ? WHERE id = ?");
            $stmt->execute(['Failed to send', $email['id']]);
        }
        
        $stmt->execute([$email['id']]);
    }
    
    if ($sent_count > 0) {
        $tasks_run[] = "Processed {$sent_count} emails from queue";
    }
} catch (Exception $e) {
    $errors[] = "Email queue: " . $e->getMessage();
}

// ============================================
// TASK 2: Cleanup Old Sessions
// ============================================
try {
    $stmt = $pdo->prepare("DELETE FROM user_sessions WHERE last_activity < DATE_SUB(NOW(), INTERVAL ? SECOND)");
    $stmt->execute([SESSION_LIFETIME * 2]);
    $deleted = $stmt->rowCount();
    
    if ($deleted > 0) {
        $tasks_run[] = "Cleaned up {$deleted} expired sessions";
    }
} catch (Exception $e) {
    $errors[] = "Session cleanup: " . $e->getMessage();
}

// ============================================
// TASK 3: Cleanup Old Cart Items
// ============================================
try {
    $stmt = $pdo->query("DELETE FROM cart WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY) AND user_id IS NULL");
    $deleted = $stmt->rowCount();
    
    if ($deleted > 0) {
        $tasks_run[] = "Cleaned up {$deleted} old cart items";
    }
} catch (Exception $e) {
    $errors[] = "Cart cleanup: " . $e->getMessage();
}

// ============================================
// TASK 4: Cleanup Old Login Attempts
// ============================================
try {
    $stmt = $pdo->query("DELETE FROM login_attempts WHERE attempted_at < DATE_SUB(NOW(), INTERVAL 24 HOUR)");
    $deleted = $stmt->rowCount();
    
    if ($deleted > 0) {
        $tasks_run[] = "Cleaned up {$deleted} old login attempts";
    }
} catch (Exception $e) {
    $errors[] = "Login attempts cleanup: " . $e->getMessage();
}

// ============================================
// TASK 5: Update Expired Negotiations
// ============================================
try {
    $stmt = $pdo->query("UPDATE negotiations SET status = 'expired' WHERE status = 'pending' AND created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");
    $updated = $stmt->rowCount();
    
    if ($updated > 0) {
        $tasks_run[] = "Expired {$updated} old negotiations";
    }
} catch (Exception $e) {
    $errors[] = "Negotiation expiry: " . $e->getMessage();
}

// ============================================
// TASK 6: Process Recurring Payments
// ============================================
try {
    $stmt = $pdo->query("SELECT * FROM subscriptions WHERE status = 'active' AND next_billing_date <= CURDATE()");
    $subscriptions = $stmt->fetchAll();
    
    foreach ($subscriptions as $subscription) {
        // Process payment (implementation depends on payment gateway)
        // This is a placeholder for the actual implementation
        log_cron_activity("Processing recurring payment for subscription {$subscription['id']}");
    }
    
    if (count($subscriptions) > 0) {
        $tasks_run[] = "Processed " . count($subscriptions) . " recurring payments";
    }
} catch (Exception $e) {
    $errors[] = "Recurring payments: " . $e->getMessage();
}

// ============================================
// TASK 7: Send Abandoned Cart Emails
// ============================================
try {
    $stmt = $pdo->query("SELECT c.*, u.email, u.name 
                        FROM cart c 
                        JOIN users u ON c.user_id = u.id 
                        WHERE c.created_at < DATE_SUB(NOW(), INTERVAL 1 HOUR) 
                        AND c.created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)
                        AND c.abandoned_email_sent = 0
                        AND c.user_id IS NOT NULL");
    $abandoned_carts = $stmt->fetchAll();
    
    foreach ($abandoned_carts as $cart) {
        // Get cart items
        $stmt = $pdo->prepare("SELECT c.*, p.name FROM cart c JOIN products p ON c.product_id = p.id WHERE c.user_id = ?");
        $stmt->execute([$cart['user_id']]);
        $items = $stmt->fetchAll();
        
        if (!empty($items)) {
            // Build email content
            $items_html = '';
            foreach ($items as $item) {
                $items_html .= "<li>" . sanitize($item['name']) . " - " . format_price($item['price']) . "</li>";
            }
            
            $subject = "You left something in your cart!";
            $body = <<<HTML
<h2>Hi {$cart['name']},</h2>
<p>You left some items in your shopping cart. Don't miss out!</p>
<ul>{$items_html}</ul>
<p><a href="<?php echo BASE_URL; ?>/cart.php" class="btn">Complete Your Purchase</a></p>
HTML;
            
            send_email($cart['email'], $subject, $body);
            
            // Mark as sent
            $stmt = $pdo->prepare("UPDATE cart SET abandoned_email_sent = 1 WHERE user_id = ?");
            $stmt->execute([$cart['user_id']]);
        }
    }
    
    if (count($abandoned_carts) > 0) {
        $tasks_run[] = "Sent " . count($abandoned_carts) . " abandoned cart emails";
    }
} catch (Exception $e) {
    $errors[] = "Abandoned cart emails: " . $e->getMessage();
}

// ============================================
// TASK 8: Update Product Statistics
// ============================================
try {
    // Update bestseller status
    $stmt = $pdo->query("UPDATE products SET bestseller = 1 WHERE times_sold >= 50 AND bestseller = 0");
    $updated = $stmt->rowCount();
    
    if ($updated > 0) {
        $tasks_run[] = "Updated {$updated} products to bestseller status";
    }
} catch (Exception $e) {
    $errors[] = "Product stats: " . $e->getMessage();
}

// ============================================
// TASK 9: Cleanup Old Activity Logs
// ============================================
try {
    $stmt = $pdo->query("DELETE FROM activity_log WHERE created_at < DATE_SUB(NOW(), INTERVAL 90 DAY)");
    $deleted = $stmt->rowCount();
    
    if ($deleted > 0) {
        $tasks_run[] = "Cleaned up {$deleted} old activity logs";
    }
} catch (Exception $e) {
    $errors[] = "Activity log cleanup: " . $e->getMessage();
}

// ============================================
// TASK 10: Cleanup Old Email Logs
// ============================================
try {
    $stmt = $pdo->query("DELETE FROM email_log WHERE sent_at < DATE_SUB(NOW(), INTERVAL 30 DAY)");
    $deleted = $stmt->rowCount();
    
    if ($deleted > 0) {
        $tasks_run[] = "Cleaned up {$deleted} old email logs";
    }
} catch (Exception $e) {
    $errors[] = "Email log cleanup: " . $e->getMessage();
}

// ============================================
// TASK 11: Backup Database (Daily at midnight)
// ============================================
if (date('H:i') === '00:00') {
    try {
        $backup_file = __DIR__ . '/backups/backup_' . date('Y-m-d_H-i-s') . '.sql';
        
        // Create backup directory if not exists
        if (!is_dir(__DIR__ . '/backups')) {
            mkdir(__DIR__ . '/backups', 0755, true);
        }
        
        // Run mysqldump
        $command = "mysqldump -h " . DB_HOST . " -u " . DB_USER . " -p" . DB_PASS . " " . DB_NAME . " > " . escapeshellarg($backup_file) . " 2>&1";
        exec($command, $output, $return_code);
        
        if ($return_code === 0) {
            $tasks_run[] = "Database backup created: " . basename($backup_file);
            
            // Delete old backups (keep last 7 days)
            $old_backups = glob(__DIR__ . '/backups/backup_*.sql');
            usort($old_backups, function($a, $b) {
                return filemtime($b) - filemtime($a);
            });
            
            foreach (array_slice($old_backups, 7) as $old_backup) {
                unlink($old_backup);
            }
        } else {
            $errors[] = "Database backup failed";
        }
    } catch (Exception $e) {
        $errors[] = "Database backup: " . $e->getMessage();
    }
}

// ============================================
// TASK 12: Generate Daily Reports
// ============================================
if (date('H:i') === '00:01') {
    try {
        // Get yesterday's stats
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        
        $stmt = $pdo->prepare("SELECT COUNT(*) as orders, COALESCE(SUM(total), 0) as revenue 
                              FROM orders 
                              WHERE DATE(created_at) = ? AND payment_status = 'completed'");
        $stmt->execute([$yesterday]);
        $stats = $stmt->fetch();
        
        // Send daily report to admin
        $admin_email = get_setting('site_email', 'admin@example.com');
        $subject = "Daily Report - " . date('M d, Y', strtotime('-1 day'));
        $body = <<<HTML
<h2>Daily Report - {$yesterday}</h2>
<p><strong>Orders:</strong> {$stats['orders']}</p>
<p><strong>Revenue:</strong> " . format_price($stats['revenue']) . "</p>
HTML;
        
        send_email($admin_email, $subject, $body);
        
        $tasks_run[] = "Daily report sent to admin";
    } catch (Exception $e) {
        $errors[] = "Daily report: " . $e->getMessage();
    }
}

// Log completion
log_cron_activity('Cron job completed', [
    'tasks_run' => $tasks_run,
    'errors' => $errors
]);

// Output results (for CLI)
if (php_sapi_name() === 'cli') {
    echo "=== CRON JOB RESULTS ===\n";
    echo "Time: " . date('Y-m-d H:i:s') . "\n\n";
    
    if (!empty($tasks_run)) {
        echo "Tasks completed:\n";
        foreach ($tasks_run as $task) {
            echo "  - {$task}\n";
        }
    } else {
        echo "No tasks to run.\n";
    }
    
    if (!empty($errors)) {
        echo "\nErrors:\n";
        foreach ($errors as $error) {
            echo "  - {$error}\n";
        }
    }
    
    echo "\n=== END ===\n";
}

// Helper function to log cron activity
function log_cron_activity($message, $data = null) {
    global $pdo;
    if (!isset($pdo)) return;
    
    try {
        $stmt = $pdo->prepare("INSERT INTO cron_log (message, data, created_at) VALUES (?, ?, NOW())");
        $stmt->execute([$message, $data ? json_encode($data) : null]);
    } catch (Exception $e) {
        error_log("Failed to log cron activity: " . $e->getMessage());
    }
}
