<?php
require_once "../config/auth.php";
require_once "../config/db.php";
require_once "../config/helpers.php";

$pageTitle = "Add Payment";
require_once "../includes/header.php";
require_once "../includes/sidebar.php";
require_once "../includes/topbar.php";

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

// Invoice
$stmt = $conn->prepare("SELECT * FROM invoices WHERE id=?");
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();

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

// Paid
$paid = $conn->query("
SELECT SUM(amount) as total_paid 
FROM payments WHERE invoice_id=$invoice_id
")->fetch_assoc()['total_paid'] ?? 0;

$pending = $invoice['total'] - $paid;
?>

<div class="main-content">
<div class="col-lg-12">

<div class="topbar">
    <h5>Add Payment</h5>
</div>

<div class="p-4">

<!-- SUMMARY CARD -->
<div class="card mb-4">
    <div class="card-body">

        <div class="row text-center">

            <div class="col-md-4">
                <h6 class="text-muted">Total</h6>
                <h4>₹<?= number_format($invoice['total'],2) ?></h4>
            </div>

            <div class="col-md-4">
                <h6 class="text-muted">Paid</h6>
                <h4 class="text-success">₹<?= number_format($paid,2) ?></h4>
            </div>

            <div class="col-md-4">
                <h6 class="text-muted">Pending</h6>
                <h4 class="text-danger">₹<?= number_format($pending,2) ?></h4>
            </div>

        </div>

    </div>
</div>

<!-- FORM CARD -->
<div class="card">
<div class="card-body">

<form method="POST" action="../actions/save_payment.php">

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

<div class="mb-3">
<label class="form-label">Amount *</label>
<input type="number" name="amount" class="form-control" step="0.01" required>
</div>

<div class="mb-3">
<label class="form-label">Payment Date *</label>
<input type="date" name="payment_date" class="form-control" value="<?= date('Y-m-d') ?>">
</div>

<div class="mb-3">
<label class="form-label">Payment Method</label>
<select name="method" class="form-control">
    <option>Cash</option>
    <option>UPI</option>
    <option>Bank</option>
</select>
</div>

<div class="d-flex justify-content-between">
    <a href="invoices.php" class="btn btn-secondary">← Back</a>
    <button class="btn btn-success" id="saveBtn">Save Payment</button>
</div>

</form>

</div>
</div>

</div>
</div>
</div>

<?php require_once "../includes/footer.php"; ?>