<?php

require_once "../../../bootstrap.php";
require_once "Group.php";

use Backend\Models\Group;
use Backend\Models\Password;
use Backend\Models\GameJam;
use Illuminate\Support\Str;

$groupName = "";
$errors = array();

if(isset($_POST['regGroup'])){


    if(passwordValidate($pass = $_POST['password'])){
        $group = new Group();

        $group->gameJam()->associate(GameJam::find($_POST['gameJamId']));

        $group->group_name = $groupName = $_POST['groupName'];

        $group->group_amount = $_POST['groupAmount'];

        if(!$group->save()){
            http_response_code(500);
            exit();
        }

        $password = New Password();

        $password->group()->associate($group);

        $password->password = password_hash($pass ,PASSWORD_DEFAULT);

        $token = Str::random(100);

        $password->remember_token = $token;

        if(!$password->save()){
            http_response_code(500);
            exit();
        }

        $_SESSION['groupName'] = $groupName;
        $_SESSION['token'] = $token;
        $_SESSION['success'] = "You are now logged in";
        makeLogin($groupName,$group->id);
        http_response_code(201);
        echo json_encode(["message" => "you are login"]);

    }else{
        http_response_code(400);
        echo json_encode(["message" => "password not valid"]);
    }
}else{
    http_response_code(400);
}
