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

$search = trim($_GET['search'] ?? '');

$where = "";

if($search){
    $search = $conn->real_escape_string($search);
    $where = "WHERE c.name LIKE '%$search%' OR i.id LIKE '%$search%'";
}

$query = "
SELECT i.*, c.name
FROM invoices i
JOIN customers c ON i.customer_id = c.id
$where
ORDER BY i.id DESC
LIMIT 50
";

$result = $conn->query($query);

if($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
?>
<tr>
    <td><?= $row['id'] ?></td>
    <td><?= e($row['name']) ?></td>
    <td><?= $row['invoice_date'] ?></td>
    <td>₹<?= number_format($row['total'],2) ?></td>

    <td>
        <a href="view_invoice.php?id=<?= $row['id'] ?>" class="btn btn-info btn-sm">View</a>
        <a href="../actions/invoice_pdf.php?id=<?= $row['id'] ?>" class="btn btn-success btn-sm">PDF</a>
        <a href="edit_invoice.php?id=<?= $row['id'] ?>" class="btn btn-warning btn-sm">Edit</a>
        <a href="../actions/delete_invoice.php?id=<?= $row['id'] ?>" 
           class="btn btn-danger btn-sm"
           onclick="return confirm('Delete?')">Delete</a>
    </td>
</tr>
<?php
    }
} else {
    echo "<tr><td colspan='5' class='text-center'>No data found</td></tr>";
}