<?php
/**
 * IBVTE Admin - Manage Colleges & Institutions
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

if (!checkDBConnection()) exit;
Auth()->requireRole(['super_admin', 'admin']);

$db = DB();
$flash = getFlashMessage();
$action = $_GET['action'] ?? 'list';

// Handle login-as-college (Admin impersonation)
if ($action === 'login_as' && isset($_GET['id'])) {
    // CSRF Protection
    if (!Auth()->verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        redirectWithMessage('colleges.php', 'Security session expired. Please try again.', 'danger');
    }

    $collegeId = intval($_GET['id']);
    $college = $db->fetchOne("SELECT username FROM users WHERE id = ?", [$collegeId]);
    
    if ($college) {
        $token = Auth()->generateImpersonationToken($collegeId);
        $loginUrl = APP_URL . "college/login.php?action=impersonate&user=" . urlencode($college['username']) . "&itoken=" . urlencode($token);
        header("Location: $loginUrl");
        exit;
    } else {
        redirectWithMessage('colleges.php', 'College not found.', 'danger');
    }
}

// Handle Actions (Approve/Reject/Suspend)
if (isset($_GET['id']) && in_array($action, ['approve', 'reject', 'suspend'])) {
    // CSRF Protection
    if (!Auth()->verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        redirectWithMessage('colleges.php', 'Security session expired. Please try again.', 'danger');
    }

    $status = '';
    if ($action === 'approve') $status = 'approved';
    if ($action === 'reject')  $status = 'rejected';
    if ($action === 'suspend') $status = 'suspended';
    if ($status) {
        $db->update('users', ['affiliation_status' => $status], ['id' => $_GET['id']]);
        redirectWithMessage('colleges.php', "College affiliation status updated to $status.", 'success');
    }
}

// Fetch Colleges
// role_id = 3 is College according to our roles table
$colleges = $db->fetchAll("
    SELECT u.*, w.balance 
    FROM users u 
    LEFT JOIN wallets w ON u.id = w.user_id 
    WHERE u.role_id = 3 
    ORDER BY u.created_at DESC
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Colleges - <?= APP_SHORT_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/admin-style.css" rel="stylesheet">
</head>
<body>
    <?php include __DIR__ . '/../includes/admin_header.php'; ?>
    <div class="container-fluid">
        <div class="row">
            <?php include __DIR__ . '/../includes/admin_sidebar.php'; ?>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2 class="h3"><i class="fas fa-university me-2 text-primary"></i>Affiliated Colleges</h2>
                    <a href="wallet.php" class="btn btn-outline-primary"><i class="fas fa-wallet me-1"></i> Manage Wallets</a>
                </div>

                <?php if ($flash): ?>
                    <div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show shadow-sm">
                        <?= htmlspecialchars($flash['message']) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <div class="card shadow-sm border-0" style="border-radius:15px;">
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead class="bg-light">
                                    <tr>
                                        <th class="ps-4">Institution Details</th>
                                        <th>Code & Reg No.</th>
                                        <th>Contact Person</th>
                                        <th>Wallet Balance</th>
                                        <th>Affiliation Status</th>
                                        <th>Login</th>
                                        <th class="text-end pe-4">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if(empty($colleges)): ?>
                                        <tr><td colspan="7" class="text-center py-5 text-muted">No affiliated colleges found.</td></tr>
                                    <?php endif; ?>
                                    <?php foreach ($colleges as $c): ?>
                                    <tr>
                                        <td class="ps-4">
                                            <div class="fw-bold text-primary"><?= htmlspecialchars($c['institution_name'] ?? 'Pending Name') ?></div>
                                            <div class="small text-muted mt-1"><i class="fas fa-map-marker-alt me-1"></i> <?= htmlspecialchars($c['city'] . ', ' . $c['state']) ?></div>
                                        </td>
                                        <td>
                                            <span class="badge bg-secondary mb-1"><?= htmlspecialchars($c['institution_code'] ?? 'N/A') ?></span><br>
                                            <small class="text-muted">Reg: <?= htmlspecialchars($c['registration_number'] ?? 'N/A') ?></small>
                                        </td>
                                        <td>
                                            <div class="fw-bold"><?= htmlspecialchars($c['full_name']) ?></div>
                                            <div class="small text-muted"><?= htmlspecialchars($c['mobile'] ?? '') ?></div>
                                            <div class="small text-muted"><?= htmlspecialchars($c['email'] ?? '') ?></div>
                                        </td>
                                        <td>
                                            <div class="fw-bold text-success fs-6">₹<?= number_format($c['balance'] ?? 0, 2) ?></div>
                                        </td>
                                        <td>
                                            <?php 
                                            $status = $c['affiliation_status'] ?? 'pending';
                                            $badge = 'bg-warning text-dark';
                                            if ($status === 'approved') $badge = 'bg-success';
                                            if ($status === 'rejected') $badge = 'bg-danger';
                                            if ($status === 'suspended') $badge = 'bg-secondary';
                                            ?>
                                            <span class="badge <?= $badge ?>"><?= ucfirst($status) ?></span>
                                            <?php if ($c['affiliation_valid_until']): ?>
                                                <div class="small text-muted mt-1">Valid till: <?= date('M Y', strtotime($c['affiliation_valid_until'])) ?></div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <a href="?action=login_as&id=<?= $c['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>" 
                                               class="btn btn-sm btn-outline-primary"
                                               onclick="return confirm('Login as this college?')">
                                                <i class="fas fa-sign-in-alt me-1"></i>Login As
                                            </a>
                                        </td>
                                        <td class="text-end pe-4">
                                            <div class="dropdown">
                                                <button class="btn btn-sm btn-light border dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                                    Action
                                                </button>
                                                <ul class="dropdown-menu dropdown-menu-end shadow border-0">
                                                    <li><a class="dropdown-item text-success" href="?action=approve&id=<?= $c['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>"><i class="fas fa-check-circle me-2"></i> Approve Affiliation</a></li>
                                                    <li><a class="dropdown-item text-warning" href="?action=suspend&id=<?= $c['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>"><i class="fas fa-pause-circle me-2"></i> Suspend</a></li>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li><a class="dropdown-item text-danger" href="?action=reject&id=<?= $c['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>"><i class="fas fa-times-circle me-2"></i> Reject / Cancel</a></li>
                                                </ul>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>