<?php
require_once '../config/config.php';
requireLogin();
if (!isSuperAdmin() && !isInstitutionAdmin()) redirect(SITE_URL . '/index.php');

$pageTitle = 'Institution Management';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    $action = $_POST['action'] ?? '';
    $instId = isset($_POST['inst_id']) ? (int)$_POST['inst_id'] : 0;
    $db = getDB();
    
    if ($action === 'activate' && $instId) {
        $db->prepare("UPDATE institutions SET status = 'active' WHERE id = ?")->execute([$instId]);
        $success = 'Institution activated.';
    } elseif ($action === 'deactivate' && $instId) {
        $db->prepare("UPDATE institutions SET status = 'inactive' WHERE id = ?")->execute([$instId]);
        $success = 'Institution deactivated.';
    } elseif ($action === 'delete' && $instId) {
        $db->prepare("DELETE FROM institutions WHERE id = ?")->execute([$instId]);
        $success = 'Institution deleted.';
    }
}

$db = getDB();
$stmt = $db->prepare("
    SELECT i.*, u.first_name, u.last_name,
           (SELECT COUNT(*) FROM institution_members WHERE institution_id = i.id) as members_count
    FROM institutions i
    LEFT JOIN users u ON i.admin_user_id = u.id
    ORDER BY i.created_at DESC
");
$stmt->execute();
$institutions = $stmt->fetchAll();

include '../templates/admin-header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar-new.php'; ?>
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <?php include 'header-bar.php'; ?>

            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <div class="card shadow">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Type</th>
                                    <th>Country</th>
                                    <th>Admin</th>
                                    <th>Members</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($institutions as $inst): ?>
                                <tr>
                                    <td><strong><?php echo e($inst['name']); ?></strong></td>
                                    <td><?php echo ucfirst($inst['type']); ?></td>
                                    <td><?php echo e($inst['country']); ?></td>
                                    <td><?php echo $inst['first_name'] ? e($inst['first_name'] . ' ' . $inst['last_name']) : 'N/A'; ?></td>
                                    <td><?php echo $inst['members_count']; ?></td>
                                    <td><span class="badge bg-<?php echo $inst['status'] === 'active' ? 'success' : 'warning'; ?>"><?php echo ucfirst($inst['status']); ?></span></td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <?php if ($inst['status'] !== 'active'): ?>
                                                <form method="POST" style="display:inline;">
                                                    <?php echo csrfField(); ?>
                                                    <input type="hidden" name="action" value="activate">
                                                    <input type="hidden" name="inst_id" value="<?php echo $inst['id']; ?>">
                                                    <button type="submit" class="btn btn-success"><i class="fas fa-check"></i></button>
                                                </form>
                                            <?php else: ?>
                                                <form method="POST" style="display:inline;">
                                                    <?php echo csrfField(); ?>
                                                    <input type="hidden" name="action" value="deactivate">
                                                    <input type="hidden" name="inst_id" value="<?php echo $inst['id']; ?>">
                                                    <button type="submit" class="btn btn-warning"><i class="fas fa-ban"></i></button>
                                                </form>
                                            <?php endif; ?>
                                            <form method="POST" style="display:inline;" onsubmit="return confirm('Delete?')">
                                                <?php echo csrfField(); ?>
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="inst_id" value="<?php echo $inst['id']; ?>">
                                                <button type="submit" class="btn btn-danger"><i class="fas fa-trash"></i></button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<?php include '../templates/admin-footer.php'; ?>
