<?php
session_start();

require("../includes/db_connect.php");


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if ((!empty($_SESSION['adm_accountId'])) && (!empty($_SESSION['charges_approve_receipt'])) && (!empty($_SESSION['charges_approve_accountId'])) && (!empty($_POST['amount_received']))) {

        if ($conn) {
            try {

                $approve_receipt = $_SESSION['charges_approve_receipt'];
                $approve_accountId = $_SESSION['charges_approve_accountId'];
                // $approve_account = $_SESSION['approve_account'];

                $amount_received = round($_POST['amount_received'], 2);


                $sql = "SELECT * FROM charges_invoices WHERE id =? AND accountId=? LIMIT 1";
                $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                $sth->execute([$approve_receipt, $approve_accountId]);
                $coin_invoice = $sth->fetchAll();

                if (count($coin_invoice) > 0) {

                    foreach ($coin_invoice as $key => $value) {

                        $id = $value['id'];
                        $accountId = $value['accountId'];
                        // $package = $value['package'];
                        $method = $value['method'];
                        $usd_amount = $value['usd_amount'];
                        $coin_amount = $value['coin_amount'];
                        $address = $value['address'];
                        $status = $value['status'];
                        $date = $value['date'];

                        if ($status == 0) {

                            $balance_sql = "SELECT * FROM charges_invoices WHERE accountId=? LIMIT 1";
                            $balance_sth = $conn->prepare($balance_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                            $balance_sth->execute([$accountId]);
                            $account_balances = $balance_sth->fetchAll();

                            // foreach ($account_balances as $key => $value) {
                            //     $usr_balance = $value['balance'];

                            //     $acc_balance = round($usr_balance, 2);

                            //     $new_balance = round(($acc_balance + $amount_received), 2);

                            //     $new_balance_sql = "UPDATE wallet SET balance=? WHERE accountId=?";

                            //     $update_balance = $conn->prepare($new_balance_sql)->execute([$new_balance, $accountId]);

                            //     if ($update_balance) {

                                    $sql = 'UPDATE charges_invoices SET status=1,usd_amount_received=? WHERE id =? AND accountId=?';

                                    $stmt = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
                                    $stmt->execute([$amount_received,$approve_receipt, $approve_accountId]);

                                    // if ($stmt) {

                                        // $req_sql = "INSERT INTO transaction_history (accountId, name, amount, type, status) VALUES (?,?,?,?,?)";

                                        // $trans_name = "Deposit";

                                        // $create_history = $conn->prepare($req_sql)->execute([$accountId, "Wallet", $amount_received, $trans_name, 1]);

                                        unset($_SESSION['charges_approve_receipt']);
                                        unset($_SESSION['charges_approve_accountId']);
                                        // unset($_SESSION['approve_account']);
                                        die("success");
                                    // } else {
                                    //     die("Unable to delete invoice!");
                                    // }
                                // } else {
                                //     die("Unable to update account balance!");
                                // }
                            // }
                        } else {
                            die("Invoice has already been approved.");
                        }
                    }
                } else {
                    die("Invoice not found.");
                }
            } catch (PDOException $e) {
                die('An unexpected error occurred. Connection failed');
            }
        } else {
            die('An unexpected error occurred. Connection failed.');
        }
    } else {
        die('Invalid request!');
    }
} else {
    die('Invalid request!');
}


function redirect()
{
    die("Invalid request!");
}