<?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'];
    $audioConfExtension = $_POST['audio_conf_extension'];

    // Get the id and role of the current user from the 'app_users' table
    $querysel = $mysqli->prepare("SELECT id, userrole, username FROM app_users WHERE BINARY username = ?");
    $querysel->bind_param("s", $username);
    $querysel->execute();
    $confdatafromdb = $querysel->get_result()->fetch_assoc();
    $cruserid = $confdatafromdb['id'];
    $cruserrole = $confdatafromdb['userrole'];

    if ($cruserrole == 'superadmin') {

        // Remove the audio conference data from the 'conferences_audio' table
        $querydel = $mysqli->prepare("DELETE FROM conferences_audio WHERE audio_conf_extension = ?");
        $querydel->bind_param("s", $audioConfExtension);

        if ($querydel->execute()) { $messagetosend = 'success'; } else { $messagetosend = 'Error while removing the data !'; }

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

        // Get the id of the user who saved this conference data
        $queryfd = $mysqli->prepare("SELECT id, userid, audio_conf_extension FROM conferences_audio WHERE audio_conf_extension = ?");
        $queryfd->bind_param("s", $audioConfExtension);
        $queryfd->execute();
        $confdatadb = $queryfd->get_result()->fetch_assoc();
        $useridfdb = $confdatadb['userid'];

        if ($useridfdb == $cruserid) {

            // Remove the audio conference data from the 'conferences_audio' table
            $querydelad = $mysqli->prepare("DELETE FROM conferences_audio WHERE userid = ? AND audio_conf_extension = ?");
            $querydelad->bind_param("is", $cruserid, $audioConfExtension);

            if ($querydelad->execute()) { $messagetosend = 'success'; } else { $messagetosend = 'Error while removing the data !'; }

        } else { $messagetosend = "You are not allowed to remove this conference data!"; }

    } elseif ($cruserrole == 'regular_user') { $messagetosend = 'Only Admins and Superadmins can remove conference data!'; }

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

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

?>