<?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 user for which we want to get the external user data
    $enabled = 1;
    $query1 = $mysqli->prepare("SELECT id, userrole, username, enabled FROM app_users WHERE (userrole = 'admin' OR userrole = 'superadmin') AND BINARY username = ? AND enabled = ?");
    $query1->bind_param("si", $username, $enabled);
    $query1->execute();
    $queryres = $query1->get_result()->fetch_assoc();
    $userID = $queryres['id'];

    $extdatafromdb = [];

    if ($userID != '') {

	    // Get the data for the current user from the 'external_users' table
	    $querysel = $mysqli->prepare("SELECT id, userid, profile_name, exten_for_external, exten_for_ext_pass, conf_extension, conf_tag, conf_access_link FROM external_users WHERE userid = ?");
            $querysel->bind_param("s", $userID);
            $querysel->execute();
            $queryselres = $querysel->get_result();

            while ($extUserDataRow = $queryselres->fetch_assoc()) {

                    $extenforexternal = $extUserDataRow['exten_for_external'];

		    if ($extUserDataRow['exten_for_ext_pass'] != '' && $extUserDataRow['exten_for_ext_pass'] != null && $extUserDataRow['exten_for_ext_pass'] != 'undefined') {
			     $sippassword = "%20%20%20%20%20%20%20";
		    } else { $sippassword = ''; }

                    $confExtension = $extUserDataRow['conf_extension'];
                    $confTag = $extUserDataRow['conf_tag'];
                    $confaccesslink = $extUserDataRow['conf_access_link'];

                   $extdatafromdb[] = ['exten_for_external' => $extenforexternal, 'exten_for_ext_pass' => $sippassword, 'conf_extension' => $confExtension, 'conf_tag' => $confTag, 'conf_access_link' => $confaccesslink];
            }
    }
    echo json_encode($extdatafromdb);

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

?>
