<?php
$pageTitle = 'Club Registration Payments';
include_once 'includes/header.php';

// --- Admin/Finance 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();
}

$settingModel = new Setting();
$db = new Database();

// Helper function for currency symbol
function get_currency_symbol($code) {
    switch ($code) {
        case 'ZMW': return 'K';
        case 'EUR': return '€';
        case 'GBP': return '£';
        default: return '$';
    }
}

// Get settings
$settings = $settingModel->getAll();
$currency_symbol = get_currency_symbol($settings['system_currency'] ?? 'USD');

// Filter
$filter = $_GET['filter'] ?? 'all';

// Fetch payment data for all clubs
try {
    $db->query("
        SELECT
            c.id as club_id,
            c.name as club_name,
            l.reg_fee_total,
            c.logo as club_logo,
            (SELECT SUM(t.amount)
             FROM wallet_transactions t
             JOIN wallets w ON t.wallet_id = w.id
             WHERE w.entity_type = 'club' AND w.entity_id = c.id AND t.type = 'registration_fee' AND (t.status = 'success' OR t.status = 'completed')
            ) as total_paid
        FROM
            clubs c
        JOIN leagues l ON c.league_id = l.id
        ORDER BY
            c.name ASC
    ");
    $payment_data = $db->resultSet();
} catch (Exception $e) {
    // Fallback if columns are missing (migration not run)
    $db->query("
        SELECT
            c.id as club_id,
            c.name as club_name,
            0 as reg_fee_total,
            c.logo as club_logo,
            (SELECT SUM(t.amount)
             FROM wallet_transactions t
             JOIN wallets w ON t.wallet_id = w.id
             WHERE w.entity_type = 'club' AND w.entity_id = c.id AND t.type = 'registration_fee' AND (t.status = 'success' OR t.status = 'completed')
            ) as total_paid
        FROM
            clubs c
        JOIN leagues l ON c.league_id = l.id
        ORDER BY
            c.name ASC
    ");
    $payment_data = $db->resultSet();
    echo "<div class='message error' style='margin: 20px;'><strong>Database Warning:</strong> The 'leagues' table is missing fee columns. Please run the migration script.</div>";
}

if ($filter === 'unpaid') {
    $payment_data = array_filter($payment_data, function($club) {
        $total_reg_fee = (float)($club->reg_fee_total ?? 0);
        $paid = (float)($club->total_paid ?? 0);
        return $paid < ($total_reg_fee - 0.01);
    });
}

include_once 'includes/sidebar.php';
?>

<h1>Club Registration Payments</h1>

<div class="dashboard-section">
    <div class="section-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; flex-wrap: wrap; gap: 15px;">
        <div style="display: flex; align-items: center; gap: 15px;">
            <h2 class="dashboard-title" style="margin-bottom: 0;">Payment Status Overview</h2>
            <div class="filter-pills">
                <a href="?filter=all" class="filter-pill <?php echo $filter === 'all' ? 'active' : ''; ?>">All</a>
                <a href="?filter=unpaid" class="filter-pill <?php echo $filter === 'unpaid' ? 'active' : ''; ?>">Unpaid Only</a>
            </div>
        </div>
    </div>

        <div class="table-wrapper">
            <table class="styled-table">
                <thead>
                    <tr>
                        <th>Club</th>
                        <th>Amount Paid</th>
                        <th>Amount Remaining</th>
                        <th>Progress</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($payment_data)): ?>
                        <tr><td colspan="5" class="no-data-msg">No clubs found.</td></tr>
                    <?php else: ?>
                        <?php foreach ($payment_data as $club):
                            $total_reg_fee = (float)($club->reg_fee_total ?? 0);
                            $paid = (float)($club->total_paid ?? 0);
                            $remaining = $total_reg_fee - $paid;
                            $percent_paid = ($total_reg_fee > 0) ? ($paid / $total_reg_fee) * 100 : 0;
                            $percent_paid = min(100, $percent_paid);

                            $status_class = 'status-unpaid';
                            $status_text = 'Not Paid';
                            if ($paid >= $total_reg_fee) {
                                $status_class = 'status-paid';
                                $status_text = 'Fully Paid';
                            } elseif ($paid > 0) {
                                $status_class = 'status-partial';
                                $status_text = 'Partially Paid';
                            }
                        ?>
                            <tr>
                                <td class="team-name-cell">
                                    <img src="<?php echo htmlspecialchars($club->club_logo ?? '/smart_football/public/assets/images/default_crest.png'); ?>" alt="" class="table-logo">
                                    <?php echo htmlspecialchars($club->club_name); ?>
                                </td>
                                <td style="color: #27ae60; font-weight: bold;"><?php echo $currency_symbol . number_format($paid, 2); ?></td>
                                <td style="color: #c0392b; font-weight: bold;"><?php echo $currency_symbol . number_format($remaining, 2); ?></td>
                                <td>
                                    <div style="width: 100px; height: 8px; background-color: #e9ecef; border-radius: 4px; display: inline-block; margin-right: 10px;">
                                        <div style="width: <?php echo $percent_paid; ?>%; background-color: <?php echo $percent_paid >= 100 ? '#2ecc71' : '#3498db'; ?>; height: 100%; border-radius: 4px;"></div>
                                    </div>
                                    <span style="font-size: 0.8rem;"><?php echo round($percent_paid); ?>%</span>
                                </td>
                                <td>
                                    <span class="status-badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                </td>
                                <td>
                                    <?php if ($remaining > 0.01): ?>
                                        <form action="manual_finance_process.php" method="POST" onsubmit="return confirm('Are you sure you want to manually mark this registration as fully paid?');">
                                            <input type="hidden" name="action" value="mark_reg_paid">
                                            <input type="hidden" name="club_id" value="<?php echo $club->club_id; ?>">
                                            <button type="submit" class="btn-sm btn-warning">Mark Paid</button>
                                        </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
</div>

<style>
.status-badge { padding: 4px 10px; border-radius: 12px; font-size: 0.75rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; }
.status-paid { background-color: #d4edda; color: #155724; }
.status-partial { background-color: #fff3cd; color: #856404; }
.status-unpaid { background-color: #f8d7da; color: #721c24; }

.filter-pills { display: flex; background: #f1f3f5; padding: 4px; border-radius: 20px; }
.filter-pill { padding: 5px 15px; border-radius: 15px; text-decoration: none; color: #666; font-size: 0.85rem; font-weight: 600; transition: all 0.2s; }
.filter-pill.active { background: #fff; color: #333; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }

.table-logo { width: 30px; height: 30px; object-fit: contain; vertical-align: middle; margin-right: 10px; }
.team-name-cell { display: flex; align-items: center; }
</style>

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