<?php
require_once '../../includes/db.php';

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

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$message = '';
$selectedId = $_POST['applicant_id'] ?? null;
$applicant = null;

if ($selectedId) {
    $stmt = $pdo->prepare("SELECT a.full_name, a.email, c.name AS celebrity_name FROM applications a LEFT JOIN celebrities c ON a.celebrity_id = c.id WHERE a.id = ?");
    $stmt->execute([$selectedId]);
    $applicant = $stmt->fetch();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_email'])) {
    $subject = trim($_POST['subject']);
    $body = trim($_POST['body']);

    if (!$applicant || empty($subject) || empty($body)) {
        $message = "<div class='alert alert-danger'>All fields are required.</div>";
    } else {
        try {
            $mail = new PHPMailer(true);
            $mail->isSMTP();
            $mail->Host = 'mail.spacemail.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'support@manageme.pro';
            $mail->Password = '#Admin404';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;

            $mail->setFrom('support@manageme.pro', 'Manageme Team');
            $mail->addAddress($applicant['email'], $applicant['full_name']);
            $mail->addReplyTo('support@manageme.pro', 'Support');

            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body = nl2br($body);
            $mail->AltBody = $body;

            $mail->send();
            $message = "<div class='alert alert-success'>Email sent to {$applicant['full_name']}.</div>";
        } catch (Exception $e) {
            $message = "<div class='alert alert-danger'>Email failed: {$mail->ErrorInfo}</div>";
        }
    }
}

// Load applicants for dropdown
$applicants = $pdo->query("
    SELECT a.id, a.full_name, a.email, c.name AS celebrity
    FROM applications a
    JOIN celebrities c ON a.celebrity_id = c.id
    ORDER BY a.id DESC
")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Send Custom Email</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { background: #f8f9fa; font-family: system-ui, sans-serif; }
    .container { max-width: 750px; margin-top: 50px; background: #fff; padding: 30px; border-radius: 10px; }
  </style>
</head>
<body>

<?php include 'navbar.php'; ?>

<div class="container">
  <h3 class="mb-4">Send Custom Email to Applicant</h3>

  <?= $message ?>

  <form method="post">
    <div class="mb-3">
      <label for="applicant_id" class="form-label">Select Applicant</label>
      <select name="applicant_id" id="applicant_id" class="form-select" onchange="this.form.submit()" required>
        <option value="">-- Choose Applicant --</option>
        <?php foreach ($applicants as $a): ?>
          <option value="<?= $a['id'] ?>" <?= ($a['id'] == $selectedId) ? 'selected' : '' ?>>
            <?= htmlspecialchars($a['full_name']) ?> - <?= htmlspecialchars($a['email']) ?> (<?= htmlspecialchars($a['celebrity']) ?>)
          </option>
        <?php endforeach; ?>
      </select>
    </div>

    <?php if ($applicant): ?>
      <div class="mb-3">
        <p><strong>Name:</strong> <?= htmlspecialchars($applicant['full_name']) ?></p>
        <p><strong>Email:</strong> <?= htmlspecialchars($applicant['email']) ?></p>
        <p><strong>Celebrity:</strong> <?= htmlspecialchars($applicant['celebrity_name']) ?></p>
      </div>

      <div class="mb-3">
        <label for="subject" class="form-label">Subject</label>
        <input type="text" name="subject" id="subject" class="form-control" required>
      </div>

      <div class="mb-3">
        <label for="body" class="form-label">Email Body</label>
        <textarea name="body" id="body" rows="8" class="form-control" required></textarea>
      </div>

      <button type="submit" name="send_email" class="btn btn-primary">Send Email</button>
    <?php endif; ?>
  </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
