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

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

    // Remove the row(s) corresponding to the specified superadmin from the 'external_users' table
    $removequery = $mysqli->prepare("DELETE FROM external_users WHERE userid = ?");
    $removequery->bind_param("i", $userID);

    if ($removequery->execute()) { $messagetosend = 'success'; } else { $messagetosend = 'failure'; }
    $removequery->close();

    // Reindex the 'external_users' table
    $reindexset = $mysqli->prepare("SET @resetrec = 0");
    $reindexup = $mysqli->prepare("UPDATE external_users SET id = @resetrec := @resetrec + 1");
    $reindexalt = $mysqli->prepare("ALTER TABLE external_users auto_increment = 1");
    if ($reindexset->execute() && $reindexup->execute() && $reindexalt->execute()) {} else { $messagetosend = 'failure'; }

    // Remove the password files directory
    if (is_dir("../restr/".$username."/externalext")) {
        $removedir = exec("rm -rf ../restr/".$username."/externalext");
    }

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

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

?>