<?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 Phaxio 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 Phaxio key and secret from the 'fax_settings' table
    $query2 = $mysqli->prepare("SELECT userid, phax_api_key, phax_api_secret FROM fax_settings WHERE userid = ?");
    $query2->bind_param("i", $userID);
    $query2->execute();
    $fetchInfo = $query2->get_result()->fetch_assoc();
    $phaxioKeyEnc = $fetchInfo['phax_api_key'];
    $phaxioSecretEnc = $fetchInfo['phax_api_secret'];

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

    $psswdaddedkeysec = file_get_contents('../restr/' . $username . '/pwdphaxiosecret');
    $compsippsswdsec = explode(':', $phaxioSecretEnc);
    $encpwdinsec = $compsippsswdsec[0];
    $ivkeysec = $compsippsswdsec[1];
    $phaxioSecret = openssl_decrypt($encpwdinsec, 'AES-256-CBC', $psswdaddedkeysec, false, $ivkeysec);

    // Get the Phaxio balance
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://" . $phaxioKey . ":" . $phaxioSecret . "@api.phaxio.com/v2.1/account/status");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Accept: application/json"));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $responsephax = curl_exec($ch);
    $recdataphax = json_decode($responsephax, TRUE);
    $phaxbalresponse = $recdataphax['data']['balance'];
    $phaxioBalance = round(($phaxbalresponse / 100), 3);
    $phaxioreqsuccess = $recdataphax['success'];
    curl_close($ch);

    if ($phaxioreqsuccess) { $messagetosend = 'success'; } else { $messagetosend = 'failure'; }

    $respdata = ['messagetosend' => $messagetosend, 'phaxiobalance' => $phaxioBalance];

    echo json_encode($respdata);

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

?>