<?php
session_start();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SESSION['usr_accountId']) && isset($_SESSION['receipt_id'])) {

    $accountId = $_SESSION['usr_accountId'];
    $receipt_id = $_SESSION['receipt_id'];
    $receipt_file = $_FILES["receipt_file"]["name"];
    $receipt_file_name = "payment_receipts/" . $_SESSION['usr_accountId'] . "_" . basename($receipt_file);
    $target1 = "../" . $receipt_file_name;

    $sql = "SELECT * FROM invoices WHERE id =? AND accountId=? LIMIT 1";

    $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
    $sth->execute([$receipt_id, $accountId]);
    $coin_invoice = $sth->fetchAll();

    if (count($coin_invoice) > 0) {
        foreach ($coin_invoice as $key => $value) {

            $method = $value['method'];
            $usd_amount = $value['usd_amount'];
            $coin_amount = $value['coin_amount'];
            $address = $value['address'];
            $receipt = $value['receipt'];
            $status = $value['status'];

            if ($status != 1) {
                if ($receipt == "default") {
                    if (move_uploaded_file($_FILES["receipt_file"]["tmp_name"], $target1)) {
                        $payment_invoice_sql = "UPDATE invoices SET receipt=?  WHERE id=? AND accountId=?";
                        $update_invoice = $conn->prepare($payment_invoice_sql)->execute([$receipt_file_name, $receipt_id, $accountId]);
                        if ($update_invoice) {
                            die("success");
                        } else {
                            die('An unexpected error occurred. Please try again.');
                        }
                    } else {
                        die("An unexpected error occurred.");
                    }
                } else {
                    die("Payment receipt already uploaded.");
                }
            } else {
                die("Invoice already approved.");
            }
        }
    } else {
        die("Invoice not found.");
    }
} else {
    die('Invalid request.');
}