<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

session_start();
require 'vendor/autoload.php'; // PHPMailer must be installed via Composer

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

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "invalid";
        exit;
    }

    // Generate a 6-digit OTP
    $otp = rand(100000, 999999);

    // Store in session
    $_SESSION['email_otp'] = $otp;
    $_SESSION['email_verify'] = $email;

    // Send email
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'gowrichakkaraverthic@gmail.com'; // your Gmail
        $mail->Password = 'zbklxgmdrtfkqxsu'; // App password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;

        $mail->setFrom('gowrichakkaraverthic@gmail.com', 'Library Admin');
        $mail->addAddress($email);
        $mail->isHTML(true);
        $mail->Subject = 'Your OTP Code';
        $mail->Body    = "<p>Your OTP for email verification is: <strong>$otp</strong></p>";

        $mail->send();
        echo "sent"; // ✅ response to fetch
        exit;
    } catch (Exception $e) {
        echo "Mailer Error: " . $mail->ErrorInfo; // ✅ better than redirect for AJAX
        exit;
    }
} else {
    echo "Invalid request";
}
?>
