<?php
/**
 * Email Queue Processor
 * Processes pending emails in queue and sends them
 * Can be run as a cron job or called manually
 */

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

$conn = $connection;

if ($conn->connect_error) {
    die(json_encode(['success' => false, 'message' => 'Database connection failed']));
}

// Get pending emails from queue (limit to 100 per run)
$sql = "SELECT id, subscriber_email, subject_line, email_content FROM newsletter_email_queue 
        WHERE status = 'pending' AND retry_count < 3 
        ORDER BY created_at ASC 
        LIMIT 100";

$result = $conn->query($sql);

if (!$result) {
    die(json_encode(['success' => false, 'message' => 'Query failed']));
}

$sent_count = 0;
$failed_count = 0;
$details = [];

while ($row = $result->fetch_assoc()) {
    $email_id = $row['id'];
    $to = $row['subscriber_email'];
    $subject = $row['subject_line'];
    $message = $row['email_content'];
    
    if (sendQueuedEmail($to, $subject, $message)) {
        // Mark as sent
        $update_sql = "UPDATE newsletter_email_queue 
                      SET status = 'sent', sent_at = NOW() 
                      WHERE id = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param('i', $email_id);
        $update_stmt->execute();
        $update_stmt->close();
        
        $sent_count++;
        $details[] = "✓ Sent to: $to";
    } else {
        // Increment retry count
        $retry_sql = "UPDATE newsletter_email_queue 
                     SET status = 'failed', 
                         retry_count = retry_count + 1, 
                         last_retry_at = NOW(),
                         error_message = 'Send attempt failed'
                     WHERE id = ?";
        $retry_stmt = $conn->prepare($retry_sql);
        $retry_stmt->bind_param('i', $email_id);
        $retry_stmt->execute();
        $retry_stmt->close();
        
        $failed_count++;
        $details[] = "✗ Failed to send to: $to";
    }
}

$conn->close();

// Return response
header('Content-Type: application/json');
echo json_encode([
    'success' => true,
    'sent_count' => $sent_count,
    'failed_count' => $failed_count,
    'message' => "Processed $sent_count emails successfully, $failed_count failed",
    'details' => $details
]);

function sendQueuedEmail($to, $subject, $message) {
    try {
        if (file_exists(__DIR__ . '/vendor/autoload.php')) {
            require __DIR__ . '/vendor/autoload.php';
            $mail = new PHPMailer\PHPMailer\PHPMailer(true);
            $mail->isSMTP();
            $mail->Host = 'mail.zemaraimgroups.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'info@zemaraimgroups.com'; // Change to your email
            $mail->Password = 'zemaraimgroups@123'; // Change to your app password
            $mail->SMTPSecure = 'PHPMailer::ENCRYPTION_SMTPS';
            $mail->Port = 465;
            $mail->setFrom('info@zemaraimgroups.com', 'Interior Design Solutions');
            $mail->addAddress($to);
            $mail->Subject = $subject;
            $mail->isHTML(true);
            $mail->Body = $message;
            $mail->SMTPOptions = [
                'ssl' => [
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                ]
            ];
            return $mail->send();
        } else {
            $header_str = "MIME-Version: 1.0\r\nContent-type: text/html; charset=UTF-8\r\n";
            $header_str .= "From: Faren Design <noreply@farendesign.com>\r\n";
            return @mail($to, $subject, $message, $header_str);
        }
    } catch (Exception $e) {
        error_log("Email send error: " . $e->getMessage());
        return false;
    }
}
?>
