<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo "This endpoint accepts POST requests only.";
    exit();
}

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

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

// DB Connection
$conn = new mysqli("localhost", "gobolcha_gobolchain", "@Jibala1997", "gobolcha_gobolchain");
if ($conn->connect_error) {
    die("Database connection failed.");
}

// Get and validate email
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    die("Invalid email address.");
}

// Check if email exists - use bind_result instead of get_result
$stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($user_id);
$emailExists = $stmt->fetch();
$stmt->close();

if (!$emailExists) {
    die("If the email is registered, a reset link will be sent.");
}

// Generate token
$token = bin2hex(random_bytes(32));
$expires = date("Y-m-d H:i:s", strtotime("+1 hour"));

// Ensure password_resets table exists
$conn->query("CREATE TABLE IF NOT EXISTS password_resets (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(255) NOT NULL,
    token VARCHAR(255) NOT NULL,
    expires_at DATETIME NOT NULL
)");

// Delete old tokens for this email
$del = $conn->prepare("DELETE FROM password_resets WHERE email = ?");
$del->bind_param("s", $email);
$del->execute();
$del->close();

// Insert new reset token
$stmt = $conn->prepare("INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $email, $token, $expires);
$stmt->execute();
$stmt->close();

// Build reset link - REMOVED SPACE after token=
$resetLink = "https://gobolchain.com/reset-password.html?token=" . urlencode($token);

// Send email
$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = 'mail.gobolchain.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'team@gobolchain.com';
    $mail->Password = '@Jibala1997';
    $mail->SMTPSecure = 'ssl';  // Changed to SSL
    $mail->Port = 465;          // Changed to 465

    $mail->setFrom('team@gobolchain.com', 'Gobolchain Support');
    $mail->addAddress($email);
    $mail->isHTML(true);
    $mail->Subject = 'Password Reset Request';

    $mail->Body = "
        <div style='font-family: Arial, sans-serif; background-color:#f9f9f9; padding: 20px; border-radius: 10px;'>
            <h2 style='color: #8B0000;'>Password Reset Request</h2>
            <p>We received a request to reset your password on the <strong>Gobolchain Network</strong>.</p>
            <p>Click the button below to reset your password. This link will expire in 1 hour.</p>
            <a href='{$resetLink}' style='display:inline-block; padding: 12px 20px; margin: 20px 0; background-color:#8B0000; color:white; text-decoration:none; border-radius:5px;'>Reset Your Password</a>
            <p>If you didn't request this, you can safely ignore this email.</p>
            <br>
            <p style='font-size: 0.9em; color: #555;'>Sent by Gobolchain Support &bull; team@gobolchain.com</p>
        </div>
    ";

    $mail->send();

    header("Location: link-sent.html");
    exit();

} catch (Exception $e) {
    echo "Email could not be sent. Mailer Error: " . $mail->ErrorInfo;
}
?>