<?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 current user from the 'app_users' table
    $queryselid = $mysqli->prepare("SELECT id, username FROM app_users WHERE BINARY username = ?");
    $queryselid->bind_param("s", $username);
    $queryselid->execute(); 
    $queryselid = $queryselid->get_result()->fetch_assoc();
    $userid = $queryselid['id'];

    // Get the Roundcube password and Roundcube basic auth password for the current user from the 'email_conf' table
    $querysel = $mysqli->prepare("SELECT userid, rcdomain, rcuser, rcpassword, rcbasicauthuser, rcbasicauthpass FROM email_conf WHERE userid = ?");
    $querysel->bind_param("i", $userid);
    $querysel->execute();
    $confdatafromdb = $querysel->get_result()->fetch_assoc();


    // Decrypt the Roundcube password (if any) and Roundcube basic auth password (if any), fetched from the database

    if ($confdatafromdb['rcpassword'] != '' && $confdatafromdb['rcpassword'] != null && $confdatafromdb['rcpassword'] != 'undefined') {

        $psswdaddedkeyrc = file_get_contents('../restr/'.$username.'/pwdkeyrc');
        $rcpasswdinit = $confdatafromdb['rcpassword'];
        $componentrcpass = explode(':', $rcpasswdinit);

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

        $rcpassworddec = openssl_decrypt($encpwdin, 'AES-256-CBC', $psswdaddedkeyrc, false, $ivkey);

        $confdatafromdb['rcpassword'] = $rcpassworddec;

    } else { $confdatafromdb['rcpassword'] = ''; }

    if ($confdatafromdb['rcbasicauthpass'] != '' && $confdatafromdb['rcbasicauthpass'] != null && $confdatafromdb['rcbasicauthpass'] != 'undefined') {

        $psswdaddedkeyrcba = file_get_contents('../restr/'.$username.'/pwdkeyrcba');
        $rcbapasswdinit = $confdatafromdb['rcbasicauthpass'];
        $componentrcbapass = explode(':', $rcbapasswdinit);

        $baencpwdin = $componentrcbapass[0];
        $baivkey = $componentrcbapass[1];

        $rcbapassworddec = openssl_decrypt($baencpwdin, 'AES-256-CBC', $psswdaddedkeyrcba, false, $baivkey);

        $confdatafromdb['rcbasicauthpass'] = $rcbapassworddec;

    } else { $confdatafromdb['rcbasicauthpass'] = ''; }

    $datafromdb = $confdatafromdb;

    echo json_encode($datafromdb);

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

?>