<?php
session_start(); // ✅ Required before setting session vars
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];
    $password = $_POST['password'];
    $confirmPassword = $_POST['confirm-password'];

    if ($password !== $confirmPassword) {
        echo "Paroles nesakrīt! <a href='index.html'>Mēģiniet vēlreiz</a>";
        exit;
    }

    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    $sql = "INSERT INTO users (email, password) VALUES (?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $email, $hashedPassword);

    if ($stmt->execute()) {
        $userId = $stmt->insert_id;

        $basicElements = ['🔥 uguns', '💧 ūdens', '🌎 zeme', '💨 gaiss'];
        foreach ($basicElements as $element) {
            $check = $conn->prepare("SELECT 1 FROM elements WHERE name = ? AND users_id = ?");
            $check->bind_param("si", $element, $userId);
            $check->execute();
            $check->store_result();

            if ($check->num_rows === 0) {
                $insert = $conn->prepare("INSERT INTO elements (name, users_id) VALUES (?, ?)");
                $insert->bind_param("si", $element, $userId);
                $insert->execute();
                $insert->close();
            }
            $check->close();
        }

        // ✅ Automatically log in and go to game
        $_SESSION['user_id'] = $userId;
        $_SESSION['email'] = $email;

        header("Location: game.html");
        exit;
    } else {
        echo "Kļūda: " . $stmt->error . "<br><a href='index.html'>Mēģiniet vēlreiz</a>";
    }

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