<?php
session_start();

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

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

ini_set('display_errors', 1);
error_reporting(E_ALL);

$email = $_POST['email'] ?? '';

if (empty($email)) {
    die("Email is required.");
}

// Check if email exists in MySQL
$host = "localhost";
$dbname = "gobolcha_gobolchain";
$username = "gobolcha_gobolchain";
$password = "@Jibala1997";

$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
    exit("Connection failed.");
}

$stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();

// Use bind_result instead of get_result
$stmt->bind_result($user_id);
$emailFound = $stmt->fetch();

$stmt->close();
$conn->close();

// If not found in DB, check in JSON file
if (!$emailFound) {
    $jsonFile = "users/" . md5($email) . ".json";
    if (file_exists($jsonFile)) {
        $emailFound = true;
    }
}

// If email not found in either place
if (!$emailFound) {
    exit("Email not found");
}

// Generate 6-digit code
$code = rand(100000, 999999);
$_SESSION['verification_code'] = $code;
$_SESSION['email_to_verify'] = $email;

// Send email
$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = 'mail.gobolchain.com';  // Fixed: Use working SMTP host
    $mail->SMTPAuth = true;
    $mail->Username = 'team@gobolchain.com';  // Fixed: Use .com not .info
    $mail->Password = '@Jibala1997';
    $mail->SMTPSecure = 'ssl';  // Use SSL with port 465
    $mail->Port = 465;

    $mail->setFrom('team@gobolchain.com', 'Gobolchain');
    $mail->addAddress($email);
    $mail->isHTML(true);
    $mail->Subject = 'Your Gobolchain Verification Code';
    $mail->Body    = "Your verification code is: <strong>$code</strong>";

    $mail->send();
    echo "Verification code sent";
} catch (Exception $e) {
    echo "Mailer Error: " . $mail->ErrorInfo;
}
?>