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

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

header('Content-Type: application/json');

if (!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid email']);
    exit;
}

$email = $_POST['email'];
$code = random_int(100000, 999999);

// Save code to database (MySQL)
$conn = new mysqli('localhost', 'gobolcha_gobolchain', '@Jibala1997', 'gobolcha_gobolchain');
if ($conn->connect_error) {
    echo json_encode(['status' => 'error', 'message' => 'DB connection failed']);
    exit;
}

// Clean previous code if exists
$stmt = $conn->prepare("DELETE FROM email_verification WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();

// Save new code
$stmt = $conn->prepare("INSERT INTO email_verification (email, code) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $code);
$stmt->execute();
$stmt->close();

// Send email
$mail = new PHPMailer(true);
try {
   $mail->isSMTP();
$mail->Host = 'mail.gobolchain.info';
$mail->SMTPAuth = true;
$mail->Username = 'team@gobolchain.info';
$mail->Password = '@Jibala1997'; 
$mail->SMTPSecure = 'tls'; 
$mail->Port = 587; 

    $mail->setFrom(MAIL_FROM, MAIL_FROM_NAME);
    $mail->addAddress($email);
    $mail->Subject = 'Gobolchain Email Verification';
    $mail->Body = "Your verification code is: $code";

    $mail->send();
    echo json_encode(['status' => 'success']);
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'Mailer Error: ' . $mail->ErrorInfo]);
}
