<?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;

// Sanitize search input for security
$search_term = isset($_POST['search']) ? trim($_POST['search']) : '';
$search_query = '';
if ($search_term !== '') {
    // Use prepared statements in real apps for security, here simplified
    $search_safe = $con->real_escape_string($search_term);
    $search_query = "WHERE expense_category LIKE '%$search_safe%' OR description LIKE '%$search_safe%'";
}

// 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");

    echo "Expense Category\tAmount (₹)\tDate\tDescription\n";
    while ($row = $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>
    /* Background and typography */
    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        min-height: 100vh;
        margin: 0;
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: #333;
        display: flex;
        flex-direction: column;
    }
    /* Container card */
    .container {
        background: #fff;
        border-radius: 14px;
        box-shadow: 0 15px 40px rgba(0, 0, 0, 0.15);
        padding: 30px 25px;
        max-width: 900px;
        margin: 70px auto 50px auto;
        width: 95%;
    }
    h3 {
        color: #5c4ee5;
        font-weight: 700;
        margin-bottom: 30px;
        text-align: center;
        letter-spacing: 1.3px;
    }
    /* Logout button */
    .logout-btn {
        position: fixed;
        top: 20px;
        right: 20px;
        background-color: #e74c3c;
        color: white;
        padding: 10px 22px;
        border-radius: 30px;
        text-decoration: none;
        font-weight: 600;
        box-shadow: 0 4px 15px rgba(231, 76, 60, 0.7);
        transition: background-color 0.3s ease;
        display: flex;
        align-items: center;
        gap: 8px;
        z-index: 100;
    }
    .logout-btn:hover {
        background-color: #c0392b;
    }
    /* Form inline on desktop */
    form.search-export {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        justify-content: center;
        margin-bottom: 25px;
    }
    form.search-export input[type="text"] {
        flex-grow: 1;
        max-width: 300px;
        border-radius: 8px;
        border: 1.5px solid #ddd;
        padding: 10px 15px;
        font-size: 1rem;
        transition: border-color 0.3s ease;
    }
    form.search-export input[type="text"]:focus {
        outline: none;
        border-color: #5c4ee5;
        box-shadow: 0 0 8px rgba(92, 78, 229, 0.4);
    }
    form.search-export button {
        border-radius: 8px;
        font-weight: 600;
        min-width: 120px;
    }
    /* Buttons styling */
    .btn-primary {
        background-color: #5c4ee5;
        border: none;
        transition: background-color 0.3s ease;
    }
    .btn-primary:hover {
        background-color: #473ebf;
    }
    .btn-success {
        background-color: #2ecc71;
        border: none;
        transition: background-color 0.3s ease;
    }
    .btn-success:hover {
        background-color: #27ae60;
    }
    /* Table styling */
    table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0 10px;
    }
    table thead th {
        background-color: #5c4ee5;
        color: white;
        padding: 12px 15px;
        border-radius: 8px;
        text-align: left;
    }
    table tbody tr {
        background-color: #f7f7fb;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(92, 78, 229, 0.1);
        transition: background-color 0.3s ease;
    }
    table tbody tr:hover {
        background-color: #edeaff;
    }
    table tbody td {
        padding: 15px 15px;
        vertical-align: middle;
        border: none !important;
    }
    /* Action buttons */
    .btn-sm {
        padding: 6px 10px;
        font-size: 0.85rem;
        border-radius: 6px;
    }
    /* Pagination */
    .pagination {
        justify-content: center;
        margin-top: 25px;
        flex-wrap: wrap;
        gap: 8px;
    }
    .page-item.active .page-link {
        background-color: #5c4ee5;
        border-color: #5c4ee5;
        color: white;
    }
    .page-link {
        border-radius: 8px;
        padding: 8px 14px;
        color: #5c4ee5;
        border: 1.5px solid #5c4ee5;
        transition: background-color 0.3s ease, color 0.3s ease;
    }
    .page-link:hover {
        background-color: #5c4ee5;
        color: white;
        text-decoration: none;
    }
    /* Responsive tweaks */
    @media (max-width: 575.98px) {
        form.search-export {
            flex-direction: column;
            align-items: stretch;
        }
        form.search-export input[type="text"],
        form.search-export button {
            max-width: 100%;
        }
        table thead {
            display: none;
        }
        table tbody tr {
            display: block;
            margin-bottom: 20px;
            box-shadow: none;
            background-color: #fff;
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 10px;
        }
        table tbody td {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
        }
        table tbody td::before {
            content: attr(data-label);
            font-weight: 600;
            color: #5c4ee5;
            flex: 1;
            text-transform: capitalize;
        }
        table tbody td:last-child {
            justify-content: flex-end;
        }
    }
</style>
</head>
<body>

<a href="logout.php" class="logout-btn" aria-label="Logout">
    <i class="bi bi-box-arrow-right"></i> Logout
</a>

<div class="container" role="main" aria-labelledby="pageTitle">
    <h3 id="pageTitle">Expense Records</h3>

    <!-- Search and Export inline form -->
    <form method="POST" class="search-export" role="search" aria-label="Search expenses">
        <input type="text" name="search" placeholder="Search by Category or Description" value="<?= htmlspecialchars($search_term) ?>" aria-label="Search expenses">
        <button type="submit" class="btn btn-primary" aria-label="Search">Search <i class="bi bi-search"></i></button>
    </form>

    <form method="POST" class="d-flex justify-content-center mb-3" aria-label="Export expenses to Excel">
        <button type="submit" name="export_excel" class="btn btn-success" aria-label="Export to Excel">
            Export to Excel <i class="bi bi-file-earmark-excel"></i>
        </button>
    </form>

    <!-- Messages -->
    <?php if (isset($_SESSION['message'])): ?>
        <div class="alert alert-success" role="alert">
            <?= htmlspecialchars($_SESSION['message']) ?>
            <?php unset($_SESSION['message']); ?>
        </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger" role="alert">
            <?= htmlspecialchars($_SESSION['error']) ?>
            <?php unset($_SESSION['error']); ?>
        </div>
    <?php endif; ?>

    <?php if ($result->num_rows > 0): ?>
        <table class="table table-borderless" role="table" aria-describedby="expenseTableDesc">
            <thead>
                <tr>
                    <th scope="col">Expense Category</th>
                    <th scope="col">Amount (₹)</th>
                    <th scope="col">Date</th>
                    <th scope="col">Description</th>
                    <th scope="col" style="width: 90px;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td data-label="Expense Category"><?= ucfirst(str_replace('_', ' ', htmlspecialchars($row['expense_category']))) ?></td>
                        <td data-label="Amount (₹)"><?= '₹' . number_format($row['amount'], 2) ?></td>
                        <td data-label="Date"><?= htmlspecialchars($row['date']) ?></td>
                        <td data-label="Description"><?= htmlspecialchars($row['description']) ?></td>
                        <td data-label="Actions">
                            <a href="edit_expense.php?id=<?= intval($row['id']) ?>" class="btn btn-primary btn-sm" aria-label="Edit Expense">
                                <i class="bi bi-pencil-fill"></i> Edit
                            </a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>

        <!-- Pagination -->
        <nav aria-label="Expense page navigation">
            <ul class="pagination">
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                        <a class="page-link" href="?page=<?= $i ?>" aria-current="<?= $i == $page ? 'page' : '' ?>">
                            <?= $i ?>
                        </a>
                    </li>
                <?php endfor; ?>
            </ul>
        </nav>

    <?php else: ?>
        <p class="text-center fw-semibold fs-5 mt-5">No expenses recorded yet.</p>
    <?php endif; ?>
</div>

<!-- Bootstrap JS Bundle (Popper + Bootstrap) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>
