<?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'];

    // Get the role of the user who attempts to remove the ban, 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') {

        $queryup = $mysqli->prepare("UPDATE `banned_users` SET `banned_until`=? WHERE `banned_sipusername`=? AND `conf_extension`=?");
        $queryup->bind_param("sss", $newBanDate, $bannedExtension, $vconfExtension);

        if ($queryup->execute()) { $messagetosend = 'success'; } else { $messagetosend = 'An error occurred while attempting to save the ban date to 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) {

            $queryupadm = $mysqli->prepare("UPDATE `banned_users` SET `banned_until`=? WHERE `banned_sipusername`=? AND `conf_extension`=?");
            $queryupadm->bind_param("sss", $newBanDate, $bannedExtension, $vconfExtension);

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

        } else { $messagetosend = 'You can change the ban time only for the users that were banned by you.'; }

    } elseif ($cruserrole == 'regular_user') {
              $messagetosend = 'Only Admins and Superadmins can unban users.';
    }

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

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

?>