<?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']) && isset($_POST['currenttconfext']) && $_POST['currenttconfext'] != '' &&
    isset($_POST['currenttconfpubkey']) && $_POST['currenttconfpubkey'] != '' && isset($_POST['crnttconfprivkey']) && $_POST['crnttconfprivkey'] != '') {

       $tconfExtension = $_POST['currenttconfext'];
       $chatPubKey = $_POST['currenttconfpubkey'];
       $chatPrivKey = $_POST['crnttconfprivkey'];

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

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

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

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

		$savePrivKey = file_put_contents('../textchat/' . $tconfExtension . '/rsa_1024_priv.pem', $chatPrivKey);
		chmod('../textchat/' . $tconfExtension . '/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");
}

?>
