<?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'])) {

    define('ACCESSCONST', TRUE);

    require('db-connect.php');

    $username = $_POST['username'];
    $bannedExtension = $_POST['bannedsipusername'];
    $vconfExtension = $_POST['confextension'];
    $newBanDate = $_POST['nwbandate'] . " 00:00:00";

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

    if ($cruserrole == 'superadmin') {

        $queryrm = $mysqli->prepare("DELETE FROM `banned_users` WHERE `banned_sipusername`=? AND `conf_extension`=?");
        $queryrm->bind_param("ss", $bannedExtension, $vconfExtension);

        if ($queryrm->execute()) { $messagetosend = 'success'; } else { $messagetosend = 'An error occurred while attempting to remove ban data from the database!'; }

    } elseif ($cruserrole == 'admin') {

        // Check if the banned user has been banned by the current admin
        $querychck = $mysqli->prepare("SELECT ban_creator, banned_sipusername, conf_extension FROM banned_users WHERE banned_sipusername = ? AND conf_extension = ?");
        $querychck->bind_param("ss", $bannedExtension, $vconfExtension);
        $querychck->execute();
        $querychckres = $querychck->get_result()->fetch_assoc();
        $banCreator = $querychckres['ban_creator'];

        if ($banCreator == $username) {

            $queryadmrm = $mysqli->prepare("DELETE FROM `banned_users` WHERE `banned_sipusername`=? AND `conf_extension`=?");
            $queryadmrm->bind_param("ss", $bannedExtension, $vconfExtension);

            if ($queryadmrm->execute()) { $messagetosend = 'success'; } else { $messagetosend = 'An error occurred while attempting to remove ban data from the database!'; }

        } else { $messagetosend = 'You can unban only the users that were banned by you.'; }

    } elseif ($cruserrole == 'regular_user') {
              $messagetosend = 'Only Admins and Superadmins can change the ban time of a user.';
    }

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

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

?>
