<?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'] ?? '';
$category_filter = $_GET['category_filter'] ?? '';
$status_filter = $_GET['status_filter'] ?? '';
$manager_filter = $_GET['manager_filter'] ?? '';
$page = $_GET['page'] ?? 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Build query with filters
$where_conditions = array("f.is_active = 1");
$params = array();
$param_types = "";

if (!empty($search)) {
    $where_conditions[] = "(f.fund_name LIKE ? OR f.fund_code LIKE ? OR f.description LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param]);
    $param_types .= "sss";
}

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

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

if (!empty($manager_filter)) {
    $where_conditions[] = "f.fund_manager = ?";
    $params[] = $manager_filter;
    $param_types .= "i";
}

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

// Get total count for pagination
$count_query = "SELECT COUNT(*) as total FROM funds f 
                LEFT JOIN fund_categories fc ON f.category_id = fc.category_id 
                LEFT JOIN users u ON f.fund_manager = 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_funds = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_funds / $limit);

// Get funds with pagination
$query = "SELECT f.*, fc.category_name, fc.color_code, u.full_name as manager_name,
                 (SELECT COUNT(*) FROM fund_transactions ft WHERE ft.fund_id = f.fund_id) as total_transactions,
                 (SELECT COUNT(DISTINCT ft.contributor_id) FROM fund_transactions ft WHERE ft.fund_id = f.fund_id) as total_contributors
          FROM funds f 
          LEFT JOIN fund_categories fc ON f.category_id = fc.category_id 
          LEFT JOIN users u ON f.fund_manager = u.user_id 
          WHERE $where_clause
          ORDER BY f.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();
$funds = $stmt->get_result();

// Get fund categories for filter dropdown
$categories_query = "SELECT category_id, category_name FROM fund_categories WHERE is_active = 1 ORDER BY category_name";
$categories_result = $conn->query($categories_query);

// Get fund managers for filter dropdown
$managers_query = "SELECT u.user_id, u.full_name FROM users u 
                   INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                   WHERE ur.role_name IN ('Administrator', 'Fund Manager') AND u.status = 'ACTIVE' 
                   ORDER BY u.full_name";
$managers_result = $conn->query($managers_query);

// Get fund statistics
$stats_query = "SELECT 
    COUNT(*) as total_funds,
    SUM(CASE WHEN status = 'ACTIVE' THEN 1 ELSE 0 END) as active_funds,
    SUM(current_balance) as total_balance,
    SUM(total_contributions) as total_contributions,
    SUM(total_withdrawals) as total_withdrawals
    FROM funds 
    WHERE is_active = 1";
$stats = $conn->query($stats_query)->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'All Funds - 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">
    
    <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;
        }
        
        .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;
        }
        
        /* 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-active { background: #dcfce7; color: #166534; }
        .status-closed { background: #fee2e2; color: #991b1b; }
        .status-suspended { background: #fef3c7; color: #92400e; }
        .status-completed { background: #ddd6fe; color: #5b21b6; }
        
        /* Category Badges */
        .category-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
            color: white;
        }
        
        /* 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; }
        
        /* Fund Progress Bar */
        .fund-progress {
            background: #f1f5f9;
            border-radius: 4px;
            height: 8px;
            overflow: hidden;
            margin-top: 0.5rem;
        }
        
        .fund-progress-bar {
            height: 100%;
            background: #059669;
            transition: width 0.3s ease;
        }
        
        /* 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;
        }
        
        /* Fund Avatar */
        .fund-avatar {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .table-header {
                flex-direction: column;
                gap: 1rem;
                align-items: stretch;
            }
            
            .data-table {
                font-size: 0.75rem;
            }
            
            .data-table th,
            .data-table td {
                padding: 0.5rem;
            }
        }
        
        /* 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 Administration</h1>
                        <p class="page-subtitle">Manage and monitor all funds in the system</p>
                    </div>

                    <!-- Stats Row -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['total_funds'] ?? 0; ?></div>
                            <div class="stat-label">Total Funds</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['active_funds'] ?? 0; ?></div>
                            <div class="stat-label">Active Funds</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['total_balance'] ?? 0); ?></div>
                            <div class="stat-label">Total Balance</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['total_contributions'] ?? 0); ?></div>
                            <div class="stat-label">Total Contributions</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 fund name, code...">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Category</label>
                                <select class="form-select" name="category_filter">
                                    <option value="">All Categories</option>
                                    <?php while ($category = $categories_result->fetch_assoc()): ?>
                                        <option value="<?php echo $category['category_id']; ?>" <?php echo $category_filter == $category['category_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($category['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="ACTIVE" <?php echo $status_filter == 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                    <option value="CLOSED" <?php echo $status_filter == 'CLOSED' ? 'selected' : ''; ?>>Closed</option>
                                    <option value="SUSPENDED" <?php echo $status_filter == 'SUSPENDED' ? 'selected' : ''; ?>>Suspended</option>
                                    <option value="COMPLETED" <?php echo $status_filter == 'COMPLETED' ? 'selected' : ''; ?>>Completed</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Fund Manager</label>
                                <select class="form-select" name="manager_filter">
                                    <option value="">All Managers</option>
                                    <?php while ($manager = $managers_result->fetch_assoc()): ?>
                                        <option value="<?php echo $manager['user_id']; ?>" <?php echo $manager_filter == $manager['user_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($manager['full_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </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_funds.php" class="btn btn-outline-secondary">Clear</a>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Funds Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Funds List (<?php echo $total_funds; ?> total)</h3>
                            <div class="d-flex gap-2">
                                <a href="create_fund.php" class="btn btn-success">
                                    <i class="ph-plus me-1"></i> Create Fund
                                </a>
                                <a href="fund_categories.php" class="btn btn-primary">
                                    <i class="ph-folder me-1"></i> Categories
                                </a>
                            </div>
                        </div>
                        
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Fund Details</th>
                                    <th>Category</th>
                                    <th>Fund Manager</th>
                                    <th>Financial Overview</th>
                                    <th>Progress</th>
                                    <th>Contributors</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($fund = $funds->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="fund-avatar me-3" style="background-color: <?php echo $fund['color_code'] ?? '#3b82f6'; ?>;">
                                                <?php echo strtoupper(substr($fund['fund_name'], 0, 2)); ?>
                                            </div>
                                            <div>
                                                <div style="font-weight: 600; color: #1e293b;">
                                                    <?php echo htmlspecialchars($fund['fund_name']); ?>
                                                </div>
                                                <div style="color: #64748b; font-size: 0.75rem;">
                                                    <?php echo htmlspecialchars($fund['fund_code']); ?>
                                                </div>
                                                <?php if ($fund['description']): ?>
                                                    <div style="color: #64748b; font-size: 0.75rem;">
                                                        <?php echo htmlspecialchars(substr($fund['description'], 0, 50)) . (strlen($fund['description']) > 50 ? '...' : ''); ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="category-badge" style="background-color: <?php echo $fund['color_code'] ?? '#3b82f6'; ?>;">
                                            <?php echo htmlspecialchars($fund['category_name']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div style="font-weight: 500; color: #1e293b;">
                                            <?php echo htmlspecialchars($fund['manager_name'] ?? 'No Manager'); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="font-weight: 600; color: #1e293b;">
                                            Balance: KES <?php echo number_format($fund['current_balance']); ?>
                                        </div>
                                        <div style="color: #059669; font-size: 0.75rem;">
                                            Contributions: KES <?php echo number_format($fund['total_contributions']); ?>
                                        </div>
                                        <div style="color: #dc2626; font-size: 0.75rem;">
                                            Withdrawals: KES <?php echo number_format($fund['total_withdrawals']); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <?php if ($fund['target_amount'] > 0): ?>
                                            <?php $progress = ($fund['current_balance'] / $fund['target_amount']) * 100; ?>
                                            <div style="font-size: 0.75rem; color: #64748b; margin-bottom: 0.25rem;">
                                                <?php echo number_format($progress, 1); ?>% of Target
                                            </div>
                                            <div class="fund-progress">
                                                <div class="fund-progress-bar" style="width: <?php echo min($progress, 100); ?>%;"></div>
                                            </div>
                                            <div style="font-size: 0.75rem; color: #64748b; margin-top: 0.25rem;">
                                                Target: KES <?php echo number_format($fund['target_amount']); ?>
                                            </div>
                                        <?php else: ?>
                                            <span style="color: #64748b; font-size: 0.75rem;">No Target Set</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div style="font-weight: 600; color: #1e293b;">
                                            <?php echo $fund['total_contributors']; ?> Contributors
                                        </div>
                                        <div style="color: #64748b; font-size: 0.75rem;">
                                            <?php echo $fund['total_transactions']; ?> Transactions
                                        </div>
                                    </td>
                                    <td>
                                        <?php 
                                        $status_class = match($fund['status']) {
                                            'ACTIVE' => 'status-active',
                                            'CLOSED' => 'status-closed',
                                            'SUSPENDED' => 'status-suspended',
                                            'COMPLETED' => 'status-completed',
                                            default => 'status-active'
                                        };
                                        ?>
                                        <span class="status-badge <?php echo $status_class; ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', strtolower($fund['status']))); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="d-flex gap-1">
                                            <a href="list_contributors.php" class="btn-action btn-primary" title="View Details">
                                                <i class="ph-eye"></i>
                                            </a>
                                            <a href="edit_fund.php?id=<?php echo $fund['fund_id']; ?>" class="btn-action btn-warning" title="Edit Fund">
                                                <i class="ph-pencil"></i>
                                            </a>
                                            <a href="fund_transactions.php?fund_id=<?php echo $fund['fund_id']; ?>" class="btn-action btn-success" title="View Transactions">
                                                <i class="ph-list"></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_funds); ?> of <?php echo $total_funds; ?> 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); ?>&category_filter=<?php echo $category_filter; ?>&status_filter=<?php echo $status_filter; ?>&manager_filter=<?php echo $manager_filter; ?>" 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); ?>&category_filter=<?php echo $category_filter; ?>&status_filter=<?php echo $status_filter; ?>&manager_filter=<?php echo $manager_filter; ?>" 
                                           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); ?>&category_filter=<?php echo $category_filter; ?>&status_filter=<?php echo $status_filter; ?>&manager_filter=<?php echo $manager_filter; ?>" 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(); ?>