<?php
// verify-email.php - Sends a 6-digit email verification code
session_start();

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['email'])) {
  http_response_code(400);
  echo json_encode(['error' => 'Invalid request.']);
  exit();
}

$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
if (!$email) {
  http_response_code(422);
  echo json_encode(['error' => 'Invalid email address.']);
  exit();
}

$code = random_int(100000, 999999);
$_SESSION['email_verification'] = [
  'email' => $email,
  'code' => $code,
  'timestamp' => time()
];

require 'mailer-config.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

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

$mail = new PHPMailer(true);
try {
  $mail->isSMTP();
  $mail->Host = SMTP_HOST;
  $mail->SMTPAuth = true;
  $mail->Username = SMTP_USERNAME;
  $mail->Password = SMTP_PASSWORD;
  $mail->SMTPSecure = SMTP_SECURE;
  $mail->Port = SMTP_PORT;
  $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
  $mail->addAddress($email);
  $mail->Subject = "Tartu College Email Verification Code";
  $mail->Body = "Your email verification code is: {$code}\n\nIt will expire in 15 minutes.";
  $mail->send();
  echo json_encode(['success' => true]);
} catch (Exception $e) {
  http_response_code(500);
  echo json_encode(['error' => 'Email failed: ' . $mail->ErrorInfo]);
}
?>