<?php
$pageTitle = 'Finance Dashboard';
include 'includes/header.php';

// --- Auth Check ---
$current_role = $_SESSION['user_role'] ?? $_SESSION['admin_user_role'] ?? '';
if (!in_array($current_role, ['admin', 'super_admin', 'finance_manager'])) {
    header('Location: dashboard.php');
    exit();
}

$walletModel = new Wallet();
$settingModel = new Setting();
$user_role = $current_role;

// --- Fetch Stats ---
$db = new Database();

// 1. Pending Withdrawals Count (Optimized)
$db->query("
    SELECT COUNT(*) as count
    FROM wallet_transactions wt 
    WHERE wt.type = 'withdrawal' 
    AND (wt.status IN ('pending', 'pending_finance') OR wt.status IS NULL OR wt.status = '')
");
$pending_count = $db->single()->count;

// 2. Recent Pending Withdrawals for Widget (Limit 5)
$db->query("
    SELECT wt.*, w.entity_type, w.entity_id, u.first_name, u.last_name, u.email as user_email, c.name as club_name
    FROM wallet_transactions wt 
    JOIN wallets w ON wt.wallet_id = w.id 
    LEFT JOIN users u ON (w.entity_type = 'user' AND w.entity_id = u.id)
    LEFT JOIN clubs c ON (w.entity_type = 'club' AND w.entity_id = c.id)
    WHERE wt.type = 'withdrawal' 
    AND (wt.status IN ('pending', 'pending_finance') OR wt.status IS NULL OR wt.status = '')
    ORDER BY wt.created_at DESC
    LIMIT 5
");
$pending_withdrawals = $db->resultSet();

// Total Site Commission
$db->query("
    SELECT SUM(amount) as total 
    FROM wallet_transactions wt
    JOIN wallets w ON wt.wallet_id = w.id
    WHERE w.entity_type = 'site' AND wt.type = 'deposit'
");
$site_comm_res = $db->single();
$total_site_commission = $site_comm_res->total ?? 0;

// Current Site Wallet Balance
$db->query("SELECT balance FROM wallets WHERE entity_type = 'site' LIMIT 1");
$site_wallet_res = $db->single();
$site_wallet_balance = $site_wallet_res->balance ?? 0;

// Total Board Commission
$db->query("
    SELECT SUM(amount) as total 
    FROM wallet_transactions wt
    JOIN wallets w ON wt.wallet_id = w.id
    WHERE w.entity_type = 'board' AND wt.type = 'deposit'
");
$board_comm_res = $db->single();
$total_board_commission = $board_comm_res->total ?? 0;

// Current Board Wallet Balance
$db->query("SELECT balance FROM wallets WHERE entity_type = 'board' LIMIT 1");
$board_wallet_res = $db->single();
$board_wallet_balance = $board_wallet_res->balance ?? 0;

// Total Circulating Funds (User & Club Wallets)
$db->query("SELECT SUM(balance) as total FROM wallets WHERE entity_type IN ('user', 'club')");
$circulating_funds_res = $db->single();
$total_circulating_funds = $circulating_funds_res->total ?? 0;

// Get currency symbol
$settings = $settingModel->getAll();
$currency_symbol = ($settings['system_currency'] ?? 'USD') === 'ZMW' ? 'K' : '$';

include 'includes/sidebar.php';
?>

<div class="page-content">
    <div class="matches-header">
        <h1>Finance Dashboard</h1>
    </div>

    <!-- Stats Grid -->
    <div class="dashboard-section">
        <div class="stats-card-grid">
            <div class="stat-card">
                <div class="stat-value" style="color: #e67e22;"><?php echo $pending_count; ?></div>
                <div class="stat-label">Pending Approvals</div>
                <a href="withdrawal_requests.php" class="btn-sm btn-outline" style="margin-top: 10px; display: inline-block;">View Requests</a>
            </div>
            <div class="stat-card">
                <div class="stat-value" style="color: #2ecc71;"><?php echo $currency_symbol . number_format($total_site_commission, 2); ?></div>
                <div class="stat-label">Total Site Commission (Lifetime)</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" style="color: #27ae60;"><?php echo $currency_symbol . number_format($site_wallet_balance, 2); ?></div>
                <div class="stat-label">Current Site Balance</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" style="color: #3498db;"><?php echo $currency_symbol . number_format($total_board_commission, 2); ?></div>
                <div class="stat-label">Total Board Commission (Lifetime)</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" style="color: #2980b9;"><?php echo $currency_symbol . number_format($board_wallet_balance, 2); ?></div>
                <div class="stat-label">Current Board Balance</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php echo $currency_symbol . number_format($total_circulating_funds, 2); ?></div>
                <div class="stat-label">Total Circulating Funds</div>
                <a href="wallet_management.php" class="btn-sm btn-outline" style="margin-top: 10px; display: inline-block;">Manage Wallets</a>
            </div>
        </div>
    </div>

    <!-- Pending Approvals Widget -->
    <div class="dashboard-section">
        <div class="section-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <h2 class="dashboard-title" style="margin: 0;">Pending Withdrawals</h2>
            <a href="withdrawal_requests.php" class="btn-sm">View All</a>
        </div>
        
        <div class="table-wrapper">
            <table class="styled-table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>User / Entity</th>
                        <th>Amount</th>
                        <th>Stage</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($pending_withdrawals)): ?>
                        <tr><td colspan="5" style="text-align:center;">No pending requests for your approval.</td></tr>
                    <?php else: ?>
                        <?php foreach ($pending_withdrawals as $r): ?>
                            <tr>
                                <td><?php echo date('d M, H:i', strtotime($r->created_at)); ?></td>
                                <td>
                                    <?php 
                                    if ($r->entity_type === 'user') {
                                        echo htmlspecialchars($r->first_name . ' ' . $r->last_name);
                                        echo '<br><small style="color:#777;">' . htmlspecialchars($r->user_email) . '</small>';
                                    } elseif ($r->entity_type === 'club') {
                                        echo htmlspecialchars($r->club_name);
                                    } else {
                                        echo ucfirst($r->entity_type) . ' #' . $r->entity_id;
                                    }
                                    ?>
                                </td>
                                <td><strong><?php echo $currency_symbol . number_format($r->amount, 2); ?></strong></td>
                                <td>
                                    <?php 
                                        $display_status = $r->status ?: 'Pending';
                                        if (in_array($r->status, ['pending', 'pending_finance']) || empty($r->status)) {
                                            $display_status = 'Pending Approval';
                                        }
                                    ?>
                                    <span class="badge badge-warning"><?php echo htmlspecialchars($display_status); ?></span>
                                </td>
                                <td><a href="withdrawal_requests.php" class="btn-sm btn-primary">Review</a></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Quick Links -->
    <div class="dashboard-section">
        <h2 class="dashboard-title">Quick Actions</h2>
        <div class="quick-actions-list" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
            <a href="financial_reports.php" class="action-item">
                <i class="fa-solid fa-chart-line"></i> <span>Financial Reports</span>
            </a>
            <a href="wallet_transactions.php" class="action-item">
                <i class="fa-solid fa-list"></i> <span>Transaction Logs</span>
            </a>
            <a href="wallet_management.php" class="action-item">
                <i class="fa-solid fa-wallet"></i> <span>Wallet Management</span>
            </a>
        </div>
    </div>
</div>

<style>
.stats-card-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}
.stat-card { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); text-align: center; border: 1px solid #eee; }
.stat-value { font-size: 2rem; font-weight: 800; margin-bottom: 5px; }
.stat-label { color: #7f8c8d; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 0.5px; }
.badge-warning { background-color: #ffc107; color: #212529; padding: 4px 8px; border-radius: 4px; font-size: 0.8rem; }
.action-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 8px;
    text-decoration: none;
    color: #333;
    font-weight: 600;
    transition: background-color 0.2s;
    border: 1px solid #eee;
}
.action-item:hover { background-color: #e9ecef; }
.action-item i { color: #3498db; font-size: 1.2rem; }
</style>

<?php include 'includes/footer.php'; ?>