<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

// Get universities with filtering
$country_filter = $_GET['country'] ?? '';
$search = $_GET['search'] ?? '';

$sql = "SELECT u.*, c.name as country_name, c.code as country_code FROM universities u JOIN countries c ON u.country_id = c.id";
$conditions = [];
$params = [];

if ($country_filter) {
    $conditions[] = "u.country_id = ?";
    $params[] = $country_filter;
}

if ($search) {
    $conditions[] = "(u.name LIKE ? OR c.name LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($conditions) {
    $sql .= " WHERE " . implode(" AND ", $conditions);
}

$sql .= " ORDER BY c.name, u.name";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$universities = $stmt->fetchAll();

// Get countries for filter
$countries = $pdo->query("SELECT id, name FROM countries ORDER BY name")->fetchAll();

// Get stats
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM universities")->fetchColumn(),
    'by_country' => $pdo->query("SELECT c.name, COUNT(*) as count FROM universities u JOIN countries c ON u.country_id = c.id GROUP BY c.id, c.name ORDER BY count DESC LIMIT 5")->fetchAll(),
];

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Universities - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .stat-card {
            border-left: 5px solid #3fb7fe;
            margin-bottom: 20px;
        }
        .university-logo {
            height: 60px;
            object-fit: contain;
            background: white;
            padding: 5px;
            border-radius: 5px;
        }
        .partner-badge {
            font-size: 0.8em;
            padding: 3px 8px;
            border-radius: 15px;
        }
        .partner-basic {
            background: #f8f9fa;
            color: #6c757d;
        }
        .partner-preferred {
            background: #fff3cd;
            color: #856404;
        }
        .partner-premium {
            background: #d1ecf1;
            color: #0c5460;
        }
    </style>
</head>
<body>

<?php include 'admin-navbar.php'; ?>

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Academic Management</h6>
        <h1 class="display-5">Manage Universities</h1>
    </div>

    <!-- Search and Filter -->
    <div class="row mb-4">
        <div class="col-lg-8">
            <form method="GET" class="d-flex">
                <div class="flex-grow-1 mr-2">
                    <input type="text" name="search" class="form-control" placeholder="Search universities by name or country" 
                           value="<?= htmlspecialchars($search) ?>">
                </div>
                <button type="submit" class="btn btn-primary">Search</button>
            </form>
        </div>
        <div class="col-lg-4">
            <select name="country" class="form-control" onchange="window.location='admin-universities.php?country='+this.value<?= $search ? '&search='.urlencode($search) : '' ?>">
                <option value="">All Countries</option>
                <?php foreach ($countries as $c): ?>
                <option value="<?= $c['id'] ?>" <?= $country_filter == $c['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($c['name']) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="stat-card">
                <div class="card-body">
                    <h6>Total Universities</h6>
                    <h3><?= $stats['total'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-9">
            <div class="bg-light p-4 rounded">
                <h6><i class="fas fa-globe"></i> Top Countries by University Count</h6>
                <div class="row mt-3">
                    <?php foreach ($stats['by_country'] as $country): ?>
                    <div class="col-md-3 mb-2">
                        <div class="text-center">
                            <strong><?= htmlspecialchars($country['name']) ?></strong>
                            <div><?= $country['count'] ?> universities</div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Universities Table -->
    <div class="table-responsive">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>University</th>
                    <th>Country</th>
                    <th>City</th>
                    <th>Ranking</th>
                    <th>Partnership</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($universities as $u): ?>
                <tr>
                    <td>
                        <div class="d-flex align-items-center">
                            <img src="<?= htmlspecialchars($u['logo'] ?: 'img/university-placeholder.png') ?>" 
                                 alt="<?= htmlspecialchars($u['name']) ?>" class="university-logo mr-2">
                            <?= htmlspecialchars($u['name']) ?>
                        </div>
                    </td>
                    <td><?= htmlspecialchars($u['country_name']) ?></td>
                    <td><?= htmlspecialchars($u['city'] ?? 'Not specified') ?></td>
                    <td><?= $u['ranking'] ? '#' . $u['ranking'] : 'Not ranked' ?></td>
                    <td>
                        <span class="partner-badge partner-<?= strtolower($u['partnership_level'] ?: 'basic') ?>">
                            <?= ucfirst($u['partnership_level'] ?: 'Basic') ?>
                        </span>
                    </td>
                    <td>
                        <div class="btn-group">
                            <a href="admin-university-profile.php?id=<?= $u['id'] ?>" class="btn btn-sm btn-primary">View</a>
                            <a href="<?= htmlspecialchars($u['website'] ?: '#') ?>" class="btn btn-sm btn-outline-primary" target="_blank">Website</a>
                            <button class="btn btn-sm btn-danger delete-university" data-id="<?= $u['id'] ?>">Delete</button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
    $('.delete-university').on('click', function() {
        const universityId = $(this).data('id');
        if (confirm('Are you sure you want to delete this university? This action cannot be undone.')) {
            alert('In a real application, this would delete the university from the database.');
        }
    });
</script>
</body>
</html>