<?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'] ?? '';
$contributor_filter = $_GET['contributor_filter'] ?? '';
$fund_filter = $_GET['fund_filter'] ?? '';
$type_filter = $_GET['type_filter'] ?? '';
$payment_method_filter = $_GET['payment_method_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
$where_conditions = array("1=1");
$params = array();
$param_types = "";

if (!empty($search)) {
    $where_conditions[] = "(ft.transaction_number LIKE ? OR ft.description LIKE ? OR ft.purpose LIKE ? OR ft.reference_number LIKE ? OR CONCAT(c.first_name, ' ', c.last_name) LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param, $search_param]);
    $param_types .= "sssss";
}

if (!empty($contributor_filter)) {
    $where_conditions[] = "ft.contributor_id = ?";
    $params[] = $contributor_filter;
    $param_types .= "i";
}

if (!empty($fund_filter)) {
    $where_conditions[] = "ft.fund_id = ?";
    $params[] = $fund_filter;
    $param_types .= "i";
}

if (!empty($type_filter)) {
    $where_conditions[] = "ft.transaction_type = ?";
    $params[] = $type_filter;
    $param_types .= "s";
}

if (!empty($payment_method_filter)) {
    $where_conditions[] = "ft.payment_method = ?";
    $params[] = $payment_method_filter;
    $param_types .= "s";
}

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

if (!empty($date_to)) {
    $where_conditions[] = "ft.transaction_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 fund_transactions ft 
                LEFT JOIN contributors c ON ft.contributor_id = c.contributor_id 
                LEFT JOIN funds f ON ft.fund_id = f.fund_id 
                WHERE $where_clause";
$count_stmt = $conn->prepare($count_query);
if (!empty($params)) {
    $count_stmt->bind_param($param_types, ...$params);
}
$count_stmt->execute();
$total_transactions = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_transactions / $limit);

// Get transactions with pagination
$query = "SELECT ft.*, 
                 CONCAT(c.first_name, ' ', c.last_name) as contributor_name,
                 c.contributor_number, c.phone_primary,
                 f.fund_name, f.fund_code,
                 u.full_name as processed_by_name
          FROM fund_transactions ft 
          LEFT JOIN contributors c ON ft.contributor_id = c.contributor_id 
          LEFT JOIN funds f ON ft.fund_id = f.fund_id 
          LEFT JOIN users u ON ft.processed_by = u.user_id
          WHERE $where_clause
          ORDER BY ft.transaction_date DESC, ft.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();
$transactions = $stmt->get_result();

// Get contributors for filter dropdown
$contributors_query = "SELECT c.contributor_id, CONCAT(c.first_name, ' ', c.last_name) as contributor_name 
                       FROM contributors c WHERE c.is_active = 1 ORDER BY c.first_name, c.last_name";
$contributors_result = $conn->query($contributors_query);

// Get funds for filter dropdown
$funds_query = "SELECT fund_id, fund_name, fund_code FROM funds WHERE is_active = 1 ORDER BY fund_name";
$funds_result = $conn->query($funds_query);

// Get summary statistics
$stats_query = "SELECT 
    COUNT(*) as total_transactions,
    SUM(CASE WHEN transaction_type = 'CONTRIBUTION' THEN amount ELSE 0 END) as total_contributions,
    SUM(CASE WHEN transaction_type = 'WITHDRAWAL' THEN amount ELSE 0 END) as total_withdrawals,
    SUM(CASE WHEN transaction_type = 'CONTRIBUTION' THEN amount ELSE -amount END) as net_amount
    FROM fund_transactions 
    WHERE status = 'COMPLETED'";
$stats = $conn->query($stats_query)->fetch_assoc();

// Get today's stats
$today_stats_query = "SELECT 
    COUNT(*) as transactions_today,
    SUM(CASE WHEN transaction_type = 'CONTRIBUTION' THEN amount ELSE 0 END) as contributions_today,
    SUM(CASE WHEN transaction_type = 'WITHDRAWAL' THEN amount ELSE 0 END) as withdrawals_today
    FROM fund_transactions 
    WHERE DATE(transaction_date) = CURDATE() AND status = 'COMPLETED'";
$today_stats = $conn->query($today_stats_query)->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Fund Transactions - Fund Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <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 */
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 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-value.positive {
            color: #059669;
        }
        
        .stat-value.negative {
            color: #dc2626;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        /* 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;
        }
        
        /* Transaction Type Badges */
        .transaction-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .transaction-contribution { background: #dcfce7; color: #166534; }
        .transaction-withdrawal { background: #fee2e2; color: #991b1b; }
        .transaction-transfer-in { background: #ddd6fe; color: #5b21b6; }
        .transaction-transfer-out { background: #fef3c7; color: #92400e; }
        
        /* 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-bank-transfer { background: #ddd6fe; color: #5b21b6; }
        .payment-mpesa { background: #fef3c7; color: #92400e; }
        .payment-mobile-money { background: #e0e7ff; color: #3730a3; }
        .payment-cheque { background: #f0f9ff; color: #0369a1; }
        .payment-other { background: #f1f5f9; color: #475569; }
        
        /* 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-completed { background: #dcfce7; color: #166534; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        .status-failed { background: #fee2e2; color: #991b1b; }
        
        /* 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-info { background: #0891b2; color: white; }
        .btn-info:hover { background: #0e7490; color: white; }
        
        /* 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: #3b82f6;
            color: #3b82f6;
        }
        
        .page-link.active {
            background: #3b82f6;
            border-color: #3b82f6;
            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: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 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;
        }
        
        /* Avatar */
        .contributor-avatar {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            background: #059669;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.75rem;
        }
        
        /* Amount styling */
        .amount-positive {
            color: #059669;
            font-weight: 600;
        }
        
        .amount-negative {
            color: #dc2626;
            font-weight: 600;
        }
        
        /* 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;
            }
        }
        
        /* Footer spacing fix */
        .main-content {
            padding-bottom: 2rem;
        }
        
        .page-content {
            margin-bottom: 3rem;
        }
    </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">Fund Transactions</h1>
                        <p class="page-subtitle">Track all fund contributions and withdrawals</p>
                    </div>

                    <!-- Stats Row -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($stats['total_transactions'] ?? 0); ?></div>
                            <div class="stat-label">Total Transactions</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value positive">KES <?php echo number_format($stats['total_contributions'] ?? 0); ?></div>
                            <div class="stat-label">Total Contributions</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value negative">KES <?php echo number_format($stats['total_withdrawals'] ?? 0); ?></div>
                            <div class="stat-label">Total Withdrawals</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value <?php echo ($stats['net_amount'] ?? 0) >= 0 ? 'positive' : 'negative'; ?>">
                                KES <?php echo number_format($stats['net_amount'] ?? 0); ?>
                            </div>
                            <div class="stat-label">Net Amount</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 transactions...">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Contributor</label>
                                <select class="form-select" name="contributor_filter">
                                    <option value="">All Contributors</option>
                                    <?php while ($contributor = $contributors_result->fetch_assoc()): ?>
                                        <option value="<?php echo $contributor['contributor_id']; ?>" <?php echo $contributor_filter == $contributor['contributor_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($contributor['contributor_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Fund</label>
                                <select class="form-select" name="fund_filter">
                                    <option value="">All Funds</option>
                                    <?php while ($fund = $funds_result->fetch_assoc()): ?>
                                        <option value="<?php echo $fund['fund_id']; ?>" <?php echo $fund_filter == $fund['fund_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($fund['fund_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Type</label>
                                <select class="form-select" name="type_filter">
                                    <option value="">All Types</option>
                                    <option value="CONTRIBUTION" <?php echo $type_filter == 'CONTRIBUTION' ? 'selected' : ''; ?>>Contribution</option>
                                    <option value="WITHDRAWAL" <?php echo $type_filter == 'WITHDRAWAL' ? 'selected' : ''; ?>>Withdrawal</option>
                                    <option value="TRANSFER_IN" <?php echo $type_filter == 'TRANSFER_IN' ? 'selected' : ''; ?>>Transfer In</option>
                                    <option value="TRANSFER_OUT" <?php echo $type_filter == 'TRANSFER_OUT' ? 'selected' : ''; ?>>Transfer Out</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Payment Method</label>
                                <select class="form-select" name="payment_method_filter">
                                    <option value="">All Methods</option>
                                    <option value="CASH" <?php echo $payment_method_filter == 'CASH' ? 'selected' : ''; ?>>Cash</option>
                                    <option value="BANK_TRANSFER" <?php echo $payment_method_filter == 'BANK_TRANSFER' ? 'selected' : ''; ?>>Bank Transfer</option>
                                    <option value="MPESA" <?php echo $payment_method_filter == 'MPESA' ? 'selected' : ''; ?>>M-Pesa</option>
                                    <option value="MOBILE_MONEY" <?php echo $payment_method_filter == 'MOBILE_MONEY' ? 'selected' : ''; ?>>Mobile Money</option>
                                    <option value="CHEQUE" <?php echo $payment_method_filter == 'CHEQUE' ? 'selected' : ''; ?>>Cheque</option>
                                </select>
                            </div>
                        </form>
                        
                        <div class="row g-3 mt-2">
                            <div class="col-md-2">
                                <label class="form-label">Date From</label>
                                <input type="date" class="form-control" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>" form="filterForm">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Date To</label>
                                <input type="date" class="form-control" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>" form="filterForm">
                            </div>
                            <div class="col-md-8">
                                <label class="form-label">&nbsp;</label>
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary" form="filterForm">Filter</button>
                                    <a href="fund_transactions.php" class="btn btn-outline-secondary">Clear</a>
                                </div>
                            </div>
                        </div>
                        
                        <form id="filterForm" method="GET" style="display: none;">
                            <input type="hidden" name="search" value="<?php echo htmlspecialchars($search); ?>">
                            <input type="hidden" name="contributor_filter" value="<?php echo htmlspecialchars($contributor_filter); ?>">
                            <input type="hidden" name="fund_filter" value="<?php echo htmlspecialchars($fund_filter); ?>">
                            <input type="hidden" name="type_filter" value="<?php echo htmlspecialchars($type_filter); ?>">
                            <input type="hidden" name="payment_method_filter" value="<?php echo htmlspecialchars($payment_method_filter); ?>">
                        </form>
                    </div>

                    <!-- Transactions Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Transaction History (<?php echo $total_transactions; ?> total)</h3>
                            <div class="d-flex gap-2">
                                <a href="add_transaction.php" class="btn btn-success">
                                    <i class="ph-plus me-1"></i> Add Transaction
                                </a>
                                <a href="export_transactions.php" class="btn btn-info">
                                    <i class="ph-download me-1"></i> Export
                                </a>
                            </div>
                        </div>
                        
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Transaction</th>
                                    <th>Contributor</th>
                                    <th>Fund</th>
                                    <th>Type</th>
                                    <th>Amount</th>
                                    <th>Payment Method</th>
                                    <th>Date</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($transaction = $transactions->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div style="font-weight: 600; color: #1e293b;">
                                            <?php echo htmlspecialchars($transaction['transaction_number']); ?>
                                        </div>
                                        <?php if ($transaction['purpose']): ?>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                <?php echo htmlspecialchars(substr($transaction['purpose'], 0, 30)) . (strlen($transaction['purpose']) > 30 ? '...' : ''); ?>
                                            </div>
                                        <?php endif; ?>
                                        <?php if ($transaction['reference_number']): ?>
                                            <div style="color: #059669; font-size: 0.75rem;">
                                                Ref: <?php echo htmlspecialchars($transaction['reference_number']); ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="contributor-avatar me-2">
                                                <?php 
                                                $names = explode(' ', $transaction['contributor_name']);
                                                echo strtoupper(substr($names[0], 0, 1) . (isset($names[1]) ? substr($names[1], 0, 1) : ''));
                                                ?>
                                            </div>
                                            <div>
                                                <div style="font-weight: 500; color: #1e293b;">
                                                    <?php echo htmlspecialchars($transaction['contributor_name']); ?>
                                                </div>
                                                <div style="color: #64748b; font-size: 0.75rem;">
                                                    <?php echo htmlspecialchars($transaction['contributor_number']); ?>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="font-weight: 500; color: #1e293b;">
                                            <?php echo htmlspecialchars($transaction['fund_name']); ?>
                                        </div>
                                        <div style="color: #64748b; font-size: 0.75rem;">
                                            <?php echo htmlspecialchars($transaction['fund_code']); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <?php 
                                        $type_class = match($transaction['transaction_type']) {
                                            'CONTRIBUTION' => 'transaction-contribution',
                                            'WITHDRAWAL' => 'transaction-withdrawal',
                                            'TRANSFER_IN' => 'transaction-transfer-in',
                                            'TRANSFER_OUT' => 'transaction-transfer-out',
                                            default => 'transaction-contribution'
                                        };
                                        ?>
                                        <span class="transaction-badge <?php echo $type_class; ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', strtolower($transaction['transaction_type']))); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php 
                                        $amount_class = in_array($transaction['transaction_type'], ['CONTRIBUTION', 'TRANSFER_IN']) ? 'amount-positive' : 'amount-negative';
                                        $amount_prefix = in_array($transaction['transaction_type'], ['CONTRIBUTION', 'TRANSFER_IN']) ? '+' : '-';
                                        ?>
                                        <span class="<?php echo $amount_class; ?>">
                                            <?php echo $amount_prefix; ?>KES <?php echo number_format($transaction['amount']); ?>
                                        </span>
                                        <?php if ($transaction['balance_after'] > 0): ?>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                Balance: KES <?php echo number_format($transaction['balance_after']); ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php 
                                        $payment_class = match($transaction['payment_method']) {
                                            'CASH' => 'payment-cash',
                                            'BANK_TRANSFER' => 'payment-bank-transfer',
                                            'MPESA' => 'payment-mpesa',
                                            'MOBILE_MONEY' => 'payment-mobile-money',
                                            'CHEQUE' => 'payment-cheque',
                                            default => 'payment-other'
                                        };
                                        ?>
                                        <span class="payment-badge <?php echo $payment_class; ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', strtolower($transaction['payment_method']))); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div style="font-weight: 500; color: #1e293b;">
                                            <?php echo date('M j, Y', strtotime($transaction['transaction_date'])); ?>
                                        </div>
                                        <div style="color: #64748b; font-size: 0.75rem;">
                                            Added: <?php echo date('M j, g:i A', strtotime($transaction['created_at'])); ?>
                                        </div>
                                        <?php if ($transaction['processed_by_name']): ?>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                By: <?php echo htmlspecialchars($transaction['processed_by_name']); ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php 
                                        $status_class = match($transaction['status']) {
                                            'COMPLETED' => 'status-completed',
                                            'PENDING' => 'status-pending',
                                            'CANCELLED' => 'status-cancelled',
                                            'FAILED' => 'status-failed',
                                            default => 'status-pending'
                                        };
                                        ?>
                                        <span class="status-badge <?php echo $status_class; ?>">
                                            <?php echo ucfirst(strtolower($transaction['status'])); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="d-flex gap-1">
                                            <a href="view_transaction.php?id=<?php echo $transaction['transaction_id']; ?>" class="btn-action btn-primary" title="View Details">
                                                <i class="ph-eye"></i>
                                            </a>
                                            <?php if ($transaction['status'] == 'PENDING'): ?>
                                                <a href="edit_transaction.php?id=<?php echo $transaction['transaction_id']; ?>" class="btn-action btn-warning" title="Edit Transaction">
                                                    <i class="ph-pencil"></i>
                                                </a>
                                            <?php endif; ?>
                                            <a href="print_receipt.php?id=<?php echo $transaction['transaction_id']; ?>" class="btn-action btn-success" title="Print Receipt" target="_blank">
                                                <i class="ph-printer"></i>
                                            </a>
                                        </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_transactions); ?> of <?php echo $total_transactions; ?> 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); ?>&contributor_filter=<?php echo $contributor_filter; ?>&fund_filter=<?php echo $fund_filter; ?>&type_filter=<?php echo $type_filter; ?>&payment_method_filter=<?php echo $payment_method_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>" 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); ?>&contributor_filter=<?php echo $contributor_filter; ?>&fund_filter=<?php echo $fund_filter; ?>&type_filter=<?php echo $type_filter; ?>&payment_method_filter=<?php echo $payment_method_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>" 
                                           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); ?>&contributor_filter=<?php echo $contributor_filter; ?>&fund_filter=<?php echo $fund_filter; ?>&type_filter=<?php echo $type_filter; ?>&payment_method_filter=<?php echo $payment_method_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>" 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>
        $(document).ready(function() {
            // Auto-submit form on filter change
            $('.form-select').on('change', function() {
                updateHiddenFields();
                $('#filterForm').submit();
            });
            
            // Handle date filter changes
            $('input[name="date_from"], input[name="date_to"]').on('change', function() {
                updateHiddenFields();
            });
            
            function updateHiddenFields() {
                // Update hidden form fields with current filter values
                $('input[name="search"]', '#filterForm').val($('input[name="search"]').val());
                $('input[name="contributor_filter"]', '#filterForm').val($('select[name="contributor_filter"]').val());
                $('input[name="fund_filter"]', '#filterForm').val($('select[name="fund_filter"]').val());
                $('input[name="type_filter"]', '#filterForm').val($('select[name="type_filter"]').val());
                $('input[name="payment_method_filter"]', '#filterForm').val($('select[name="payment_method_filter"]').val());
                
                // Add date fields to hidden form
                if (!$('input[name="date_from"]', '#filterForm').length) {
                    $('#filterForm').append('<input type="hidden" name="date_from">');
                    $('#filterForm').append('<input type="hidden" name="date_to">');
                }
                $('input[name="date_from"]', '#filterForm').val($('input[name="date_from"]').val());
                $('input[name="date_to"]', '#filterForm').val($('input[name="date_to"]').val());
            }
            
            // Search on enter key
            $('input[name="search"]').on('keypress', function(e) {
                if (e.which === 13) {
                    updateHiddenFields();
                    $('#filterForm').submit();
                }
            });
            
            // Initialize date range picker (if you want to add this feature)
            var today = new Date();
            var thirtyDaysAgo = new Date(today.getTime() - (30 * 24 * 60 * 60 * 1000));
            
            // Set default date range if none specified
            if (!$('input[name="date_from"]').val() && !$('input[name="date_to"]').val()) {
                // Uncomment these lines if you want default date range
                // $('input[name="date_from"]').val(thirtyDaysAgo.toISOString().split('T')[0]);
                // $('input[name="date_to"]').val(today.toISOString().split('T')[0]);
            }
        });
    </script>

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

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