<?php
session_start();
include "dbconnect.php"; // Database connection

// Set the number of records per page
$limit = 10;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $limit;

// Search query
$search_term = $_POST['search'] ?? '';
$search_query = '';
if (!empty($search_term)) {
    // Use prepared statement later for real safety; here simple string escaping for demo
    $search_term_escaped = $con->real_escape_string($search_term);
    $search_query = "WHERE expense_category LIKE '%$search_term_escaped%' OR description LIKE '%$search_term_escaped%'";
}

// Fetch total number of records for pagination
$total_sql = "SELECT COUNT(*) AS total FROM expenses $search_query";
$total_result = $con->query($total_sql);
$total_row = $total_result->fetch_assoc();
$total_records = $total_row['total'];
$total_pages = ceil($total_records / $limit);

// Fetch expenses from the database
$sql = "SELECT * FROM expenses $search_query ORDER BY date DESC LIMIT $limit OFFSET $offset";
$result = $con->query($sql);

// Export to Excel
if (isset($_POST['export_excel'])) {
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=expenses.xls");

    // Column headers
    echo "Expense Category\tAmount (₹)\tDate\tDescription\n";

    // Fetch again for export (reset result pointer)
    $export_sql = "SELECT * FROM expenses $search_query ORDER BY date DESC";
    $export_result = $con->query($export_sql);

    while ($row = $export_result->fetch_assoc()) {
        echo ucfirst(str_replace('_', ' ', $row['expense_category'])) . "\t" .
             number_format($row['amount'], 2) . "\t" .
             $row['date'] . "\t" .
             $row['description'] . "\n";
    }
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Expense Records</title>

<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- Bootstrap Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet" />

<style>
  body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
    margin: 0;
    padding: 0;
  }
  .container {
    margin-top: 50px;
    background: #fff;
    padding: 30px 25px;
    border-radius: 15px;
    box-shadow: 0 8px 25px rgba(0,0,0,0.15);
    max-width: 900px;
  }
  h3 {
    color: #764ba2;
    text-align: center;
    font-weight: 700;
    margin-bottom: 30px;
  }
  .btn {
    border-radius: 6px;
  }
  .btn-warning {
    background-color: #ffb703;
    border-color: #ffb703;
    color: #222;
  }
  .btn-warning:hover {
    background-color: #e6a400;
    border-color: #e6a400;
    color: #111;
  }
  .btn-danger {
    background-color: #d90429;
    border-color: #d90429;
  }
  .btn-danger:hover {
    background-color: #b1031f;
    border-color: #b1031f;
  }
  .btn-primary {
    background-color: #5a189a;
    border-color: #5a189a;
  }
  .btn-primary:hover {
    background-color: #3c096c;
    border-color: #3c096c;
  }
  .btn-success {
    background-color: #2a9d8f;
    border-color: #2a9d8f;
  }
  .btn-success:hover {
    background-color: #21867a;
    border-color: #21867a;
  }
  .logout-btn {
    position: fixed;
    top: 20px;
    right: 20px;
    background-color: #d90429;
    color: white;
    padding: 10px 20px;
    border-radius: 8px;
    font-weight: 600;
    text-decoration: none;
    box-shadow: 0 3px 8px rgba(0,0,0,0.3);
    transition: background-color 0.3s ease;
    z-index: 1050;
  }
  .logout-btn:hover {
    background-color: #b1031f;
  }
  table th {
    background-color: #764ba2;
    color: white;
    vertical-align: middle;
    text-align: center;
  }
  table td {
    vertical-align: middle;
    text-align: center;
  }
  .table-striped tbody tr:nth-of-type(odd) {
    background-color: #f3f1ff;
  }
  .pagination {
    justify-content: center;
  }
  /* Form Input group icon styling */
  .input-group-text {
    background-color: #764ba2;
    color: #fff;
    border: none;
  }
  .form-control:focus {
    border-color: #764ba2;
    box-shadow: 0 0 8px #764ba2;
  }

  @media (max-width: 575.98px) {
    .container {
      margin: 20px 10px;
      padding: 20px 15px;
    }
    table th, table td {
      font-size: 0.85rem;
      padding: 6px 5px;
    }
    .logout-btn {
      top: 10px;
      right: 10px;
      padding: 8px 14px;
      font-size: 0.9rem;
    }
  }
</style>

</head>
<body>

<!-- Logout Button -->
<a href="logout.php" class="logout-btn" title="Logout"><i class="bi bi-box-arrow-right"></i> Logout</a>

<div class="container">
    <h3><i class="bi bi-receipt-cutoff"></i> Expense Records</h3>

    <!-- Search Form -->
    <form method="POST" class="mb-4">
        <div class="input-group">
            <span class="input-group-text" id="search-icon"><i class="bi bi-search"></i></span>
            <input type="text" name="search" class="form-control" placeholder="Search by Category or Description" aria-label="Search" aria-describedby="search-icon" value="<?= htmlspecialchars($search_term) ?>">
            <button type="submit" class="btn btn-primary"><i class="bi bi-funnel-fill"></i> Search</button>
        </div>
    </form>

    <!-- Export to Excel Button -->
    <form method="POST" class="mb-4 d-flex justify-content-end">
        <button type="submit" name="export_excel" class="btn btn-success">
            <i class="bi bi-file-earmark-excel-fill"></i> Export to Excel
        </button>
    </form>

    <!-- Success/Error Messages -->
    <?php if (isset($_SESSION['message'])): ?>
        <div class="alert alert-success text-center" role="alert">
            <i class="bi bi-check-circle-fill"></i> <?= htmlspecialchars($_SESSION['message']) ?>
            <?php unset($_SESSION['message']); ?>
        </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger text-center" role="alert">
            <i class="bi bi-exclamation-triangle-fill"></i> <?= htmlspecialchars($_SESSION['error']) ?>
            <?php unset($_SESSION['error']); ?>
        </div>
    <?php endif; ?>

    <?php if ($result && $result->num_rows > 0): ?>
        <div class="table-responsive">
          <table class="table table-striped table-hover align-middle">
              <thead>
                  <tr>
                      <th><i class="bi bi-tags-fill"></i> Expense Category</th>
                      <th><i class="bi bi-currency-rupee"></i> Amount (₹)</th>
                      <th><i class="bi bi-calendar-event-fill"></i> Date</th>
                      <th><i class="bi bi-card-text"></i> Description</th>
                      <th><i class="bi bi-gear-fill"></i> Actions</th>
                  </tr>
              </thead>
              <tbody>
                  <?php while ($row = $result->fetch_assoc()): ?>
                      <tr>
                          <td><?= htmlspecialchars(ucfirst(str_replace('_', ' ', $row['expense_category']))) ?></td>
                          <td>₹<?= number_format($row['amount'], 2) ?></td>
                          <td><?= htmlspecialchars($row['date']) ?></td>
                          <td><?= htmlspecialchars($row['description']) ?></td>
                          <td>
                              <a href="edit_expense.php?id=<?= $row['id'] ?>" class="btn btn-warning btn-sm" title="Edit">
                                  <i class="bi bi-pencil-square"></i>
                              </a>
                              <a href="delete_expense.php?id=<?= $row['id'] ?>" class="btn btn-danger btn-sm" title="Delete" onclick="return confirm('Are you sure you want to delete this expense?');">
                                  <i class="bi bi-trash-fill"></i>
                              </a>
                          </td>
                      </tr>
                  <?php endwhile; ?>
              </tbody>
          </table>
        </div>

        <!-- Pagination -->
        <nav aria-label="Page navigation example">
            <ul class="pagination">
                <?php
                // Build URL with search query if applicable
                $base_url = '?';
                if (!empty($search_term)) {
                    $base_url .= 'page=';
                } else {
                    $base_url .= 'page=';
                }
                for ($i = 1; $i <= $total_pages; $i++): 
                    $active_class = ($i == $page) ? 'active' : '';
                    $url = "?page=$i";
                    if (!empty($search_term)) {
                        $url .= "&search=" . urlencode($search_term);
                    }
                ?>
                <li class="page-item <?= $active_class ?>">
                    <a class="page-link" href="<?= $url ?>"><?= $i ?></a>
                </li>
                <?php endfor; ?>
            </ul>
        </nav>

    <?php else: ?>
        <p class="text-center fs-5 mt-4">No expenses recorded yet.</p>
    <?php endif; ?>

</div>

<!-- Bootstrap JS Bundle -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>
