<?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'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
}

// Get search parameters
$search = $_GET['search'] ?? '';
$family_filter = $_GET['family_filter'] ?? '';
$status_filter = $_GET['status_filter'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$family_type = $_GET['type'] ?? '';
$page = $_GET['page'] ?? 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Build query with filters for FAMILY category type only
$where_conditions = array("ec.category_type = 'FAMILY'");
$params = array();
$param_types = "";

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

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

// Filter by family type if specified
if (!empty($family_type)) {
    switch($family_type) {
        case 'rent':
            $where_conditions[] = "(ec.category_name LIKE '%Rent%' OR ec.category_name LIKE '%Housing%')";
            break;
        case 'bills':
            $where_conditions[] = "(ec.category_name LIKE '%Bills%' OR ec.category_name LIKE '%Utilities%')";
            break;
        case 'groceries':
            $where_conditions[] = "(ec.category_name LIKE '%Groceries%' OR ec.category_name LIKE '%Food%')";
            break;
        case 'healthcare':
            $where_conditions[] = "ec.category_name LIKE '%Healthcare%'";
            break;
        case 'education':
            $where_conditions[] = "ec.category_name LIKE '%Education%'";
            break;
        case 'transportation':
            $where_conditions[] = "ec.category_name LIKE '%Transportation%'";
            break;
        case 'entertainment':
            $where_conditions[] = "ec.category_name LIKE '%Entertainment%'";
            break;
    }
}

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 expense_categories ec ON e.category_id = ec.category_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 family expenses with pagination
$query = "SELECT e.*, ec.category_name, ec.category_type, ec.color_code,
                 u_created.full_name as created_by_name,
                 u_approved.full_name as approved_by_name
          FROM expenses e 
          LEFT JOIN expense_categories ec ON e.category_id = ec.category_id 
          LEFT JOIN users u_created ON e.created_by = u_created.user_id 
          LEFT JOIN users u_approved ON e.approved_by = u_approved.user_id 
          WHERE $where_clause
          ORDER BY e.expense_date DESC, 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 family categories for filter dropdown
$family_categories_query = "SELECT * FROM expense_categories WHERE category_type = 'FAMILY' AND is_active = 1 ORDER BY category_name";
$family_categories_result = $conn->query($family_categories_query);

// Get family expense statistics
$stats_query = "SELECT 
    COUNT(*) as total_count,
    SUM(CASE WHEN status = 'PAID' THEN amount ELSE 0 END) as total_paid,
    SUM(CASE WHEN status = 'PENDING' THEN amount ELSE 0 END) as total_pending,
    SUM(CASE WHEN DATE(expense_date) = CURDATE() THEN amount ELSE 0 END) as today_total,
    SUM(CASE WHEN YEAR(expense_date) = YEAR(CURDATE()) AND MONTH(expense_date) = MONTH(CURDATE()) AND status = 'PAID' THEN amount ELSE 0 END) as month_total,
    COUNT(CASE WHEN status = 'PENDING' THEN 1 END) as pending_count
    FROM expenses e 
    LEFT JOIN expense_categories ec ON e.category_id = ec.category_id
    WHERE ec.category_type = 'FAMILY'";
$stats = $conn->query($stats_query)->fetch_assoc();

// Get individual family category totals
$family_totals_query = "SELECT 
    ec.category_name,
    COUNT(e.expense_id) as count,
    SUM(CASE WHEN e.status = 'PAID' THEN e.amount ELSE 0 END) as total_amount,
    SUM(CASE WHEN YEAR(e.expense_date) = YEAR(CURDATE()) AND MONTH(e.expense_date) = MONTH(CURDATE()) AND e.status = 'PAID' THEN e.amount ELSE 0 END) as month_amount
    FROM expense_categories ec
    LEFT JOIN expenses e ON ec.category_id = e.category_id
    WHERE ec.category_type = 'FAMILY' AND ec.is_active = 1
    GROUP BY ec.category_id, ec.category_name
    ORDER BY total_amount DESC";
$family_totals = $conn->query($family_totals_query);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Family Expenses - Personal Fund Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <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 - Family themed */
        .page-header {
            background: linear-gradient(135deg, #27ae60 0%, #2ecc71 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;
        }
        
        /* 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;
        }
        
        /* 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;
        }
        
        /* Family Breakdown */
        .family-breakdown {
            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;
        }
        
        .family-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .family-item:last-child {
            border-bottom: none;
        }
        
        .family-name {
            font-weight: 600;
            color: #1e293b;
        }
        
        .family-stats {
            display: flex;
            gap: 1rem;
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .family-amount {
            font-weight: 600;
            color: #27ae60;
        }
        
        /* Quick Filter Buttons */
        .quick-filters {
            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;
        }
        
        .filter-btn {
            padding: 0.5rem 1rem;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            background: white;
            color: #64748b;
            text-decoration: none;
            margin: 0.25rem;
            display: inline-block;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .filter-btn:hover, .filter-btn.active {
            background: #27ae60;
            color: white;
            border-color: #27ae60;
        }
        
        /* 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; }
        
        /* Payment Method Badges */
        .payment-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .payment-cash { background: #dcfce7; color: #166534; }
        .payment-card { background: #ddd6fe; color: #5b21b6; }
        .payment-bank-transfer { background: #e0e7ff; color: #3730a3; }
        .payment-mpesa { background: #fef3c7; color: #92400e; }
        .payment-mobile-money { background: #fef3c7; color: #92400e; }
        .payment-cheque { background: #f3e8ff; color: #7c3aed; }
        
        /* 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; }
        
        .btn-family { background: #27ae60; color: white; }
        .btn-family:hover { background: #219a52; 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: #27ae60;
            box-shadow: 0 0 0 3px rgba(39, 174, 96, 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: #3b82f6;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
        }
        
        .btn-outline-secondary {
            background: transparent;
            border: 1px solid #e2e8f0;
            color: #64748b;
        }
        
        .btn-outline-secondary:hover {
            background: #f8fafc;
            border-color: #64748b;
        }
        
        /* Expense Avatar */
        .expense-avatar {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            background: #27ae60;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        /* Pagination */
        .pagination-wrapper {
            padding: 1.5rem;
            background: #f8fafc;
            border-top: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-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: #3b82f6;
            color: #3b82f6;
        }
        
        .page-link.active {
            background: #3b82f6;
            border-color: #3b82f6;
            color: white;
        }
        
        /* 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 id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1 class="page-title">Family Expenses</h1>
                        <p class="page-subtitle">Track and manage all family-related expenses and household costs</p>
                    </div>

                    <!-- Stats Row -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['total_count'] ?? 0; ?></div>
                            <div class="stat-label">Total Family Expenses</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['total_paid'] ?? 0); ?></div>
                            <div class="stat-label">Total Paid</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['month_total'] ?? 0); ?></div>
                            <div class="stat-label">This Month</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['pending_count'] ?? 0; ?></div>
                            <div class="stat-label">Pending</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['today_total'] ?? 0); ?></div>
                            <div class="stat-label">Today</div>
                        </div>
                    </div>

                    <!-- Family Breakdown -->
                    <div class="family-breakdown">
                        <h3 style="margin-bottom: 1.5rem; color: #1e293b; font-weight: 600;">Family Expense Breakdown</h3>
                        <?php while ($family = $family_totals->fetch_assoc()): ?>
                        <div class="family-item">
                            <div>
                                <div class="family-name"><?php echo htmlspecialchars($family['category_name']); ?></div>
                                <div class="family-stats">
                                    <span><?php echo $family['count']; ?> expenses</span>
                                    <span>This month: KES <?php echo number_format($family['month_amount']); ?></span>
                                </div>
                            </div>
                            <div class="family-amount">
                                KES <?php echo number_format($family['total_amount']); ?>
                            </div>
                        </div>
                        <?php endwhile; ?>
                    </div>

                    <!-- Quick Filters -->
                    <div class="quick-filters">
                        <h6 style="margin-bottom: 1rem; color: #1e293b;">Quick Filters by Family Category:</h6>
                        <a href="family_expenses.php" class="filter-btn <?php echo empty($family_type) ? 'active' : ''; ?>">All Family</a>
                        <a href="family_expenses.php?type=rent" class="filter-btn <?php echo $family_type === 'rent' ? 'active' : ''; ?>">Rent & Housing</a>
                        <a href="family_expenses.php?type=bills" class="filter-btn <?php echo $family_type === 'bills' ? 'active' : ''; ?>">Bills & Utilities</a>
                        <a href="family_expenses.php?type=groceries" class="filter-btn <?php echo $family_type === 'groceries' ? 'active' : ''; ?>">Groceries & Food</a>
                        <a href="family_expenses.php?type=healthcare" class="filter-btn <?php echo $family_type === 'healthcare' ? 'active' : ''; ?>">Healthcare</a>
                        <a href="family_expenses.php?type=education" class="filter-btn <?php echo $family_type === 'education' ? 'active' : ''; ?>">Education</a>
                        <a href="family_expenses.php?type=transportation" class="filter-btn <?php echo $family_type === 'transportation' ? 'active' : ''; ?>">Transportation</a>
                        <a href="family_expenses.php?type=entertainment" class="filter-btn <?php echo $family_type === 'entertainment' ? 'active' : ''; ?>">Entertainment</a>
                    </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 family expenses...">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Family Category</label>
                                <select class="form-select" name="family_filter">
                                    <option value="">All Categories</option>
                                    <?php 
                                    $family_categories_result->data_seek(0);
                                    while ($family = $family_categories_result->fetch_assoc()): 
                                    ?>
                                        <option value="<?php echo $family['category_id']; ?>" <?php echo $family_filter == $family['category_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($family['category_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </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-2">
                                <label class="form-label">From Date</label>
                                <input type="date" class="form-control" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">To Date</label>
                                <input type="date" class="form-control" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>">
                            </div>
                            <div class="col-md-12">
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary">Filter</button>
                                    <a href="family_expenses.php" class="btn btn-outline-secondary">Clear</a>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Family Expenses Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Family Expenses (<?php echo $total_expenses; ?> total)</h3>
                            <div class="d-flex gap-2">
                                <a href="add_expense.php?type=FAMILY" class="btn btn-family">
                                    <i class="ph-plus me-1"></i> Add Family Expense
                                </a>
                                <a href="expense_reports.php?type=FAMILY" class="btn btn-primary">
                                    <i class="ph-chart-bar me-1"></i> Family Reports
                                </a>
                            </div>
                        </div>
                        
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Expense Details</th>
                                    <th>Family Category</th>
                                    <th>Amount</th>
                                    <th>Payment Method</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                    <th>Created By</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($expense = $expenses->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="expense-avatar me-3">
                                                FA
                                            </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: #27ae60; font-size: 0.75rem;">
                                                        Vendor: <?php echo htmlspecialchars($expense['vendor_name']); ?>
                                                    </div>
                                                <?php endif; ?>
                                                <?php if ($expense['description'] && strlen($expense['description']) > 0): ?>
                                                    <div style="color: #64748b; font-size: 0.75rem;">
                                                       <?php echo htmlspecialchars(substr($expense['description'], 0, 50)) . (strlen($expense['description']) > 50 ? '...' : ''); ?>
                                                   </div>
                                               <?php endif; ?>
                                           </div>
                                       </div>
                                   </td>
                                   <td>
                                       <div>
                                           <span style="font-weight: 500; color: #1e293b;">
                                               <?php echo htmlspecialchars($expense['category_name']); ?>
                                           </span>
                                       </div>
                                       <span class="type-badge" style="background: #dcfce7; color: #166534; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.75rem;">
                                           Family Expense
                                       </span>
                                   </td>
                                   <td>
                                       <span style="font-weight: 600; color: #1e293b; font-size: 1rem;">
                                           KES <?php echo number_format($expense['amount'], 2); ?>
                                       </span>
                                       <?php if ($expense['receipt_number']): ?>
                                           <div style="color: #64748b; font-size: 0.75rem;">
                                               Receipt: <?php echo htmlspecialchars($expense['receipt_number']); ?>
                                           </div>
                                       <?php endif; ?>
                                   </td>
                                   <td>
                                       <?php 
                                       $payment_class = match($expense['payment_method']) {
                                           'CASH' => 'payment-cash',
                                           'CARD' => 'payment-card',
                                           'BANK_TRANSFER' => 'payment-bank-transfer',
                                           'MPESA' => 'payment-mpesa',
                                           'MOBILE_MONEY' => 'payment-mobile-money',
                                           'CHEQUE' => 'payment-cheque',
                                           default => 'payment-cash'
                                       };
                                       ?>
                                       <span class="payment-badge <?php echo $payment_class; ?>">
                                           <?php echo ucfirst(str_replace('_', ' ', strtolower($expense['payment_method']))); ?>
                                       </span>
                                       <?php if ($expense['payment_reference']): ?>
                                           <div style="color: #64748b; font-size: 0.75rem;">
                                               Ref: <?php echo htmlspecialchars($expense['payment_reference']); ?>
                                           </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['requires_approval'] && $expense['status'] == 'PENDING'): ?>
                                           <div style="color: #d97706; font-size: 0.75rem;">
                                               <i class="ph-warning"></i> Needs Approval
                                           </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;">
                                           Added: <?php echo date('M j, g:i A', strtotime($expense['created_at'])); ?>
                                       </div>
                                       <?php if ($expense['approved_at']): ?>
                                           <div style="color: #059669; font-size: 0.75rem;">
                                               Approved: <?php echo date('M j, g:i A', strtotime($expense['approved_at'])); ?>
                                           </div>
                                       <?php endif; ?>
                                   </td>
                                   <td>
                                       <div style="font-weight: 500; color: #1e293b;">
                                           <?php echo htmlspecialchars($expense['created_by_name']); ?>
                                       </div>
                                       <?php if ($expense['approved_by_name']): ?>
                                           <div style="color: #059669; font-size: 0.75rem;">
                                               Approved by: <?php echo htmlspecialchars($expense['approved_by_name']); ?>
                                           </div>
                                       <?php endif; ?>
                                   </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 Expense">
                                                   <i class="ph-pencil"></i>
                                               </a>
                                           <?php endif; ?>
                                           <?php if ($expense['status'] == 'PENDING' && $role_name == 'Administrator'): ?>
                                               <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-family" title="Print Receipt" target="_blank">
                                                   <i class="ph-printer"></i>
                                               </a>
                                           <?php endif; ?>
                                       </div>
                                   </td>
                               </tr>
                               <?php endwhile; ?>
                           </tbody>
                       </table>

                       <!-- Pagination -->
                       <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>
                           
                           <?php if ($total_pages > 1): ?>
                               <div class="pagination">
                                   <?php if ($page > 1): ?>
                                       <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&family_filter=<?php echo $family_filter; ?>&status_filter=<?php echo $status_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&type=<?php echo $family_type; ?>" 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="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&family_filter=<?php echo $family_filter; ?>&status_filter=<?php echo $status_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&type=<?php echo $family_type; ?>" 
                                          class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                                           <?php echo $i; ?>
                                       </a>
                                   <?php endfor; ?>
                                   
                                   <?php if ($page < $total_pages): ?>
                                       <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&family_filter=<?php echo $family_filter; ?>&status_filter=<?php echo $status_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&type=<?php echo $family_type; ?>" class="page-link">
                                           <i class="ph-caret-right"></i>
                                       </a>
                                   <?php endif; ?>
                               </div>
                           <?php endif; ?>
                       </div>
                   </div>
               </div>
           </div>
           <?php include 'layouts/footer.php'; ?>
       </div>
   </div>

   <?php include 'layouts/vendor-scripts.php'; ?>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   
   <script>
       // Auto-submit form on filter change
       $(document).ready(function() {
           $('.form-select').on('change', function() {
               $(this).closest('form').submit();
           });
       });
   </script>

   <!-- App js -->
   <script src="assets/js/app.js"></script>
</body>
</html>

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