<?php

require_once __DIR__.'/../../../includes/auth.php';
requireLogin();
requirePermission('finance.manage');

require_once __DIR__.'/../../../config/database.php';

$company_id = $_SESSION['company_id'] ?? 0;

$invoice_id = (int)($_GET['invoice_id'] ?? 0);

/* ===============================
FETCH INVOICE
================================ */

$stmt = $pdo->prepare("
SELECT invoice_number,total,paid_total,balance
FROM invoices
WHERE id = ?
AND company_id = ?
");

$stmt->execute([$invoice_id,$company_id]);

$invoice = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$invoice){
die("Invoice not found.");
}

$breadcrumb = "Add Payment";
require_once __DIR__.'/../../../includes/layout.php';

?>

<div class="container">

<div class="page-header">
<h2>Add Payment</h2>
<p class="page-subtitle">
Record a payment for this invoice.
</p>
</div>


<!-- INVOICE SUMMARY -->

<div class="card" style="max-width:500px;margin-bottom:20px;">

<strong>Invoice #:</strong>
<?= htmlspecialchars($invoice['invoice_number']) ?><br><br>

<strong>Total:</strong>
R <?= number_format($invoice['total'],2) ?><br>

<strong>Paid:</strong>
R <?= number_format($invoice['paid_total'],2) ?><br>

<strong>Balance:</strong>
R <?= number_format($invoice['balance'],2) ?>

</div>


<!-- PAYMENT FORM -->

<div class="card" style="max-width:500px;">

<?php if($invoice['balance'] <= 0): ?>

<div style="padding:12px;background:#e8f7ee;border:1px solid #b6e3c6;border-radius:6px;">
<strong>Invoice already fully paid.</strong>
</div>

<?php else: ?>

<form method="POST" action="save.php">

<input type="hidden" name="invoice_id" value="<?= $invoice_id ?>">

<div class="form-group">

<label>Amount</label>

<input
type="number"
step="0.01"
name="amount"
required
value="<?= number_format($invoice['balance'],2,'.','') ?>"
class="form-control"
>

</div>


<div class="form-group">

<label>Payment Method</label>

<select
name="method"
class="form-control"
>

<option value="EFT">EFT</option>
<option value="Cash">Cash</option>
<option value="Card">Card</option>

</select>

</div>


<div class="form-group">

<label>Reference</label>

<input
type="text"
name="reference"
class="form-control"
placeholder="Payment reference / EFT reference"
>

</div>


<button type="submit" class="btn">
Save Payment
</button>

</form>

<?php endif; ?>

</div>

</div>

<?php require_once __DIR__.'/../../../includes/layout_footer.php'; ?>