<?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 title LIKE '%$search%'";
}

$query = "
SELECT * FROM expenses 
$where
ORDER BY expense_date 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['title']) ?></td>
<td>₹<?= number_format($row['amount'],2) ?></td>
<td><?= $row['expense_date'] ?></td>

<td>
<a href="edit_expense.php?id=<?= $row['id'] ?>" class="btn btn-warning btn-sm">Edit</a>

<a href="../actions/delete_expense.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>";
}