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

// Load environment config
require_once 'env.php';
require_once 'mailer/src/PHPMailer.php';
require_once 'mailer/src/SMTP.php';
require_once 'mailer/src/Exception.php';

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

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $email = $_POST["email"] ?? '';
    $password = $_POST["password"] ?? '';
    $token = bin2hex(random_bytes(32)); // 64 char random token

    if (!$email || !$password) {
        die("Email and password are required.");
    }

    // Hash password
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    // Connect to DB
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die("Database connection failed: " . $conn->connect_error);
    }
    
    // Before inserting, check if email already exists
$stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    echo "This email is already registered.";
    exit();
}

    // Insert user
    $stmt = $conn->prepare("INSERT INTO users (email, password, token) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $email, $hashedPassword, $token);

    if ($stmt->execute()) {
        // Send verification email
        $mail = new PHPMailer(true);
        try {
            // SMTP config
            $mail->isSMTP();
            $mail->Host = MAIL_HOST;
            $mail->SMTPAuth = true;
            $mail->Username = MAIL_USERNAME;
            $mail->Password = MAIL_PASSWORD;
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;

            // Sender info
            $mail->setFrom(MAIL_FROM, MAIL_FROM_NAME);
            $mail->addAddress($email);

            // Email content
            $mail->isHTML(true);
            $mail->Subject = 'Verify your email - Gobolcoin';
            $verificationLink = "https://{$_SERVER['HTTP_HOST']}/auth/verify.php?email=" . urlencode($email) . "&token=" . $token;
            $mail->Body = "Click the link below to verify your email:<br><a href='$verificationLink'>$verificationLink</a>";

            $mail->send();
            echo "Signup successful! Please check your email to verify.";
        } catch (Exception $e) {
            echo "Signup saved but email not sent. Mailer Error: {$mail->ErrorInfo}";
        }
    } else {
        echo "Signup failed: " . $stmt->error;
    }

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

<!-- Simple HTML signup form -->
<!DOCTYPE html>
<html>
<head>
    <title>Signup - Gobolcoin</title>
</head>
<body>
    <h2>Signup</h2>
    <form method="POST" action="">
        <label>Email:</label><br>
        <input type="email" name="email" required><br><br>

        <label>Password:</label><br>
        <input type="password" name="password" required><br><br>

        <button type="submit">Sign Up</button>
    </form>
</body>
</html>
