<?php
/**
 *  Copyright (C) 2021  Double Bastion LLC
 *
 *  This file is part of Roundpin, which is licensed under the
 *  GNU Affero General Public License Version 3.0. The license terms
 *  are detailed in the "LICENSE.txt" file located in the root directory.
 */

session_start();

 // header('Set-Cookie: PHPSESSID= ' . session_id() . '; SameSite=strict; Secure=true; HttpOnly=true;');

if (isset($_POST['s_ajax_call']) && ($_POST['s_ajax_call'] == $_SESSION['validate_s_access']) && $_POST['username'] == $_SESSION['loginname']) {

    define('ACCESSCONST', TRUE);
    require('db-connect.php');

    $username = $_POST['username'];
    $usergroup = $_POST['newgroup'];

    // Get the role and id of the user who creates the group, from the 'app_users' table
    $queryprm = $mysqli->prepare("SELECT id, userrole, username FROM app_users WHERE username = ?");
    $queryprm->bind_param("s", $username);
    $queryprm->execute();
    $queryprmres = $queryprm->get_result()->fetch_assoc();
    $cruserrole = $queryprmres["userrole"];
    $cruserid = $queryprmres["id"];

    if ($cruserrole == 'admin' || $cruserrole == 'superadmin') {

        $queryingr = $mysqli->prepare("INSERT INTO groups (userid, group_name) VALUES (?, ?)");
        $queryingr->bind_param("is", $cruserid, $usergroup);

	if ($queryingr->execute()) { $messagetosend = 'success'; } else { $messagetosend = 'An error occurred while attempting to save the group to the database!'; }

    } else { $messagetosend = 'Only Admins and Superadmins can create new groups.'; }

    $response = array('result' => $messagetosend);
    echo json_encode($response);

} else {
    header("Location: ../login.php");
}

?>