<?php
/**
 * Cron Job: Send Scheduled Emails
 * 
 * This script checks for pending scheduled emails that are due and sends them.
 * 
 * SETUP ON CPANEL:
 * 1. Go to cPanel > Cron Jobs
 * 2. Set to run every 5 minutes (or every hour):
 *    Every 5 min:  * /5 * * * *
 *    Every hour:   0 * * * *
 *    Once daily:   0 9 * * *
 * 3. Command: php /home/YOUR_USERNAME/public_html/llcpro/jediprime/jediprime/faq/cron/send_scheduled_emails.php
 *    OR use wget: wget -q -O /dev/null https://yourdomain.com/llcpro/jediprime/jediprime/faq/cron/send_scheduled_emails.php
 * 
 * You can also trigger it via browser: https://yourdomain.com/llcpro/jediprime/jediprime/faq/cron/send_scheduled_emails.php?key=YOUR_CRON_KEY
 */

// Security key to prevent unauthorized access via browser
$cron_key = 'jedi_cron_2024_secure'; // Change this to something unique

// Allow CLI execution without key check
if (php_sapi_name() !== 'cli') {
    if (!isset($_GET['key']) || $_GET['key'] !== $cron_key) {
        http_response_code(403);
        die('Unauthorized');
    }
}

// Load config
$config_path = dirname(__DIR__) . '/include/config.php';
if (!file_exists($config_path)) {
    die("Config not found");
}
include($config_path);

// ═══════════════════════════════════════════════════════════════
//  SMTP CONFIGURATION (from database settings)
// ═══════════════════════════════════════════════════════════════
$smtp_config = get_mail_settings($pdo, $site_data);
$smtp_from_name = trim($smtp_config['smtp_from_name'] ?? $smtp_config['web_name'] ?? $site_data['web_name'] ?? 'Website');
$smtp_from_email = trim($smtp_config['smtp_from_email'] ?? $smtp_config['web_email'] ?? $site_data['web_email'] ?? '');
// ═══════════════════════════════════════════════════════════════

// Get pending scheduled emails that are due
try {
    $stmt = $pdo->prepare("SELECT * FROM scheduled_emails WHERE status = 'pending' AND scheduled_at <= NOW() ORDER BY scheduled_at ASC LIMIT 5");
    $stmt->execute();
    $emails_to_send = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("DB Error: " . $e->getMessage());
}

if (empty($emails_to_send)) {
    echo "No scheduled emails to send.\n";
    exit();
}

// Process each scheduled email
foreach ($emails_to_send as $scheduled) {
    $subject = $scheduled['subject'];
    $message = $scheduled['message'];
    $recipient_type = $scheduled['recipient_type'];

    // Get recipients
    $recipients = [];
    try {
        if ($recipient_type === 'all') {
            $stmt = $pdo->prepare("SELECT id, email, username, full_name FROM users WHERE status = 1");
            $stmt->execute();
            $recipients = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } else {
            $user_ids = array_map('intval', explode(',', $scheduled['user_ids']));
            if (!empty($user_ids)) {
                $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
                $stmt = $pdo->prepare("SELECT id, email, username, full_name FROM users WHERE id IN ($placeholders) AND status = 1");
                $stmt->execute($user_ids);
                $recipients = $stmt->fetchAll(PDO::FETCH_ASSOC);
            }
        }
    } catch (PDOException $e) {
        // Mark as failed
        $pdo->prepare("UPDATE scheduled_emails SET status = 'failed', sent_at = NOW() WHERE id = ?")->execute([$scheduled['id']]);
        echo "Error fetching recipients for email #{$scheduled['id']}: " . $e->getMessage() . "\n";
        continue;
    }

    if (empty($recipients)) {
        $pdo->prepare("UPDATE scheduled_emails SET status = 'failed', sent_at = NOW() WHERE id = ?")->execute([$scheduled['id']]);
        echo "No recipients for email #{$scheduled['id']}\n";
        continue;
    }

    // Build email template
    $logo_url = !empty($site_data['logo_url']) ? $site_data['logo_url'] : $site_data['web_url'] . '/images/softbills.png';
    $web_url = $site_data['web_url'];
    $web_email = $site_data['web_email'];
    
    $whatsapp_number = '2349162671360';
    if (!empty($site_data['whatsapp_number'])) {
        $whatsapp_number = preg_replace('/[^0-9]/', '', $site_data['whatsapp_number']);
    }
    $whatsapp_link = 'https://wa.me/' . $whatsapp_number;

    $email_body = '<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>' . htmlspecialchars($subject) . '</title>
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background-color: #f0f2f5;">
    <div style="max-width: 600px; margin: 30px auto; background: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.08);">
        <div style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); padding: 30px; text-align: center;">
            <img src="' . htmlspecialchars($logo_url) . '" alt="' . htmlspecialchars($smtp_from_name) . '" style="max-width: 120px; max-height: 60px; margin-bottom: 12px;">
            <h1 style="margin: 0; font-size: 20px; color: #ffffff; font-weight: 600;">' . htmlspecialchars($smtp_from_name) . '</h1>
        </div>
        <div style="padding: 35px 30px;">
            ' . $message . '
        </div>
        <div style="padding: 0 30px 15px; text-align: center;">
            <a href="' . $whatsapp_link . '" target="_blank" style="display: inline-block; background-color: #25D366; color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 50px; font-size: 15px; font-weight: 600; box-shadow: 0 4px 12px rgba(37,211,102,0.3);">
                &#128172; Chat on WhatsApp
            </a>
        </div>
        <div style="padding: 0 30px 30px; text-align: center;">
            <p style="margin: 0 0 10px; font-size: 14px; font-weight: 600; color: #333;">Join Our Telegram Group</p>
            <p style="margin: 0 0 14px; font-size: 12px; color: #6c757d;">Get updates, support &amp; exclusive offers</p>
            <a href="' . htmlspecialchars($site_data['channel_url'] ?? '') . '" target="_blank" style="display: inline-block; background-color: #0088cc; color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 50px; font-size: 15px; font-weight: 600; box-shadow: 0 4px 12px rgba(0,136,204,0.3);">
                &#9992; Join Telegram
            </a>
        </div>
        <div style="background: #f8f9fc; padding: 25px 30px; text-align: center; border-top: 1px solid #e3e6f0;">
            <p style="margin: 0 0 8px; font-size: 13px; color: #6c757d;">
                <a href="' . htmlspecialchars($web_url) . '" style="color: #4e73df; text-decoration: none; font-weight: 600;">' . htmlspecialchars($web_url) . '</a>
            </p>
            <p style="margin: 0 0 8px; font-size: 13px; color: #6c757d;">
                &#9993; <a href="mailto:' . htmlspecialchars($web_email) . '" style="color: #4e73df; text-decoration: none;">' . htmlspecialchars($web_email) . '</a>
            </p>
            <p style="margin: 12px 0 0; font-size: 11px; color: #adb5bd;">
                &copy; ' . date('Y') . ' ' . htmlspecialchars($smtp_from_name) . '. All rights reserved.
            </p>
        </div>
    </div>
</body>
</html>';

    // Send emails
    $sent_count = 0;
    $failed_count = 0;

    foreach ($recipients as $recipient) {
        $to = $recipient['email'];
        if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
            $failed_count++;
            continue;
        }

        try {
            $mail_sent = send_system_email($to, $subject, $email_body, $pdo, $site_data, [
                'from_email' => $smtp_from_email,
                'from_name' => $smtp_from_name,
            ]);

            if ($mail_sent) {
                $sent_count++;
            } else {
                $failed_count++;
            }
        } catch (Exception $e) {
            $failed_count++;
        }

        // Delay between sends
        if (count($recipients) > 10) {
            usleep(200000);
        }
    }

    // Update scheduled email status
    $status = $sent_count > 0 ? 'sent' : 'failed';
    try {
        $stmt = $pdo->prepare("UPDATE scheduled_emails SET status = ?, sent_count = ?, failed_count = ?, sent_at = NOW() WHERE id = ?");
        $stmt->execute([$status, $sent_count, $failed_count, $scheduled['id']]);
    } catch (PDOException $e) {
        echo "Error updating status for email #{$scheduled['id']}\n";
    }

    echo "Email #{$scheduled['id']}: Sent={$sent_count}, Failed={$failed_count}\n";
}

echo "Done.\n";
?>
