<!-- Author  Raivis Rampāns
Created 12.03.2025
Editor Raivis
Modified 12.03.2025
Description: The file that takes care of user registrations and logins -->

<?php
session_start();
require "conn.php";

$username = "";
$email = "";
$errors = array();

// Register
if (isset($_POST['signup'])) {
    $username = trim(mysqli_real_escape_string($conn, $_POST['username']));
    $email = trim(mysqli_real_escape_string($conn, $_POST['email']));
    $password = mysqli_real_escape_string($conn, $_POST['password']);
    $cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']);

    if ($password !== $cpassword) {
        $errors['password'] = "The passwords don't match!";
    }

    // Pārbauda, vai lietotājvārds vai epasts jau eksistē
    $stmt = $conn->prepare("SELECT username, email FROM users WHERE username = ? OR email = ?");
    $stmt->bind_param("ss", $username, $email);
    $stmt->execute();
    $stmt->store_result();
    
    if ($stmt->num_rows > 0) {
        $stmt->bind_result($existing_username, $existing_email);
        while ($stmt->fetch()) {
            if ($existing_username === $username) {
                $errors['username'] = "That username already exists!";
            }
            if ($existing_email === $email) {
                $errors['email'] = "That email is already registered!";
            }
        }
    }
    $stmt->close();

    if (count($errors) === 0) {
        $encpass = password_hash($password, PASSWORD_BCRYPT);
        $stmt = $conn->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $username, $email, $encpass);
        if ($stmt->execute()) {
            $_SESSION['username'] = $username;
            $_SESSION['email'] = $email;
            $_SESSION['user_id'] = $conn->insert_id;
            header('location: index.php');
            exit();
        } else {
            $errors['db-error'] = "Failed while inserting data into database!";
        }
        $stmt->close();
    }
}

// Login
if(isset($_POST['login'])){
    $email = trim($_POST['email']); // Noņem liekas atstarpes
    $password = trim($_POST['password']);

    if (empty($email) || empty($password)) {
        $_SESSION['login_error'] = "All fields are required!";
        header("Location: login.php");
        exit();
    }

    // Pārbauda, vai lietotājs eksistē
    $check_user = "SELECT * FROM users WHERE email = ?";
    $stmt = $conn->prepare($check_user);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $res = $stmt->get_result();

    if($res->num_rows > 0){
        $fetch = $res->fetch_assoc();
        $fetch_pass = $fetch['password'];

        if(password_verify($password, $fetch_pass)){
            $_SESSION['username'] = $fetch['username'];
            $_SESSION['email'] = $fetch['email'];
            $_SESSION['user_id'] = $fetch['id'];
            header('Location: index.php');
            exit();
        } else {
            $_SESSION['login_error'] = "Incorrect email or password!";
        }
    } else {
        $_SESSION['login_error'] = "No account found with that email!";
    }

    header("Location: login.php");
    exit();
}

// Ja ir kļūdas, saglabā tās sesijā un pāradresē uz atbilstošo lapu
if (!empty($errors)) {
    $_SESSION['errors'] = $errors;
    if (isset($_POST['signup'])) {
        header("Location: register.php");
    } else {
        header("Location: login.php");
    }
    exit();
}
?>