<?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 user who asks for their Telnyx balance
    $query1 = $mysqli->prepare("SELECT id, username FROM app_users WHERE BINARY username = ?");
    $query1->bind_param("s", $username);
    $query1->execute();
    $queryres = $query1->get_result()->fetch_assoc();
    $userID = $queryres['id'];

    // Get the encrypted Telnyx key from the 'fax_settings' table
    $query2 = $mysqli->prepare("SELECT userid, tel_secret_key FROM fax_settings WHERE userid = ?");
    $query2->bind_param("i", $userID);
    $query2->execute();
    $fetchInfo = $query2->get_result()->fetch_assoc();
    $telnyxKeyEnc = $fetchInfo['tel_secret_key'];

    // Decrypt the key obtained from the 'fax_settings' table
    $psswdaddedkey = file_get_contents('../restr/' . $username . '/pwdtelnyxkey');
    $componentsippsswd = explode(':', $telnyxKeyEnc);
    $encpwdin = $componentsippsswd[0];
    $ivkey = $componentsippsswd[1];
    $telnyxKey = openssl_decrypt($encpwdin, 'AES-256-CBC', $psswdaddedkey, false, $ivkey);

    // Get the Telnyx balance
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.telnyx.com/v2/balance");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Accept: application/json", "Authorization: Bearer " . $telnyxKey));
    $responsetel = curl_exec($ch);
    if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200) { $messagetosend = 'success'; } else { $messagetosend = 'failure'; }
    $recdatatel = json_decode($responsetel, TRUE);
    $telbalresponse = $recdatatel['data']['balance'];
    $telnyxBalance = round(floatval($telbalresponse), 3);
    curl_close($ch);

    $respdata = ['messagetosend' => $messagetosend, 'telnyxbalance' => $telnyxBalance];

    echo json_encode($respdata);

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

?>
