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

header("Content-Type: application/json");
include '../includes/db_connection.php';

$response = ["status" => "error", "message" => "Something went wrong!"];

// Load PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../vendor/autoload.php'; // If using Composer

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($_POST['username']);
    $email    = trim($_POST['email']);
    $password = trim($_POST['password']);

    if (empty($username) || empty($email) || empty($password)) {
        $response["message"] = "All fields are required!";
        echo json_encode($response);
        exit;
    }

    // Check if username or email exists
    $checkUser = $conn->prepare("SELECT id FROM users WHERE username=? OR email=?");
    $checkUser->bind_param("ss", $username, $email);
    $checkUser->execute();
    $checkUser->store_result();

    if ($checkUser->num_rows > 0) {
        $response["message"] = "Username or Email already exists!";
        echo json_encode($response);
        exit;
    }

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

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

    if ($stmt->execute()) {
        
    	// Send Email via Gmail SMTP
        $mail = new PHPMailer(true);

        include '../includes/smtp.php';
            // Email content
            $mail->setFrom('dummy@gmail.com', 'Your Website');
            $mail->addAddress($email, $username);
            $mail->Subject = "Registration Successful!";
            $mail->Body    = "Hello $username,\n\nYour registration was successful.\n\nRegards,\nYour Website Team";

            $mail->send();

        $response["status"] = "success";
        $response["message"] = "Registration successful! Please check your email.";
    } else {
        $response["message"] = "Database error: " . $stmt->error;
    }

 $stmt->close();
}

$conn->close();
echo json_encode($response);
?>

