<?php
// ✅ Start session before any output
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ✅ Check admin login session
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

// ✅ Database Connection
$host = "localhost";
$dbname = "pnoacamy_referral_system";
$username = "pnoacamy_referral_system";
$password = "Anna4082Daimon!";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// ✅ PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'src/PHPMailer.php';
require 'src/SMTP.php';
require 'src/Exception.php';

// ✅ EMAIL BROADCAST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_email'])) {
    $table = $_POST['target_table'];
    $subject = $_POST['subject'];
    $body = $_POST['body'];

    if ($table === 'users') {
        $stmt = $pdo->query("SELECT email, first_name AS fname FROM users WHERE email IS NOT NULL AND email != ''");
        $footer = "<br><br>You are receiving this email because you are a member of our MLM Lead Pro system. As an MLM Lead Pro member, you may receive important updates from us.";
    } else {
        $stmt = $pdo->query("SELECT email, name AS fname FROM leads WHERE email IS NOT NULL AND email != ''");
        $footer = "<br><br>You are receiving this email as a lead within our MLM Lead Pro system. We rarely send to leads and only do so for important updates.";
    }

    $sent = 0;

while ($row = $stmt->fetch()) {
    $to = $row['email'];
    $fname = !empty($row['fname']) ? $row['fname'] : 'there';
    $personalized_body = str_replace('{{fname}}', $fname, $body);
    $personalized_subject = str_replace('{{fname}}', $fname, $subject);

    $mail = new PHPMailer(true);
    $mail->CharSet = 'UTF-8';
    try {
        $mail->isSMTP();
        $mail->Host       = 'mlmlead.pro';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'edward@mlmlead.pro';
        $mail->Password   = '^JL4]K9w3@XE';
        $mail->SMTPSecure = 'ssl';
        $mail->Port       = 465;

        $mail->setFrom('edward@mlmlead.pro', 'Edward MLM Lead Pro');
        $mail->addAddress($to);
        $mail->isHTML(true);
        $mail->Subject = $personalized_subject;
        $mail->Body    = nl2br($personalized_body . $footer);

        $mail->send();
        $sent++;

        // ⏸ Throttle sending every 50 emails
        if ($sent % 50 === 0) {
            sleep(5);
        }
    } catch (Exception $e) {
        error_log("❌ Email to $to failed: " . $mail->ErrorInfo);
    }
}


    $message = "✅ Emails sent: $sent";
}

// ✅ Preview Handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['preview_email'])) {
    $sample_name = "Sarah";
    $preview_subject = str_replace('{{fname}}', $sample_name, $_POST['subject']);
    $preview_body = nl2br(str_replace('{{fname}}', $sample_name, $_POST['body']));
    $target_table = $_POST['target_table'];

    if ($target_table === 'users') {
        $footer = "<br><br>You are receiving this email because you are a member of our MLM Lead Pro system.";
    } else {
        $footer = "<br><br>You are receiving this email as a lead within our MLM Lead Pro system.";
    }

    $full_preview = $preview_body . $footer;
}

// ✅ Retain form values
$subject_val = isset($_POST['subject']) ? htmlspecialchars($_POST['subject']) : '';
$body_val = isset($_POST['body']) ? htmlspecialchars($_POST['body']) : '';
$table_val = isset($_POST['target_table']) ? $_POST['target_table'] : 'users';
?>

<!DOCTYPE html>
<html>
<head>
  <title>Email Broadcaster</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body style="display: flex; min-height: 100vh; margin: 0;">
  <div style="width: 220px; background: #343a40; color: #fff; padding: 20px;"><?php include 'google-translate-widget-front-end.php'; ?>
    <h4>Admin Menu</h4>
    <a href="admin.php" style="color:#fff; display:block; margin-bottom:10px;">Dashboard</a>
    <a href="admin-activity.php"  style="color:#fff; display:block; margin-bottom:10px;">User Activity</a>
    <a href="admin-users.php"  style="color:#fff; display:block; margin-bottom:10px;">User Manager</a>
    <a href="add_program.php" style="color:#fff; display:block; margin-bottom:10px;">Add Programs</a>
    <a href="admin-branding.php" style="color:#fff; display:block; margin-bottom:10px;">Branding</a>
    <a href="add-sharecode-admin.php" style="color:#fff; display:block; margin-bottom:10px;">Share Codes</a>
    <a href="video-admin.php" style="color:#fff; display:block; margin-bottom:10px;">Training Videos</a>
    <a href="email_broadcast.php" style="color:#fff; display:block; margin-bottom:10px;">Internal Mailer</a>
    <a href="mailer/mailer.php" style="color:#fff; display:block; margin-bottom:10px;">CSV Mailer</a>
    <a href="email-templates.php" style="color:#fff; display:block; margin-bottom:10px;">Email Templates</a>
  </div>

  <div style="flex-grow: 1; padding: 20px;">
    <h2>Send Email Broadcast</h2>

    <?php if (isset($message)) echo "<div class='alert alert-success'>$message</div>"; ?>

    <form method="POST">
      <label>Subject:</label>
      <input type="text" name="subject" class="form-control mb-3" value="<?= $subject_val ?>" required>

      <label>Email Body (use <code>{{fname}}</code> to personalize):</label>
      <textarea name="body" class="form-control mb-3" rows="8" required><?= $body_val ?></textarea>

      <label>Send To:</label>
      <select name="target_table" class="form-select mb-3">
        <option value="users" <?= $table_val === 'users' ? 'selected' : '' ?>>Users Table</option>
        <option value="leads" <?= $table_val === 'leads' ? 'selected' : '' ?>>Leads Table</option>
      </select>

      <button name="preview_email" class="btn btn-secondary me-2">Preview Email</button>
      <button name="send_email" class="btn btn-primary">Send Emails</button>
    </form>

    <?php if (isset($full_preview)): ?>
      <hr>
      <h4>📧 Preview</h4>
      <strong>Subject:</strong> <?= htmlspecialchars($preview_subject) ?><br><br>
      <strong>Email Body:</strong>
      <div style="border:1px solid #ccc; padding:10px;"><?= $full_preview ?></div>
    <?php endif; ?>
  </div>
</body>
</html>
