<?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 SIP password for the current user from the 'app_users' table
    $enabled = 1;
    $querysel = $mysqli->prepare("SELECT username, sip_password, enabled FROM app_users WHERE BINARY username = ? AND enabled = ?");
    $querysel->bind_param("si", $username, $enabled);
    $querysel->execute();
    $confdatafromdbinit = $querysel->get_result();
    $confdatafromdb = $confdatafromdbinit->fetch_assoc();


    // Decrypt the SIP password fetched from the database
//    if ($confdatafromdb['sip_password'] != '' && $confdatafromdb['sip_password'] != null && $confdatafromdb['sip_password'] != 'undefined') {
    if ($confdatafromdb['sip_password']) {

        $psswdaddedkey = file_get_contents('../restr/'.$username.'/pwdkey');

        $componentsippsswd = explode(':', $confdatafromdb['sip_password']);

	$encpwdin = $componentsippsswd[0];
	$ivkey = $componentsippsswd[1];

	$sippassworddec = openssl_decrypt($encpwdin, 'AES-256-CBC', $psswdaddedkey, false, $ivkey);

        $sipdatafromdb = $sippassworddec;

    } else { $sipdatafromdb = ''; }

    echo json_encode($sipdatafromdb);

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

?>
