<?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['crsipusername']) && $_POST['crsipusername'] != '' && isset($_POST['encextenpass']) && $_POST['encextenpass'] != '' &&
    isset($_POST['crvconfextension']) && $_POST['crvconfextension'] != '') {

    define('ACCESSCONST', TRUE);

    require('db-connect.php');

    $crsipusername = $_POST['crsipusername'];
    $extenPassEnc = $_POST['encextenpass'];
    $conferenceExt = $_POST['crvconfextension'];

    // Check if the received external user extension, the corresponding encrypted password and the extension of the conference, match the data in the 'external_users' table
    $query = $mysqli->prepare("SELECT exten_for_external, exten_for_ext_pass, conf_extension FROM external_users WHERE exten_for_external = ? AND exten_for_ext_pass = ? AND conf_extension = ?");
    $query->bind_param("sss", $crsipusername, $extenPassEnc, $conferenceExt);
    $query->execute();
    $extqueryres = $query->get_result()->fetch_array();

    if (!$extqueryres) {

        http_response_code(400);
        exit();

    } else {

        // Check if the current user has been banned from accessing this conference
        $queryselck = $mysqli->prepare("SELECT banned_sipusername, conf_extension, banned_until FROM banned_users WHERE banned_sipusername = ? AND conf_extension = ?");
        $queryselck->bind_param("ss", $crsipusername, $conferenceExt);
        $queryselck->execute();
        $userdatafromdbck = $queryselck->get_result()->fetch_assoc();

        if ($userdatafromdbck) {

            $currentDate = new DateTime(date("Y-m-d H:i:s"));
            $banDate = new DateTime($userdatafromdbck['banned_until']);

            if ($currentDate <= $banDate) {
                $banmessage = 'failure'; 
            } else { 
                $banmessage = 'success';

                // Remove the database record, since the ban time has expired
                $querydel = $mysqli->prepare("DELETE FROM banned_users WHERE banned_sipusername = ? AND conf_extension = ?");
                $querydel->bind_param("ss", $crsipusername, $conferenceExt);
                $querydel->execute();
            }

        } else { $banmessage = 'success'; }
    }

    $response = array('notbanned' => $banmessage);

    echo json_encode($response);

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

?>
