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

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

// Initial load
$result = $conn->query("
SELECT invoices.*, customers.name 
FROM invoices
JOIN customers ON invoices.customer_id = customers.id
ORDER BY invoices.id DESC
");
?>

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

<div class="topbar d-flex justify-content-between align-items-center">
    <h5>Invoices</h5>
    <a href="add_invoice.php" class="btn btn-primary">+ Create Invoice</a>
</div>

<div class="p-4">

<!-- SEARCH -->
<div class="mb-3">
    <input type="text" id="invoiceSearch" class="form-control" placeholder="Search invoices...">
</div>

<!-- TABLE -->
<div class="table-responsive">
<table class="table table-bordered table-striped">

<thead class="table-dark">
<tr>
<th>ID</th>
<th>Customer</th>
<th>Date</th>
<th>Total</th>
<th>Paid</th>
<th>Pending</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>

<tbody id="invoiceTable">

<?php if($result->num_rows > 0){ ?>
<?php while($row = $result->fetch_assoc()){ ?>

<?php
$paid = $conn->query("
SELECT SUM(amount) as paid 
FROM payments WHERE invoice_id=".$row['id']
)->fetch_assoc()['paid'] ?? 0;

$pending = $row['total'] - $paid;

if($pending <= 0){
    $status = "Paid";
    $badge = "success";
} elseif($paid > 0){
    $status = "Partial";
    $badge = "warning";
} else {
    $status = "Unpaid";
    $badge = "danger";
}
?>

<tr>
<td>#<?= $row['id'] ?></td>
<td><?= e($row['name']) ?></td>
<td><?= $row['invoice_date'] ?></td>
<td>₹<?= number_format($row['total'],2) ?></td>
<td class="text-success">₹<?= number_format($paid,2) ?></td>
<td class="text-danger">₹<?= number_format($pending,2) ?></td>
<td><span class="badge bg-<?= $badge ?>"><?= $status ?></span></td>

<td>

<a href="view_invoice.php?id=<?= $row['id'] ?>" class="btn btn-info btn-sm" target="_blank">View</a>

<a href="../actions/invoice_pdf.php?id=<?= $row['id'] ?>" class="btn btn-secondary btn-sm" target="_blank">PDF</a>

<?php if($pending > 0){ ?>
<a href="add_payment.php?id=<?= $row['id'] ?>" class="btn btn-success btn-sm">Pay</a>
<?php } ?>

<a href="../actions/whatsapp_invoice.php?id=<?= $row['id'] ?>" class="btn btn-success btn-sm" target="_blank">WhatsApp</a>

<a href="#"
   class="btn btn-danger btn-sm deleteBtn"
   data-id="<?= $row['id'] ?>"
   data-name="Invoice #<?= $row['id'] ?>"
   data-url="../actions/delete_invoice.php">
   Delete
</a>

</td>
</tr>

<?php } ?>
<?php } else { ?>
<tr>
<td colspan="8" class="text-center">No invoices found</td>
</tr>
<?php } ?>

</tbody>
</table>
</div>

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

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