<?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());
}

// Get filters
$country_filter = $_GET['country'] ?? '';
$field_filter = $_GET['field'] ?? '';
$search = $_GET['search'] ?? '';

// Build query - Updated to include both logo and banner_image
$sql = "SELECT u.*, c.name as country_name, 
        COUNT(p.id) as program_count
        FROM universities u
        JOIN countries c ON u.country_id = c.id
        LEFT JOIN programs p ON u.id = p.university_id";

$conditions = [];
$params = [];

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

if ($field_filter) {
    // This would require a more complex query with program filtering
    // For now, we'll just filter by search
    $conditions[] = "(p.name LIKE ? OR u.name LIKE ?)";
    $params[] = "%$field_filter%";
    $params[] = "%$field_filter%";
}

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

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

$sql .= " GROUP BY u.id ORDER BY u.partnership_level DESC, u.ranking ASC, 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 popular fields (based on program counts)
$field_counts = $pdo->query("SELECT 
    CASE 
        WHEN p.degree_level LIKE '%business%' OR p.name LIKE '%business%' THEN 'Business'
        WHEN p.degree_level LIKE '%engineering%' OR p.name LIKE '%engineering%' THEN 'Engineering'
        WHEN p.degree_level LIKE '%medicine%' OR p.name LIKE '%medicine%' THEN 'Medicine'
        WHEN p.degree_level LIKE '%computer%' OR p.name LIKE '%computer%' OR p.name LIKE '%IT%' THEN 'IT/Computer Science'
        WHEN p.degree_level LIKE '%arts%' OR p.name LIKE '%arts%' OR p.name LIKE '%humanities%' THEN 'Arts & Humanities'
        ELSE 'Other'
    END as field,
    COUNT(*) as count
    FROM programs p
    GROUP BY field
    ORDER BY count DESC
    LIMIT 5")->fetchAll();

// Get stats
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM universities")->fetchColumn(),
    'by_partnership' => $pdo->query("SELECT partnership_level, COUNT(*) as count FROM universities GROUP BY partnership_level")->fetchAll(),
];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Partner 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>
        .university-card {
            transition: all 0.3s;
            border: none;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        .university-card:hover {
            transform: translateY(-10px);
            box-shadow: 0 15px 30px rgba(0,0,0,0.2);
        }
        .university-img {
            height: 180px;
            object-fit: cover;
            width: 100%;
        }
        .university-logo {
            width: 80px;
            height: 80px;
            object-fit: contain;
            position: absolute;
            top: -40px;
            right: 20px;
            background: white;
            border-radius: 50%;
            padding: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .country-flag {
            width: 30px;
            height: 20px;
            object-fit: cover;
            border-radius: 5px;
            margin-right: 10px;
        }
        .program-count {
            font-size: 0.9em;
            color: #6c757d;
        }
        .partner-badge {
            font-size: 0.8em;
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
        }
        .partner-basic {
            background: #f8f9fa;
            color: #6c757d;
        }
        .partner-preferred {
            background: #fff3cd;
            color: #856404;
        }
        .partner-premium {
            background: #d1ecf1;
            color: #0c5460;
        }
        .filter-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
        }
    </style>
</head>
<body>

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

<!-- Header Start -->
<div class="jumbotron jumbotron-fluid page-header" style="margin-bottom: 90px;">
    <div class="container text-center py-5">
        <h1 class="text-white text-uppercase mb-3">Partner Universities</h1>
        <div class="d-inline-flex">
            <p class="m-0 text-white"><a class="text-white" href="index.php">Home</a></p>
            <p class="m-0 text-white px-2">/</p>
            <p class="m-0 text-white">Universities</p>
        </div>
    </div>
</div>
<!-- Header End -->

<!-- Universities Start -->
<div class="container-fluid py-5">
    <div class="container py-5">
        <div class="text-center mb-5">
            <h5 class="text-primary text-uppercase mb-3" style="letter-spacing: 5px;">Our Partners</h5>
            <h1>Partner Universities</h1>
        </div>
        
        <!-- Search and Filter -->
        <div class="filter-section">
            <form method="GET">
                <div class="row">
                    <div class="col-lg-4 mb-2">
                        <div class="form-group">
                            <input type="text" name="search" class="form-control" placeholder="Search universities..." 
                                   value="<?= htmlspecialchars($search) ?>">
                        </div>
                    </div>
                    <div class="col-lg-3 mb-2">
                        <select name="country" class="form-control">
                            <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 class="col-lg-3 mb-2">
                        <select name="field" class="form-control">
                            <option value="">All Fields</option>
                            <?php foreach ($field_counts as $field): ?>
                            <option value="<?= strtolower($field['field']) ?>" <?= $field_filter === strtolower($field['field']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($field['field']) ?> (<?= $field['count'] ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-lg-2 mb-2">
                        <button class="btn btn-primary btn-block">Filter</button>
                    </div>
                </div>
            </form>
        </div>

        <!-- University Cards -->
        <div class="row">
            <?php if (empty($universities)): ?>
            <div class="col-12 text-center">
                <i class="fas fa-university fa-3x text-muted mb-3"></i>
                <h5>No universities found</h5>
                <p class="text-muted">No universities match your search criteria.</p>
            </div>
            <?php else: ?>
            <?php foreach ($universities as $u): ?>
            <div class="col-lg-4 col-md-6">
                <div class="university-card card">
                    <div class="position-relative">
                        <!-- Banner Image (university-img) -->
                        <img class="img-fluid university-img w-100" 
                             src="<?= htmlspecialchars($u['banner_image'] ?: 'img/university-banner-placeholder.jpg') ?>" 
                             alt="<?= htmlspecialchars($u['name']) ?> Banner">
                        <!-- University Logo (university-logo) -->
                        <img class="university-logo" 
                             src="<?= htmlspecialchars($u['logo'] ?: 'img/university-logo-placeholder.png') ?>" 
                             alt="<?= htmlspecialchars($u['name']) ?> Logo">
                    </div>
                    <div class="card-body text-center p-4">
                        <h4 class="card-title mb-2"><?= htmlspecialchars($u['name']) ?></h4>
                        <div class="d-flex justify-content-center align-items-center mb-3">
                            <img src="img/flags/<?= strtolower($u['country_name']) ?>.png" 
                                 alt="<?= htmlspecialchars($u['country_name']) ?>" class="country-flag">
                            <span><?= htmlspecialchars($u['city'] ?? $u['country_name']) ?></span>
                        </div>
                        <div class="d-flex justify-content-center mb-3">
                            <span class="partner-badge partner-<?= strtolower($u['partnership_level'] ?: 'basic') ?>">
                                <?= ucfirst($u['partnership_level'] ?: 'Basic') ?>
                            </span>
                        </div>
                        <p class="card-text"><?= substr(htmlspecialchars($u['description'] ?? ''), 0, 150) ?>...</p>
                        <div class="program-count mb-3">
                            <i class="fas fa-graduation-cap"></i> <?= $u['program_count'] ?> Programs Available
                        </div>
                        <a href="university-profile.php?id=<?= $u['id'] ?>" class="btn btn-primary">View Programs</a>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <!-- Pagination -->
        <?php if (!empty($universities)): ?>
        <div class="row mt-5">
            <div class="col-12">
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-center">
                        <li class="page-item disabled">
                            <a class="page-link" href="#" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                                <span class="sr-only">Previous</span>
                            </a>
                        </li>
                        <li class="page-item active"><a class="page-link" href="#">1</a></li>
                        <li class="page-item"><a class="page-link" href="#">2</a></li>
                        <li class="page-item"><a class="page-link" href="#">3</a></li>
                        <li class="page-item">
                            <a class="page-link" href="#" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                                <span class="sr-only">Next</span>
                            </a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>
<!-- Universities End -->

<!-- Footer Start -->
<div class="container-fluid position-relative overlay-top bg-dark text-white-50 py-5" style="margin-top: 90px;">
    <div class="container mt-5 pt-5">
        <div class="row">
            <div class="col-md-6 mb-5">
                <a href="index.php" class="navbar-brand">
                    <img src="img/jhoverseas.jpg" alt="JV Overseas Logo" style="height: 50px;">
                </a>
                <p class="m-0">JV Overseas Education Uganda is a leading educational consultancy helping students access higher education opportunities worldwide.</p>
            </div>
            <div class="col-md-6 mb-5">
                <h3 class="text-white mb-4">Quick Links</h3>
                <div class="d-flex flex-column justify-content-start">
                    <a class="text-white-50 mb-2" href="index.php"><i class="fa fa-angle-right mr-2"></i>Home</a>
                    <a class="text-white-50 mb-2" href="about.php"><i class="fa fa-angle-right mr-2"></i>About Us</a>
                    <a class="text-white-50 mb-2" href="services.php"><i class="fa fa-angle-right mr-2"></i>Services</a>
                    <a class="text-white-50 mb-2" href="universities.php"><i class="fa fa-angle-right mr-2"></i>Universities</a>
                    <a class="text-white-50 mb-2" href="apply.php"><i class="fa fa-angle-right mr-2"></i>Free Consultation</a>
                    <a class="text-white-50 mb-2" href="contact.php"><i class="fa fa-angle-right mr-2"></i>Contact Us</a>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6 mb-5">
                <h3 class="text-white mb-4">Get In Touch</h3>
                <p class="m-0"><i class="fa fa-map-marker-alt mr-2"></i>Kampala, Uganda</p>
                <p class="m-0"><i class="fa fa-phone-alt mr-2"></i><a href="tel:+256788289235" class="text-white-50">+256 788 289 235</a></p>
                <p class="m-0"><i class="fa fa-envelope mr-2"></i><a href="mailto:info@jvoverseas.com" class="text-white-50">info@jvoverseas.com</a></p>
                <div class="d-flex flex-column justify-content-start">
                    <div class="d-flex align-items-center mt-2">
                        <a class="text-white-50 mr-2" href="#"><i class="fab fa-twitter"></i></a>
                        <a class="text-white-50 mr-2" href="#"><i class="fab fa-facebook-f"></i></a>
                        <a class="text-white-50 mr-2" href="#"><i class="fab fa-linkedin-in"></i></a>
                        <a class="text-white-50 mr-2" href="#"><i class="fab fa-instagram"></i></a>
                    </div>
                </div>
            </div>
            <div class="col-md-6 mb-5">
                <h3 class="text-white mb-4">Newsletter</h3>
                <p>Stay updated with our latest news and education opportunities.</p>
                <form action="newsletter-subscribe.php" method="POST">
                    <div class="form-inline">
                        <div class="input-group">
                            <input type="email" class="form-control" name="email" placeholder="Your Email" required>
                            <div class="input-group-append">
                                <button class="btn btn-primary" type="submit">Subscribe</button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- Footer End -->

<!-- Back to Top -->
<a href="#" class="btn btn-lg btn-primary rounded-0 btn-lg-square back-to-top"><i class="fa fa-angle-double-up"></i></a>

<!-- JavaScript Libraries -->
<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 src="lib/easing/easing.min.js"></script>
<script src="lib/waypoints/waypoints.min.js"></script>
<script src="lib/counterup/counterup.min.js"></script>
<script src="lib/owlcarousel/owl.carousel.min.js"></script>
<script src="mail/jqBootstrapValidation.min.js"></script>
<script src="mail/contact.js"></script>
<script src="js/main.js"></script>

<script>
// Set current year in footer
document.getElementById('year')?.textContent = new Date().getFullYear();
</script>
<!-- Video Modal -->
<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>        
                <!-- 16:9 aspect ratio -->
                <div class="embed-responsive embed-responsive-16by9">
                    <iframe class="embed-responsive-item" src="" id="video" allowscriptaccess="always" allow="autoplay"></iframe>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // Video modal
    $(document).ready(function () {
        var $videoSrc;
        $('.btn-play').click(function () {
            $videoSrc = $(this).data("src");
        });
        console.log($videoSrc);

        $('#videoModal').on('shown.bs.modal', function (e) {
            $("#video").attr('src', $videoSrc + "?autoplay=1&amp;modestbranding=1&amp;showinfo=0");
        })

        $('#videoModal').on('hide.bs.modal', function (e) {
            $("#video").attr('src', $videoSrc);
        })
    });
</script>
</body>
</html>