<?php
include "../../classes/autoload.php";
?>

<h2>Payment History</h2>
<table class="width_100">
    <tr>
        <th>Date</th>
        <th>Amount</th>
    </tr>
    <?php
    $payment_history_res = $db->query("payments", "SELECT * FROM payments WHERE invoice_id = {$_GET['invoice_id']}");
    $payments_total = 0;
    if ($payment_history_res->num_rows > 0) {
        while ($payment_his = $payment_history_res->fetch_assoc()) {
            echo "<tr>";
            echo "<td>{$payment_his['date_time']}</td>";
            echo "<td>R " . number_format($payment_his['amount'],2) . "</td>";
            echo "</tr>";
            $payments_total += $payment_his['amount'];
        }


        echo "<tr>";
        echo "<td><b>PAYMENTS TOTAL</b></td>";
        echo "<td><b>R " . number_format($payments_total, 2) . "</b></td>";
        echo "</tr>";

        $invoice_details_res = $db->query("invoice_list", "SELECT * FROM invoice_list WHERE invoice_id = {$_GET['invoice_id']}");
        $invoice_total = 0;
        if ($invoice_details_res->num_rows > 0) {
            while ($invoice_list = $invoice_details_res->fetch_assoc()) {
                $invoice_total += (float) $invoice_list['price'] * (float) $invoice_list['qty'] * 1.15;
            }
        }

        echo "<tr>";
        echo "<td><b>INVOICE TOTAL<b></td>";
        echo "<td><b>R " . number_format($invoice_total, 2) . "</b></td>";
        echo "</tr>";

        echo "<tr>";
        echo "<td><b>NETT</b></td>";
        echo "<td><b id='nett'>R " . number_format($invoice_total - $payments_total, 2) . "</b></td>";
        echo "</tr>";

    } else {
        ?>
        <tr>
            <td colspan="2">NO PAYMENTS YET</td>
        </tr>
        <?php

        $invoice_details_res = $db->query("invoice_list", "SELECT * FROM invoice_list WHERE invoice_id = {$_GET['invoice_id']}");
        $invoice_total = 0;
        if ($invoice_details_res->num_rows > 0) {
            while ($invoice_list = $invoice_details_res->fetch_assoc()) {
                $invoice_total += (float) $invoice_list['price'] * (float) $invoice_list['qty'] * 1.15;
            }
        }

        echo "<tr>";
        echo "<td><b>INVOICE TOTAL<b></td>";
        echo "<td><b>R " . number_format($invoice_total, 2) . "</b></td>";
        echo "</tr>";

        echo "<tr>";
        echo "<td><b>NETT</b></td>";
        echo "<td><b id='nett'>R " . number_format($invoice_total - $payments_total, 2) . "</b></td>";
        echo "</tr>";
    }

    ?>
</table>