<?php
require_once __DIR__.'/../../../includes/auth.php';
requireLogin();

$accountId = $_GET['account_id'] ?? 0;

if(!$accountId){
    die("Account ID missing");
}

/* CALL API */
ob_start();
$_GET['account_id'] = $accountId;
require __DIR__.'/../../../../api/statements/get.php';
$response = ob_get_clean();

$data = json_decode($response, true);

if(!$data || $data['status'] !== 'success'){
    die("Failed to load statement");
}

$account = $data['account'];
$transactions = $data['transactions'];
$closingBalance = $data['closing_balance'];
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Statement</title>

<style>
body { font-family: Arial; font-size:12px; }
table { width:100%; border-collapse: collapse; }
th, td { border:1px solid #ccc; padding:6px; }
th { background:#f4f4f4; }
.right { text-align:right; }
</style>
</head>

<body>

<h2>Account Statement</h2>

<p>
<strong>Customer:</strong> <?= $account['customer_name'] ?><br>
<strong>Account:</strong> <?= $account['account_name'] ?>
</p>

<table>
<thead>
<tr>
<th>Date</th>
<th>Type</th>
<th>Reference</th>
<th>Description</th>
<th class="right">Debit</th>
<th class="right">Credit</th>
<th class="right">Balance</th>
</tr>
</thead>

<tbody>
<?php foreach($transactions as $t): ?>
<tr>
<td><?= $t['date'] ?></td>
<td><?= $t['type'] ?></td>
<td><?= $t['reference'] ?></td>
<td><?= $t['description'] ?></td>
<td class="right"><?= number_format($t['debit'],2) ?></td>
<td class="right"><?= number_format($t['credit'],2) ?></td>
<td class="right"><?= number_format($t['balance'],2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<h3 style="text-align:right;">Closing Balance: R <?= number_format($closingBalance,2) ?></h3>

<script>
window.print();
</script>

</body>
</html>