<?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'] ?? '';
$fund_filter = $_GET['fund_filter'] ?? '';
$contributor_filter = $_GET['contributor_filter'] ?? '';
$transaction_type_filter = $_GET['transaction_type_filter'] ?? '';
$payment_method_filter = $_GET['payment_method_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
$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 ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    $param_types .= "ssss";
}

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

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

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

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

if (!empty($status_filter)) {
    $where_conditions[] = "ft.status = ?";
    $params[] = $status_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 funds f ON ft.fund_id = f.fund_id 
                LEFT JOIN contributors c ON ft.contributor_id = c.contributor_id 
                LEFT JOIN users u ON ft.processed_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_transactions = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_transactions / $limit);

// Get transactions with pagination
$query = "SELECT ft.*, 
                 f.fund_name, f.fund_code,
                 CONCAT(c.first_name, ' ', c.last_name) as contributor_name,
                 c.contributor_number,
                 u.full_name as processed_by_name
          FROM fund_transactions ft 
          LEFT JOIN funds f ON ft.fund_id = f.fund_id 
          LEFT JOIN contributors c ON ft.contributor_id = c.contributor_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 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 contributors for filter dropdown
$contributors_query = "SELECT contributor_id, contributor_number, CONCAT(first_name, ' ', last_name) as full_name 
                       FROM contributors WHERE is_active = 1 ORDER BY first_name, last_name";
$contributors_result = $conn->query($contributors_query);

// Get transaction 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,
    COUNT(CASE WHEN transaction_date = CURDATE() THEN 1 END) as today_transactions,
    SUM(CASE WHEN transaction_date = CURDATE() AND transaction_type = 'CONTRIBUTION' THEN amount ELSE 0 END) as today_contributions,
    SUM(CASE WHEN transaction_date = CURDATE() AND transaction_type = 'WITHDRAWAL' THEN amount ELSE 0 END) as today_withdrawals,
    COUNT(CASE WHEN status = 'PENDING' THEN 1 END) as pending_transactions
    FROM fund_transactions";
$stats = $conn->query($stats_query)->fetch_assoc();

// Calculate net flow
$net_flow = ($stats['total_contributions'] ?? 0) - ($stats['total_withdrawals'] ?? 0);
$today_net_flow = ($stats['today_contributions'] ?? 0) - ($stats['today_withdrawals'] ?? 0);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'All Transactions - Personal Fund Tracker')); ?>
    <?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">
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        /* Use the same styling from list_consultations.php */
        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;
            position: relative;
        }
        
        .stat-card.positive {
            border-left: 4px solid #059669;
        }
        
        .stat-card.negative {
            border-left: 4px solid #dc2626;
        }
        
        .stat-card.neutral {
            border-left: 4px solid #3b82f6;
        }
        
        .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;
        }
        
        .stat-change {
            font-size: 0.75rem;
            margin-top: 0.5rem;
        }
        
        .stat-change.positive {
            color: #059669;
        }
        
        .stat-change.negative {
            color: #dc2626;
        }
        
        /* 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; }
        .transaction-adjustment { background: #f1f5f9; color: #64748b; }
        
        /* 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; }
        
        /* 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: #fef3c7; color: #92400e; }
        .payment-cheque { background: #e0e7ff; color: #3730a3; }
        .payment-other { background: #f1f5f9; color: #64748b; }
        
        /* 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; }
        
        /* Transaction Amount Styling */
        .amount-positive {
            color: #059669;
            font-weight: 600;
        }
        
        .amount-negative {
            color: #dc2626;
            font-weight: 600;
        }
        
        /* 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;
        }
        
        /* Transaction Avatar */
        .transaction-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .avatar-contribution {
            background: #059669;
        }
        
        .avatar-withdrawal {
            background: #dc2626;
        }
        
        .avatar-transfer {
            background: #3b82f6;
        }
        
        /* Quick Stats */
        .quick-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 1rem;
            background: #f8fafc;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
        
        .quick-stat {
            text-align: center;
        }
        
        .quick-stat-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
        }
        
        .quick-stat-label {
            font-size: 0.75rem;
            color: #64748b;
            text-transform: uppercase;
        }
        
        /* 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">All Transactions</h1>
                        <p class="page-subtitle">Monitor and manage all fund transactions</p>
                    </div>

                    <!-- Stats Row -->
                    <div class="stats-row">
                        <div class="stat-card neutral">
                            <div class="stat-value"><?php echo $stats['total_transactions'] ?? 0; ?></div>
                            <div class="stat-label">Total Transactions</div>
                            <div class="stat-change positive">
                                <?php echo $stats['today_transactions'] ?? 0; ?> today
                            </div>
                        </div>
                        <div class="stat-card positive">
                            <div class="stat-value">KES <?php echo number_format($stats['total_contributions'] ?? 0); ?></div>
                            <div class="stat-label">Total Contributions</div>
                            <div class="stat-change positive">
                                +KES <?php echo number_format($stats['today_contributions'] ?? 0); ?> today
                            </div>
                        </div>
                        <div class="stat-card negative">
                            <div class="stat-value">KES <?php echo number_format($stats['total_withdrawals'] ?? 0); ?></div>
                            <div class="stat-label">Total Withdrawals</div>
                            <div class="stat-change negative">
                                -KES <?php echo number_format($stats['today_withdrawals'] ?? 0); ?> today
                            </div>
                        </div>
                        <div class="stat-card <?php echo $net_flow >= 0 ? 'positive' : 'negative'; ?>">
                            <div class="stat-value">KES <?php echo number_format($net_flow); ?></div>
                            <div class="stat-label">Net Flow</div>
                            <div class="stat-change <?php echo $today_net_flow >= 0 ? 'positive' : 'negative'; ?>">
                                <?php echo $today_net_flow >= 0 ? '+' : '-'; ?>KES <?php echo number_format(abs($today_net_flow)); ?> today
                            </div>
                        </div>
                        <?php if ($stats['pending_transactions'] > 0): ?>
                        <div class="stat-card" style="border-left: 4px solid #d97706;">
                            <div class="stat-value"><?php echo $stats['pending_transactions']; ?></div>
                            <div class="stat-label">Pending Transactions</div>
                        </div>
                        <?php endif; ?>
                    </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 transaction number, description...">
                            </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">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['full_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Type</label>
                                <select class="form-select" name="transaction_type_filter">
                                    <option value="">All Types</option>
                                    <option value="CONTRIBUTION" <?php echo $transaction_type_filter == 'CONTRIBUTION' ? 'selected' : ''; ?>>Contribution</option>
                                    <option value="WITHDRAWAL" <?php echo $transaction_type_filter == 'WITHDRAWAL' ? 'selected' : ''; ?>>Withdrawal</option>
                                    <option value="TRANSFER_IN" <?php echo $transaction_type_filter == 'TRANSFER_IN' ? 'selected' : ''; ?>>Transfer In</option>
                                    <option value="TRANSFER_OUT" <?php echo $transaction_type_filter == 'TRANSFER_OUT' ? 'selected' : ''; ?>>Transfer Out</option>
                                    <option value="ADJUSTMENT" <?php echo $transaction_type_filter == 'ADJUSTMENT' ? 'selected' : ''; ?>>Adjustment</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Date Range</label>
                                <div class="row g-2">
                                    <div class="col-6">
                                        <input type="date" class="form-control" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>" placeholder="From">
                                    </div>
                                    <div class="col-6">
                                        <input type="date" class="form-control" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>" placeholder="To">
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <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>
                            <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="COMPLETED" <?php echo $status_filter == 'COMPLETED' ? 'selected' : ''; ?>>Completed</option>
                                    <option value="PENDING" <?php echo $status_filter == 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="CANCELLED" <?php echo $status_filter == 'CANCELLED' ? 'selected' : ''; ?>>Cancelled</option>
                                    <option value="FAILED" <?php echo $status_filter == 'FAILED' ? 'selected' : ''; ?>>Failed</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">&nbsp;</label>
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary">Filter</button>
                                    <a href="list_transactions.php" class="btn btn-outline-secondary">Clear</a>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Transactions Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Transactions List (<?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>
                                <button type="button" class="btn btn-primary" onclick="exportTransactions()">
                                    <i class="ph-download me-1"></i> Export
                                </button>
                            </div>
                        </div>
                        
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Transaction Details</th>
                                    <th>Fund & Contributor</th>
                                    <th>Type & Amount</th>
                                    <th>Payment Method</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                    <th>Processed By</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($transaction = $transactions->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="transaction-avatar me-3 avatar-<?php echo strtolower($transaction['transaction_type']); ?>">
                                                <?php 
                                                $icon = match($transaction['transaction_type']) {
                                                    'CONTRIBUTION' => '↗',
                                                    'WITHDRAWAL' => '↙',
                                                    'TRANSFER_IN' => '→',
                                                    'TRANSFER_OUT' => '←',
                                                    default => '•'
                                                };
                                                echo $icon;
                                                ?>
                                            </div>
                                            <div>
                                                <div style="font-weight: 600; color: #1e293b;">
                                                    <?php echo htmlspecialchars($transaction['transaction_number']); ?>
                                                </div>
                                                <?php if ($transaction['description']): ?>
                                                    <div style="color: #64748b; font-size: 0.75rem;">
                                                        <?php echo htmlspecialchars(substr($transaction['description'], 0, 40)) . (strlen($transaction['description']) > 40 ? '...' : ''); ?>
                                                    </div>
                                                <?php endif; ?>
                                                <?php if ($transaction['reference_number']): ?>
                                                    <div style="color: #3b82f6; font-size: 0.75rem;">
                                                        Ref: <?php echo htmlspecialchars($transaction['reference_number']); ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="font-weight: 600; color: #1e293b;">
                                            <?php echo htmlspecialchars($transaction['fund_name']); ?>
                                        </div>
                                        <div style="color: #64748b; font-size: 0.75rem;">
                                            <?php echo htmlspecialchars($transaction['fund_code']); ?>
                                        </div>
                                        <div style="color: #059669; font-size: 0.75rem; margin-top: 0.25rem;">
                                            <?php echo htmlspecialchars($transaction['contributor_name']); ?>
                                        </div>
                                        <div style="color: #64748b; font-size: 0.75rem;">
                                            <?php echo htmlspecialchars($transaction['contributor_number']); ?>
                                        </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',
                                            'ADJUSTMENT' => 'transaction-adjustment',
                                            default => 'transaction-adjustment'
                                        };
                                        ?>
                                        <span class="transaction-badge <?php echo $type_class; ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', strtolower($transaction['transaction_type']))); ?>
                                        </span>
                                        <div class="<?php echo in_array($transaction['transaction_type'], ['CONTRIBUTION', 'TRANSFER_IN']) ? 'amount-positive' : 'amount-negative'; ?>" style="margin-top: 0.5rem;">
                                            <?php echo in_array($transaction['transaction_type'], ['CONTRIBUTION', 'TRANSFER_IN']) ? '+' : '-'; ?>KES <?php echo number_format($transaction['amount']); ?>
                                        </div>
                                        <?php if ($transaction['interest_rate'] > 0): ?>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                Interest: <?php echo $transaction['interest_rate']; ?>%
                                            </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>
                                        <?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 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;">
                                            Created: <?php echo date('M j, g:i A', strtotime($transaction['created_at'])); ?>
                                        </div>
                                        <?php if ($transaction['expected_return_date']): ?>
                                            <div style="color: #d97706; font-size: 0.75rem;">
                                                Return: <?php echo date('M j, Y', strtotime($transaction['expected_return_date'])); ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div style="font-weight: 500; color: #1e293b;">
                                            <?php echo htmlspecialchars($transaction['processed_by_name'] ?? 'System'); ?>
                                        </div>
                                    </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' && in_array($role_name, ['Administrator', 'Fund Manager'])): ?>
                                                <button type="button" class="btn-action btn-success" onclick="approveTransaction(<?php echo $transaction['transaction_id']; ?>)" title="Approve">
                                                    <i class="ph-check"></i>
                                                </button>
                                                <button type="button" class="btn-action btn-danger" onclick="cancelTransaction(<?php echo $transaction['transaction_id']; ?>)" title="Cancel">
                                                    <i class="ph-x"></i>
                                                </button>
                                            <?php endif; ?>
                                            <?php if ($transaction['status'] == 'COMPLETED'): ?>
                                                <a href="print_transaction.php?id=<?php echo $transaction['transaction_id']; ?>" class="btn-action btn-warning" 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_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); ?>&fund_filter=<?php echo $fund_filter; ?>&contributor_filter=<?php echo $contributor_filter; ?>&transaction_type_filter=<?php echo $transaction_type_filter; ?>&payment_method_filter=<?php echo $payment_method_filter; ?>&status_filter=<?php echo $status_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); ?>&fund_filter=<?php echo $fund_filter; ?>&contributor_filter=<?php echo $contributor_filter; ?>&transaction_type_filter=<?php echo $transaction_type_filter; ?>&payment_method_filter=<?php echo $payment_method_filter; ?>&status_filter=<?php echo $status_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); ?>&fund_filter=<?php echo $fund_filter; ?>&contributor_filter=<?php echo $contributor_filter; ?>&transaction_type_filter=<?php echo $transaction_type_filter; ?>&payment_method_filter=<?php echo $payment_method_filter; ?>&status_filter=<?php echo $status_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>
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        $(document).ready(function() {
            // Auto-submit form on filter change
            $('.form-select').on('change', function() {
                $(this).closest('form').submit();
            });
            
            // Date range validation
            $('input[name="date_from"], input[name="date_to"]').on('change', function() {
                const dateFrom = $('input[name="date_from"]').val();
                const dateTo = $('input[name="date_to"]').val();
                
                if (dateFrom && dateTo && new Date(dateFrom) > new Date(dateTo)) {
                    Swal.fire({
                        title: 'Invalid Date Range!',
                        text: 'Start date cannot be after end date.',
                        icon: 'error',
                        confirmButtonColor: '#dc2626'
                    });
                    $(this).val('');
                }
            });
        });
        
        // Approve transaction
        function approveTransaction(transactionId) {
            Swal.fire({
                title: 'Approve Transaction?',
                text: 'This will mark the transaction as completed and update fund balances.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Approve',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#059669',
                cancelButtonColor: '#6b7280'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Show loading
                    Swal.fire({
                        title: 'Processing...',
                        text: 'Approving transaction',
                        icon: 'info',
                        allowOutsideClick: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    
                    // Send AJAX request to approve transaction
                    $.post('ajax/approve_transaction.php', {
                        transaction_id: transactionId
                    }, function(response) {
                        if (response.success) {
                            Swal.fire({
                                title: 'Success!',
                                text: 'Transaction approved successfully.',
                                icon: 'success',
                                confirmButtonColor: '#059669'
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                title: 'Error!',
                                text: response.message || 'Failed to approve transaction.',
                                icon: 'error',
                                confirmButtonColor: '#dc2626'
                            });
                        }
                    }).fail(function() {
                        Swal.fire({
                            title: 'Error!',
                            text: 'Failed to communicate with server.',
                            icon: 'error',
                            confirmButtonColor: '#dc2626'
                        });
                    });
                }
            });
        }
        
        // Cancel transaction
        function cancelTransaction(transactionId) {
            Swal.fire({
                title: 'Cancel Transaction?',
                text: 'This action cannot be undone. The transaction will be marked as cancelled.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Cancel Transaction',
                cancelButtonText: 'No, Keep Transaction',
                confirmButtonColor: '#dc2626',
                cancelButtonColor: '#6b7280'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Show loading
                    Swal.fire({
                        title: 'Processing...',
                        text: 'Cancelling transaction',
                        icon: 'info',
                        allowOutsideClick: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    
                    // Send AJAX request to cancel transaction
                    $.post('ajax/cancel_transaction.php', {
                        transaction_id: transactionId
                    }, function(response) {
                        if (response.success) {
                            Swal.fire({
                                title: 'Cancelled!',
                                text: 'Transaction has been cancelled.',
                                icon: 'success',
                                confirmButtonColor: '#059669'
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                title: 'Error!',
                                text: response.message || 'Failed to cancel transaction.',
                                icon: 'error',
                                confirmButtonColor: '#dc2626'
                            });
                        }
                    }).fail(function() {
                        Swal.fire({
                            title: 'Error!',
                            text: 'Failed to communicate with server.',
                            icon: 'error',
                            confirmButtonColor: '#dc2626'
                        });
                    });
                }
            });
        }
        
        // Export transactions
        function exportTransactions() {
            Swal.fire({
                title: 'Export Transactions',
                text: 'Choose export format:',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Export as CSV',
                cancelButtonText: 'Export as PDF',
                confirmButtonColor: '#059669',
                cancelButtonColor: '#3b82f6'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Export as CSV
                    window.open('export_transactions.php?format=csv&' + window.location.search.substring(1), '_blank');
                } else if (result.dismiss === Swal.DismissReason.cancel) {
                    // Export as PDF
                    window.open('export_transactions.php?format=pdf&' + window.location.search.substring(1), '_blank');
                }
            });
        }
    </script>

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

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