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

$pageTitle = "Expenses";

require_once "../includes/header.php";
require_once "../includes/sidebar.php";
require_once "../includes/topbar.php";

// ================= ALERT =================
$msg = $_GET['msg'] ?? '';

if($msg == 'added'){
    echo "<div class='alert alert-success'>Expense added successfully</div>";
}
if($msg == 'updated'){
    echo "<div class='alert alert-success'>Expense updated</div>";
}
if($msg == 'deleted'){
    echo "<div class='alert alert-danger'>Expense deleted</div>";
}

// ================= DATA =================
$result = $conn->query("
SELECT * FROM expenses 
ORDER BY expense_date DESC
LIMIT 20
");
?>

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

<div class="p-4">

<div class="d-flex justify-content-between mb-3">

    <input type="text" id="expenseSearch" 
           class="form-control w-50" 
           placeholder="Search expense...">

    <a href="add_expense.php" class="btn btn-primary">
        + Add Expense
    </a>

</div>

<div class="table-responsive">

<table class="table table-bordered table-striped">

<thead class="table-dark">
<tr>
   
    <th>Title</th>
    <th>Amount</th>
    <th>Date</th>
    <th>Action</th>
</tr>
</thead>

<tbody id="expenseTable">

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

<tr>

<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="#"
   class="btn btn-danger btn-sm deleteBtn"
   data-id="<?= $row['id'] ?>"
   data-url="../actions/delete_expense.php"
>
   Delete
</a>

</td>

</tr>

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

</tbody>

</table>

</div>

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

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