<?php
require_once '../config/config.php';

$isMobile = preg_match('/Mobile|Android|iPhone|iPad|iPod/', $_SERVER['HTTP_USER_AGENT']);
$pageTitle = 'Browse Institutions';

$search = $_GET['search'] ?? '';
$db = getDB();
$where = ["i.status = 'active'"];
$params = [];

if (!empty($search)) {
    $where[] = "(i.name LIKE ? OR i.description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$whereClause = implode(' AND ', $where);

$stmt = $db->prepare("
    SELECT i.*, 
           (SELECT COUNT(*) FROM institution_members WHERE institution_id = i.id) as members_count
    FROM institutions i
    WHERE $whereClause
    ORDER BY i.name
");
$stmt->execute($params);
$institutions = $stmt->fetchAll();

// Include appropriate header based on device
if ($isMobile) {
    include '../templates/mobile-header.php';
} else {
    include '../templates/header.php';
}
?>

<div class="container my-5">
    <h2 class="mb-4"><i class="fas fa-university"></i> Browse Institutions</h2>
    
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-8">
                    <input type="text" class="form-control" name="search" value="<?php echo e($search); ?>" placeholder="Search institutions...">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100"><i class="fas fa-search"></i> Search</button>
                </div>
                <div class="col-md-2">
                    <a href="institutions.php" class="btn btn-outline-secondary w-100"><i class="fas fa-redo"></i> Reset</a>
                </div>
            </form>
        </div>
    </div>
    
    <p class="text-muted mb-4">Found <?php echo count($institutions); ?> institutions</p>
    
    <div class="row g-4">
        <?php foreach ($institutions as $inst): ?>
        <div class="col-md-6 col-lg-4">
            <div class="card h-100 shadow-sm">
                <div class="card-body">
                    <h5 class="card-title"><?php echo e($inst['name']); ?></h5>
                    <p class="text-muted small"><i class="fas fa-map-marker-alt"></i> <?php echo e($inst['country']); ?></p>
                    <?php if ($inst['description']): ?>
                        <p class="card-text small"><?php echo e(substr($inst['description'], 0, 100)); ?>...</p>
                    <?php endif; ?>
                    <p class="mb-0"><strong><?php echo $inst['members_count']; ?></strong> members</p>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<?php // Include appropriate footer based on device
if ($isMobile) {
    include '../templates/mobile-footer.php';
} else {
    include '../templates/footer.php';
} ?>
