<?php
    //Author: Ralfs Lāns
    //Created: 19.03.2024
    //Editor: Artūrs Mūrnieks
    //Modified: 19.03.2024

    session_start();
    require "conn.php";
    $username = "";
    $errors = array();

    // Signup
    if(isset($_POST['signup'])){
        $username = mysqli_real_escape_string($conn, $_POST['username']);
        $password = mysqli_real_escape_string($conn, $_POST['password']);
        $cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']);
        if($password !== $cpassword){
            $errors['password'] = "Confirm password not matched!";
        }
        $username_check = "SELECT * FROM users WHERE username = '$username'";
        $res = mysqli_query($conn, $username_check);
        if(mysqli_num_rows($res) > 0){
            $errors['username'] = "Username that you have entered is already exist!";
        }
        if(count($errors) === 0){
            $encpass = password_hash($password, PASSWORD_BCRYPT);
            $insert_data = "INSERT INTO users (username, password) values('$username', '$encpass')";
            echo $insert_data;
            $data_check = mysqli_query($conn, $insert_data);
            if($data_check){
                $_SESSION['username'] = $username;
                $_SESSION['password'] = $password;
                header('location: index.php');
                exit();
            }else{
                $errors['db-error'] = "Failed while inserting data into database!";
            }
        }
    }

    // Login
    if(isset($_POST['login'])){
        $username = mysqli_real_escape_string($conn, $_POST['username']);
        $password = mysqli_real_escape_string($conn, $_POST['password']);
        $check_username = "SELECT * FROM users WHERE username = '$username'";
        $res = mysqli_query($conn, $check_username);
        if(mysqli_num_rows($res) > 0){
            $fetch = mysqli_fetch_assoc($res);
            $fetch_pass = $fetch['password'];
            if(password_verify($password, $fetch_pass)){
                $_SESSION['username'] = $username;
                $_SESSION['password'] = $password;
                header('location: index.php');
                exit();
            }else{
                $errors['username'] = "Incorrect username or password!";
            }
        }else{
            $errors['username'] = "It's look like you're not yet a member! Click on the bottom link to signup.";
        }
    }