<?php
/**
 *  Copyright (C) 2022, 2024  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();

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

 define('ACCESSCONST', TRUE);

 require('db-connect.php');

    $username = $_POST['username'];
    $extenForExternal = $_POST['exten_for_external'];

    // Get the id of the user for which we want to remove the extension for external access
    $enabled = 1;
    $selectid = $mysqli->prepare("SELECT id, userrole, username, enabled FROM app_users WHERE (userrole = 'admin' OR userrole = 'superadmin') AND BINARY username = ? AND enabled = ?");
    $selectid->bind_param("si", $username, $enabled);
    $selectid->execute();
    $queryres = $selectid->get_result()->fetch_assoc();
    $userID = $queryres['id'];

    // Remove the row corresponding to the specified user and extension from the 'external_users' table
    $removequery = $mysqli->prepare("DELETE FROM external_users WHERE userid = ? AND exten_for_external = ?");
    $removequery->bind_param("is", $userID, $extenForExternal);

    if ($removequery->execute()) { $messagetosend = 'The data has been successfully removed from the database !'; } else { $messagetosend = 'Error while removing the data from the database !'; }
    $removequery->close();

    // Remove the password file for the extension whose data has been removed from the 'external_users' table
    if (file_exists("../restr/".$username."/externalext/".$extenForExternal)) {
        $removefile = exec("rm ../restr/".$username."/externalext/".$extenForExternal);
    }

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

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

?>
