<?php
include("../classes/manager.class.php");
$m = new Manager();
$id = $_REQUEST['id'];

if ($id) {
    $purchaseId = $id;

    // Fetch the purchase details from the database
    $purchase = PurchaseSetup::GetPurchaseSetupById($purchaseId);

    if ($purchase) {
        // Initialize total deductions
        $totalPaidAmount = 0;
        $totalWithholdingTax = 0;

        // Fetch payments related to the purchase ID
        $payments = Purpayment::GetPurpaymentList("WHERE purchase_reference_code = '$purchaseId' AND supplier_payment_type = 'supplier'");

        if ($payments) {
            // Calculate total paid amounts and withholding tax
            foreach ($payments as $payment) {
                $totalPaidAmount += $payment->amount_payable;
                $totalWithholdingTax += $payment->withholding_tax_amount;
            }
        }

        // Calculate the remaining amount
        $remainingAmount = $purchase->total_amount - ($totalPaidAmount + $totalWithholdingTax);
      	 // Round the remaining amount to 2 decimal places
        $remainingAmount1 = round($remainingAmount, 2);

        // Return only the remaining amount
        echo json_encode(array('remaining_amount' => $remainingAmount1));
    } else {
        // Return an error message if no purchase is found
        echo json_encode(array('error' => 'No purchase found'));
    }
}
?>
