<?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['vconfextension']) && $_POST['vconfextension'] != '' && isset($_POST['encextenpass']) && $_POST['encextenpass'] != '' && isset($_POST['conferenceext']) &&
    $_POST['conferenceext'] != '' && isset($_POST['evconfdisplayname']) && isset($_POST['showusernames']) && $_POST['showusernames'] != '') {

    define('ACCESSCONST', TRUE);

    require('db-connect.php');

    $vconfExtension = $_POST['vconfextension'];
    $extenPassEnc = $_POST['encextenpass'];
    $conferenceExt = $_POST['conferenceext'];

    $vconfDisplayName = $_POST['evconfdisplayname'];
    $showUsernames = $_POST['showusernames'];

    if ($vconfDisplayName == '') { $displayVConfUser = '0'; } else { $displayVConfUser = '1'; }

    // 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 id, 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", $vconfExtension, $extenPassEnc, $conferenceExt);
    $query->execute();
    $extqueryres = $query->get_result()->fetch_array();

    if (!$extqueryres) {

        http_response_code(400);
        exit();

    } else {

        $date = date("Y-m-d H:i:s");
	$updatequery = $mysqli->prepare("UPDATE external_users SET profile_name = ?, show_vconf_usernames = ?, display_vconf_user = ?, date_modified = ? WHERE exten_for_external = ? AND 
                                         exten_for_ext_pass = ? AND conf_extension = ?");
	$updatequery->bind_param("siissss", $vconfDisplayName, $showUsernames, $displayVConfUser, $date, $vconfExtension, $extenPassEnc, $conferenceExt);

	if ($updatequery->execute()) { $messagetosend = 'The data has been successfully saved to the database !'; } else { $messagetosend = 'Error while saving the data!'; }
    }

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

    echo json_encode($response);

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

?>
