<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $role_id = $user_details['role_id'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
}

// Get search and filter parameters
$search = $_GET['search'] ?? '';
$company_filter = $_GET['company_filter'] ?? '';
$category_filter = $_GET['category_filter'] ?? '';
$status_filter = $_GET['status_filter'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$page = $_GET['page'] ?? 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Build query with filters and role-based restrictions
$where_conditions = array("1=1");
$params = array();
$param_types = "";

// Role-based filtering
if ($role_id == 2) { // Fund Manager - restrict access
    $where_conditions[] = "ec.category_type NOT IN ('FAMILY', 'SALARY')";
}

if (!empty($search)) {
    $where_conditions[] = "(e.expense_title LIKE ? OR e.expense_number LIKE ? OR e.vendor_name LIKE ? OR c.company_name LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    $param_types .= "ssss";
}

if (!empty($company_filter)) {
    $where_conditions[] = "e.company_id = ?";
    $params[] = $company_filter;
    $param_types .= "i";
}

if (!empty($category_filter)) {
    $where_conditions[] = "e.category_id = ?";
    $params[] = $category_filter;
    $param_types .= "i";
}

if (!empty($status_filter)) {
    $where_conditions[] = "e.status = ?";
    $params[] = $status_filter;
    $param_types .= "s";
}

if (!empty($date_from)) {
    $where_conditions[] = "e.expense_date >= ?";
    $params[] = $date_from;
    $param_types .= "s";
}

if (!empty($date_to)) {
    $where_conditions[] = "e.expense_date <= ?";
    $params[] = $date_to;
    $param_types .= "s";
}

$where_clause = implode(" AND ", $where_conditions);

// Get total count for pagination
$count_query = "SELECT COUNT(*) as total 
                FROM expenses e 
                LEFT JOIN companies c ON e.company_id = c.company_id 
                LEFT JOIN expense_categories ec ON e.category_id = ec.category_id 
                LEFT JOIN users u ON e.created_by = u.user_id 
                WHERE $where_clause";

$count_stmt = $conn->prepare($count_query);
if (!empty($params)) {
    $count_stmt->bind_param($param_types, ...$params);
}
$count_stmt->execute();
$total_expenses = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_expenses / $limit);

// Get expenses with pagination
$query = "SELECT e.*, 
                 c.company_name, c.company_code,
                 ec.category_name, ec.category_type, ec.color_code,
                 u.full_name as created_by_name,
                 a.full_name as approved_by_name
          FROM expenses e 
          LEFT JOIN companies c ON e.company_id = c.company_id 
          LEFT JOIN expense_categories ec ON e.category_id = ec.category_id 
          LEFT JOIN users u ON e.created_by = u.user_id 
          LEFT JOIN users a ON e.approved_by = a.user_id 
          WHERE $where_clause
          ORDER BY e.created_at DESC 
          LIMIT ? OFFSET ?";

$stmt = $conn->prepare($query);
$params[] = $limit;
$params[] = $offset;
$param_types .= "ii";

if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$expenses = $stmt->get_result();

// Get companies for filter dropdown
$companies_query = "SELECT * FROM companies WHERE is_active = 1 ORDER BY company_name";
$companies_result = $conn->query($companies_query);

// Get categories for filter dropdown
$categories_query = "SELECT ec.*, c.company_name 
                    FROM expense_categories ec 
                    LEFT JOIN companies c ON ec.company_id = c.company_id 
                    WHERE ec.is_active = 1";

// Apply role-based filtering for categories
if ($role_id == 2) { // Fund Manager
    $categories_query .= " AND ec.category_type NOT IN ('FAMILY', 'SALARY')";
}

$categories_query .= " ORDER BY c.company_name, ec.sort_order, ec.category_name";
$categories_result = $conn->query($categories_query);

// Get summary statistics
$stats_query = "SELECT 
    COUNT(*) as total_count,
    SUM(amount) as total_amount,
    COUNT(CASE WHEN status = 'PENDING' THEN 1 END) as pending_count,
    COUNT(CASE WHEN status = 'PAID' THEN 1 END) as paid_count,
    COUNT(CASE WHEN status = 'DRAFT' THEN 1 END) as draft_count
    FROM expenses e 
    LEFT JOIN expense_categories ec ON e.category_id = ec.category_id 
    WHERE $where_clause";

$stats_stmt = $conn->prepare($stats_query);
if (!empty($params) && count($params) > 2) { // Exclude limit and offset
    $stats_params = array_slice($params, 0, -2);
    $stats_types = substr($param_types, 0, -2);
    $stats_stmt->bind_param($stats_types, ...$stats_params);
}
$stats_stmt->execute();
$stats = $stats_stmt->get_result()->fetch_assoc();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>All Expenses - Personal Fund Management System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/phosphor-icons@1.4.2/src/css/icons.min.css">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        /* Stats Cards */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        /* Filter Card */
        .filter-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        /* Table Card */
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        /* Status Badges */
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-draft { background: #f1f5f9; color: #64748b; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-approved { background: #dcfce7; color: #166534; }
        .status-paid { background: #dcfce7; color: #166534; }
        .status-rejected { background: #fee2e2; color: #991b1b; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        
        /* Category Badges */
        .category-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 500;
            color: white;
        }
        
        /* Company Badges */
        .company-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
            background: #e2e8f0;
            color: #374151;
        }
        
        .company-online { background: #dbeafe; color: #1e40af; }
        .company-notale { background: #f3e8ff; color: #6b21a8; }
        
        /* Action Buttons */
        .btn-action {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            margin: 0 0.25rem;
            transition: all 0.2s ease;
        }
        
        .btn-primary { background: #3b82f6; color: white; }
        .btn-primary:hover { background: #1d4ed8; color: white; }
        
        .btn-success { background: #059669; color: white; }
        .btn-success:hover { background: #047857; color: white; }
        
        .btn-warning { background: #d97706; color: white; }
        .btn-warning:hover { background: #b45309; color: white; }
        
        .btn-danger { background: #dc2626; color: white; }
        .btn-danger:hover { background: #b91c1c; color: white; }
        
        /* Form Controls */
        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #6366f1;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-primary {
            background: #6366f1;
            color: white;
        }
        
        .btn-primary:hover {
            background: #4f46e5;
        }
        
        .btn-outline-secondary {
            background: transparent;
            border: 1px solid #e2e8f0;
            color: #64748b;
        }
        
        .btn-outline-secondary:hover {
            background: #f8fafc;
            border-color: #64748b;
        }
        
        /* Pagination */
        .pagination-wrapper {
            padding: 1.5rem;
            background: #f8fafc;
            border-top: 1px solid #e2e8f0;
            display: flex;
            justify-content: between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .pagination-info {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .pagination {
            display: flex;
            gap: 0.5rem;
            margin: 0;
        }
        
        .page-link {
            padding: 0.5rem 0.75rem;
            background: white;
            border: 1px solid #e2e8f0;
            color: #374151;
            text-decoration: none;
            border-radius: 6px;
            font-size: 0.875rem;
        }
        
        .page-link:hover {
            background: #f8fafc;
            border-color: #6366f1;
            color: #6366f1;
        }
        
        .page-link.active {
            background: #6366f1;
            border-color: #6366f1;
            color: white;
        }
        
        /* Expense Avatar */
        .expense-avatar {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            background: #6366f1;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .table-header {
                flex-direction: column;
                gap: 1rem;
                align-items: stretch;
            }
            
            .data-table {
                font-size: 0.75rem;
            }
            
            .data-table th,
            .data-table td {
                padding: 0.5rem;
            }
        }
    </style>
</head>

<body>
    <div class="container-fluid">
        <div class="page-content">
            <!-- Page Header -->
            <div class="page-header">
                <h1 class="page-title">All Expenses</h1>
                <p class="page-subtitle">Manage and monitor all company expenses with advanced filtering</p>
            </div>

            <!-- Stats Row -->
            <div class="stats-row">
                <div class="stat-card">
                    <div class="stat-value"><?php echo number_format($stats['total_count']); ?></div>
                    <div class="stat-label">Total Expenses</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value">KES <?php echo number_format($stats['total_amount'], 2); ?></div>
                    <div class="stat-label">Total Amount</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo number_format($stats['pending_count']); ?></div>
                    <div class="stat-label">Pending Approval</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo number_format($stats['paid_count']); ?></div>
                    <div class="stat-label">Paid</div>
                </div>
            </div>

            <!-- Filter Card -->
            <div class="filter-card">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Search</label>
                        <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                               placeholder="Search expenses, vendors...">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Company</label>
                        <select class="form-select" name="company_filter">
                            <option value="">All Companies</option>
                            <?php while ($company = $companies_result->fetch_assoc()): ?>
                                <option value="<?php echo $company['company_id']; ?>" 
                                        <?php echo $company_filter == $company['company_id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($company['company_name']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Category</label>
                        <select class="form-select" name="category_filter">
                            <option value="">All Categories</option>
                            <?php 
                            $current_company = '';
                            while ($category = $categories_result->fetch_assoc()): 
                                if ($current_company != $category['company_name']) {
                                    if ($current_company != '') echo '</optgroup>';
                                    echo '<optgroup label="' . htmlspecialchars($category['company_name']) . '">';
                                    $current_company = $category['company_name'];
                                }
                            ?>
                                <option value="<?php echo $category['category_id']; ?>" 
                                        <?php echo $category_filter == $category['category_id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($category['category_name']); ?>
                                </option>
                            <?php 
                            endwhile; 
                            if ($current_company != '') echo '</optgroup>';
                            ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Status</label>
                        <select class="form-select" name="status_filter">
                            <option value="">All Status</option>
                            <option value="DRAFT" <?php echo $status_filter == 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                            <option value="PENDING" <?php echo $status_filter == 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                            <option value="APPROVED" <?php echo $status_filter == 'APPROVED' ? 'selected' : ''; ?>>Approved</option>
                            <option value="PAID" <?php echo $status_filter == 'PAID' ? 'selected' : ''; ?>>Paid</option>
                            <option value="REJECTED" <?php echo $status_filter == 'REJECTED' ? 'selected' : ''; ?>>Rejected</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Date Range</label>
                        <div class="d-flex gap-2">
                            <input type="date" class="form-control" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>"
                                   placeholder="From">
                            <input type="date" class="form-control" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>"
                                   placeholder="To">
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="ph-funnel me-1"></i> Filter
                            </button>
                            <a href="list_expenses.php" class="btn btn-outline-secondary">Clear</a>
                            <a href="add_expense.php" class="btn btn-success ms-auto">
                                <i class="ph-plus me-1"></i> Add Expense
                            </a>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Expenses Table -->
            <div class="table-card">
                <div class="table-header">
                    <h3 class="table-title">Expenses List (<?php echo $total_expenses; ?> total)</h3>
                    <div class="d-flex gap-2">
                        <a href="expense_reports.php" class="btn btn-warning">
                            <i class="ph-chart-bar me-1"></i> Reports
                        </a>
                        <a href="export_expenses.php" class="btn btn-success">
                            <i class="ph-download me-1"></i> Export
                        </a>
                    </div>
                </div>
                
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Expense Details</th>
                            <th>Company</th>
                            <th>Category</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Created By</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($expenses->num_rows > 0): ?>
                            <?php while ($expense = $expenses->fetch_assoc()): ?>
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="expense-avatar me-3">
                                            <?php 
                                            $icon = match($expense['category_type']) {
                                                'SHOP' => '🏪',
                                                'SSO' => '🔐',
                                                'VANS' => '🚐',
                                                'SPECIAL' => '⭐',
                                                default => '📄'
                                            };
                                            echo $icon;
                                            ?>
                                        </div>
                                        <div>
                                            <div style="font-weight: 600; color: #1e293b;">
                                                <?php echo htmlspecialchars($expense['expense_title']); ?>
                                            </div>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                #<?php echo htmlspecialchars($expense['expense_number']); ?>
                                            </div>
                                            <?php if ($expense['vendor_name']): ?>
                                                <div style="color: #8b5cf6; font-size: 0.75rem;">
                                                    Vendor: <?php echo htmlspecialchars($expense['vendor_name']); ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <?php 
                                    $company_class = match($expense['company_code']) {
                                        'ONLINE' => 'company-online',
                                        'NOTALE' => 'company-notale',
                                        default => ''
                                    };
                                    ?>
                                    <span class="company-badge <?php echo $company_class; ?>">
                                        <?php echo htmlspecialchars($expense['company_name']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="category-badge" style="background-color: <?php echo $expense['color_code']; ?>;">
                                        <?php echo htmlspecialchars($expense['category_name']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span style="font-weight: 600; color: #1e293b;">
                                        KES <?php echo number_format($expense['amount'], 2); ?>
                                    </span>
                                    <?php if ($expense['payment_method']): ?>
                                        <div style="color: #64748b; font-size: 0.75rem;">
                                            via <?php echo ucfirst(str_replace('_', ' ', strtolower($expense['payment_method']))); ?>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php 
                                    $status_class = match($expense['status']) {
                                        'DRAFT' => 'status-draft',
                                        'PENDING' => 'status-pending',
                                        'APPROVED' => 'status-approved',
                                        'PAID' => 'status-paid',
                                        'REJECTED' => 'status-rejected',
                                        'CANCELLED' => 'status-cancelled',
                                        default => 'status-draft'
                                    };
                                    ?>
                                    <span class="status-badge <?php echo $status_class; ?>">
                                        <?php echo ucfirst(str_replace('_', ' ', strtolower($expense['status']))); ?>
                                    </span>
                                    <?php if ($expense['approved_by_name'] && $expense['status'] === 'PAID'): ?>
                                        <div style="color: #059669; font-size: 0.75rem;">
                                            Approved by <?php echo htmlspecialchars($expense['approved_by_name']); ?>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div style="font-weight: 500; color: #1e293b;">
                                        <?php echo date('M j, Y', strtotime($expense['expense_date'])); ?>
                                    </div>
                                    <div style="color: #64748b; font-size: 0.75rem;">
                                        Created: <?php echo date('M j, Y', strtotime($expense['created_at'])); ?>
                                    </div>
                                </td>
                                <td>
                                    <div style="font-weight: 500; color: #374151;">
                                        <?php echo htmlspecialchars($expense['created_by_name']); ?>
                                    </div>
                                </td>
                                <td>
                                    <div class="d-flex gap-1">
                                        <a href="view_expense.php?id=<?php echo $expense['expense_id']; ?>" 
                                           class="btn-action btn-primary" title="View Details">
                                            <i class="ph-eye"></i>
                                        </a>
                                        <?php if (in_array($expense['status'], ['DRAFT', 'PENDING'])): ?>
                                            <a href="edit_expense.php?id=<?php echo $expense['expense_id']; ?>" 
                                               class="btn-action btn-warning" title="Edit">
                                                <i class="ph-pencil"></i>
                                            </a>
                                        <?php endif; ?>
                                        <?php if ($expense['status'] === 'PENDING' && $role_id === 1): ?>
                                            <a href="approve_expense.php?id=<?php echo $expense['expense_id']; ?>" 
                                               class="btn-action btn-success" title="Approve">
                                                <i class="ph-check"></i>
                                            </a>
                                        <?php endif; ?>
                                        <?php if ($expense['status'] === 'PAID'): ?>
                                            <a href="print_expense.php?id=<?php echo $expense['expense_id']; ?>" 
                                               class="btn-action btn-success" title="Print" target="_blank">
                                                <i class="ph-printer"></i>
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8" style="text-align: center; padding: 3rem; color: #64748b;">
                                    <i class="ph-file-x" style="font-size: 3rem; margin-bottom: 1rem; display: block;"></i>
                                    No expenses found matching your criteria.
                                    <br><br>
                                    <a href="add_expense.php" class="btn btn-primary">
                                        <i class="ph-plus me-1"></i> Create First Expense
                                    </a>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                <div class="pagination-wrapper">
                    <div class="pagination-info">
                        Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $total_expenses); ?> of <?php echo $total_expenses; ?> entries
                    </div>
                    
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" 
                               class="page-link">
                                <i class="ph-caret-left"></i>
                            </a>
                        <?php endif; ?>
                        
                        <?php 
                        $start = max(1, $page - 2);
                        $end = min($total_pages, $page + 2);
                        
                        for ($i = $start; $i <= $end; $i++): 
                        ?>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>" 
                               class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                                <?php echo $i; ?>
                            </a>
                        <?php endfor; ?>
                        
                        <?php if ($page < $total_pages): ?>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" 
                               class="page-link">
                                <i class="ph-caret-right"></i>
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Auto-submit form on filter change
            $('.form-select').on('change', function() {
                if ($(this).val() !== '') {
                    $(this).closest('form').submit();
                }
            });
            
            // Auto-submit on date change
            $('input[type="date"]').on('change', function() {
                $(this).closest('form').submit();
            });
            
            // Search on Enter key
            $('input[name="search"]').on('keypress', function(e) {
                if (e.which === 13) {
                    $(this).closest('form').submit();
                }
            });
        });
    </script>
</body>
</html>

<?php $conn->close(); ?>