<?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['currentvconfext']) && 
    $_POST['currentvconfext'] != '' && isset($_POST['currentvconfpubkey']) && $_POST['currentvconfpubkey'] != '' && isset($_POST['currentvconfprivkey']) && 
    $_POST['currentvconfprivkey'] != '') {

       define('ACCESSCONST', TRUE);

       require('db-connect.php');

       $extForExternal = $_POST['vconfextension'];
       $extenPassEnc = $_POST['encextenpass'];

       $vconfExtension = $_POST['currentvconfext'];
       $chatPubKey = $_POST['currentvconfpubkey'];
       $chatPrivKey = $_POST['currentvconfprivkey'];

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

       if (!$extqueryres) {

           http_response_code(400);
           exit();

       } else {

	       // Create the necessary directory if it doesn't exist
	       if (!is_dir('../textchat/' . $vconfExtension)) {
		    mkdir('../textchat/' . $vconfExtension, 0700);
	       }

	       // Save the RSA keys
	       if ($vconfExtension != '') {

		   if (!file_exists('../textchat/' . $vconfExtension . '/rsa_1024_pub.pem') || !file_exists('../textchat/' . $vconfExtension . '/rsa_1024_priv.pem')) {

			$savePubKey = file_put_contents('../textchat/' . $vconfExtension . '/rsa_1024_pub.pem', $chatPubKey);
			chmod('../textchat/' . $vconfExtension . '/rsa_1024_pub.pem', 0600);

			$savePrivKey = file_put_contents('../textchat/' . $vconfExtension . '/rsa_1024_priv.pem', $chatPrivKey);
			chmod('../textchat/' . $vconfExtension . '/rsa_1024_priv.pem', 0400);

			$messageres = 'success';

		   } else { $messageres = 'success'; }

	       } else { 
		     $messageres = 'failure';
	       }

       }

       $generateresp = ['messageres' => $messageres];

       echo json_encode($generateresp);

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

?>