<?php
// Gallery.php - Mumbai University (mum_unu folder)
// Location: college/mum_unu/Gallery.php
// Database Table: mum_gallery (sai7755_college)
// Exact same UI as previous gallery - ONLY DB changes [cite:3][cite:4][cite:6][cite:7]

ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();

// ✅ DIRECT DATABASE CONNECTION - NO EXTERNAL FILES NEEDED
$host = 'localhost';
$dbname = 'sai7755_college';
$username = 'sai7755_college';
$password = 'Admin_66666';  // Update if different

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

// Mumbai University school_id - UPDATE THIS VALUE
$school_id = 3;  // Check: SELECT DISTINCT school_id FROM mum_gallery LIMIT 1; [cite:8]

// Handle AJAX like/view updates
if ($_POST['action'] ?? '') {
    $id = (int)($_POST['id'] ?? 0);
    
    if ($_POST['action'] == 'like') {
        $stmt = $pdo->prepare("UPDATE mum_gallery SET likes = likes + 1 WHERE id = ? AND school_id = ? AND status = 'active'");
        $stmt->execute([$id, $school_id]);
        echo json_encode(['success' => true]);
    } elseif ($_POST['action'] == 'view') {
        $stmt = $pdo->prepare("UPDATE mum_gallery SET views = views + 1 WHERE id = ? AND school_id = ? AND status = 'active'");
        $stmt->execute([$id, $school_id]);
        echo json_encode(['success' => true]);
    }
    exit;
}

// Fetch gallery items - ORDER BY display_order, featured first
$stmt = $pdo->prepare("
    SELECT * FROM mum_gallery 
    WHERE school_id = ? AND status = 'active' 
    ORDER BY featured DESC, display_order ASC, created_at DESC
");
$stmt->execute([$school_id]);
$gallery_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch categories
$stmt = $pdo->prepare("SELECT DISTINCT category FROM mum_gallery WHERE school_id = ? AND category IS NOT NULL AND category != '' ORDER BY category");
$stmt->execute([$school_id]);
$categories = $stmt->fetchAll(PDO::FETCH_COLUMN);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mumbai University Gallery</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        /* SAME EXACT UI - Modern Admin Panel Design */
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #2c3e50; 
            min-height: 100vh;
        }

        /* Sidebar - Fixed Left */
        .sidebar {
            position: fixed; left: 0; top: 0; width: 260px; height: 100vh;
            background: rgba(255,255,255,0.95); backdrop-filter: blur(20px);
            box-shadow: 4px 0 20px rgba(0,0,0,0.1); z-index: 1000;
            padding: 2rem 1.5rem; transition: transform 0.3s ease;
        }
        .logo { font-size: 1.8rem; font-weight: 700; color: #667eea; margin-bottom: 2rem; text-align: center; }
        .nav-item { display: flex; align-items: center; padding: 0.8rem 1rem; margin-bottom: 0.5rem; 
                    border-radius: 12px; cursor: pointer; transition: all 0.3s; color: #64748b; }
        .nav-item i { width: 24px; margin-right: 12px; font-size: 1.1rem; }
        .nav-item:hover, .nav-item.active { background: linear-gradient(135deg, #667eea, #764ba2); color: white; transform: translateX(4px); }

        /* Main Content */
        .main-content { margin-left: 260px; padding: 2rem; min-height: 100vh; }
        .header { 
            background: rgba(255,255,255,0.95); backdrop-filter: blur(20px); 
            padding: 2rem; border-radius: 20px; box-shadow: 0 10px 40px rgba(0,0,0,0.1);
            margin-bottom: 2rem; display: flex; justify-content: space-between; align-items: center;
        }
        .header h1 { font-size: 2.2rem; background: linear-gradient(135deg, #667eea, #764ba2); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }

        /* Stats Cards */
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1.5rem; margin-bottom: 2rem; }
        .stat-card { 
            background: rgba(255,255,255,0.95); backdrop-filter: blur(20px); padding: 1.5rem 2rem; 
            border-radius: 16px; text-align: center; box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            transition: transform 0.3s, box-shadow 0.3s;
        }
        .stat-card:hover { transform: translateY(-8px); box-shadow: 0 20px 40px rgba(0,0,0,0.15); }
        .stat-number { font-size: 2.5rem; font-weight: 700; background: linear-gradient(135deg, #667eea, #764ba2); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
        .stat-label { color: #64748b; font-size: 0.95rem; margin-top: 0.25rem; }

        /* Gallery Grid */
        .gallery-container { 
            background: rgba(255,255,255,0.95); backdrop-filter: blur(20px); 
            padding: 2rem; border-radius: 20px; box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        }
        .gallery-grid { 
            display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); 
            gap: 1.5rem; margin-top: 1.5rem;
        }

        /* Media Cards */
        .media-card { 
            background: white; border-radius: 16px; overflow: hidden; box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); position: relative;
        }
        .media-card:hover { transform: translateY(-12px) scale(1.02); box-shadow: 0 25px 50px rgba(0,0,0,0.2); }
        .media-wrapper { position: relative; height: 220px; overflow: hidden; }
        .media-wrapper img, .media-wrapper video { width: 100%; height: 100%; object-fit: cover; transition: transform 0.4s; }
        .media-card:hover .media-wrapper img { transform: scale(1.1); }
        .media-card:hover .media-wrapper video { transform: scale(1.05); }
        
        .media-badge { position: absolute; top: 12px; left: 12px; background: linear-gradient(135deg, #667eea, #764ba2); color: white; 
                      padding: 0.4rem 0.8rem; border-radius: 20px; font-size: 0.8rem; font-weight: 600; }
        .featured-badge { position: absolute; top: 12px; right: 12px; background: linear-gradient(135deg, #f093fb, #f5576c); 
                         color: white; padding: 0.4rem 0.8rem; border-radius: 20px; font-size: 0.8rem; font-weight: 600; }
        
        .media-info { padding: 1.2rem; }
        .media-title { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.5rem; color: #2c3e50; }
        .media-desc { color: #64748b; font-size: 0.9rem; line-height: 1.4; margin-bottom: 1rem; display: -webkit-box; 
                      -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
        .media-stats { display: flex; justify-content: space-between; align-items: center; }
        .stats { display: flex; align-items: center; gap: 1rem; }
        .stat { display: flex; align-items: center; gap: 0.3rem; color: #64748b; font-size: 0.85rem; }
        .like-btn { background: linear-gradient(135deg, #667eea, #764ba2); color: white; border: none; 
                   padding: 0.5rem 1rem; border-radius: 25px; cursor: pointer; font-weight: 600; 
                   transition: all 0.3s; display: flex; align-items: center; gap: 0.4rem; }
        .like-btn:hover { transform: scale(1.05); box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4); }

        /* Category Filter */
        .category-filter { display: flex; flex-wrap: wrap; gap: 0.8rem; margin-bottom: 1.5rem; }
        .category-btn { 
            background: rgba(102, 126, 234, 0.1); color: #667eea; border: 2px solid rgba(102, 126, 234, 0.3); 
            padding: 0.6rem 1.2rem; border-radius: 25px; cursor: pointer; font-weight: 500; transition: all 0.3s;
        }
        .category-btn:hover, .category-btn.active { background: linear-gradient(135deg, #667eea, #764ba2); color: white; transform: translateY(-2px); }

        /* Responsive */
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); }
            .main-content { margin-left: 0; }
            .header { flex-direction: column; gap: 1rem; text-align: center; }
            .gallery-grid { grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); }
        }

        /* Video Controls */
        .video-controls { position: absolute; bottom: 12px; left: 12px; right: 12px; 
                         background: linear-gradient(transparent, rgba(0,0,0,0.8)); color: white; 
                         padding: 1rem; border-radius: 12px; opacity: 0; transition: opacity 0.3s; }
        .media-card:hover .video-controls { opacity: 1; }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="logo">
            <i class="fas fa-university"></i> Mumbai Uni
        </div>
        <div class="nav-item active">
            <i class="fas fa-images"></i> Gallery
        </div>
        <div class="nav-item">
            <i class="fas fa-plus"></i> Upload Media
        </div>
        <div class="nav-item">
            <i class="fas fa-tags"></i> Categories
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <div class="header">
            <div>
                <h1><i class="fas fa-images"></i> Media Gallery</h1>
                <p>Featured images and videos from Mumbai University</p>
            </div>
        </div>

        <!-- Stats -->
        <?php 
        $total = count($gallery_items);
        $images = count(array_filter($gallery_items, fn($item) => $item['media_type'] == 'image'));
        $videos = $total - $images;
        ?>
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo $total; ?></div>
                <div class="stat-label">Total Media</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $images; ?></div>
                <div class="stat-label">Images</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $videos; ?></div>
                <div class="stat-label">Videos</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo array_sum(array_column($gallery_items, 'views')); ?></div>
                <div class="stat-label">Total Views</div>
            </div>
        </div>

        <!-- Categories & Gallery -->
        <div class="gallery-container">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                <h2 style="color: #2c3e50;"><i class="fas fa-th-large"></i> Gallery</h2>
                <div class="category-filter">
                    <button class="category-btn active" onclick="filterCategory('all')">All</button>
                    <?php foreach($categories as $cat): ?>
                        <button class="category-btn" onclick="filterCategory('<?php echo htmlspecialchars($cat); ?>')">
                            <?php echo htmlspecialchars($cat); ?>
                        </button>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <div class="gallery-grid" id="galleryGrid">
                <?php foreach($gallery_items as $item): ?>
                    <div class="media-card" data-category="<?php echo htmlspecialchars($item['category'] ?? ''); ?>" data-type="<?php echo $item['media_type']; ?>">
                        <div class="media-wrapper">
                            <?php if($item['media_type'] == 'image'): ?>
                                <img src="<?php echo htmlspecialchars($item['file_path']); ?>" 
                                     alt="<?php echo htmlspecialchars($item['title'] ?? ''); ?>" 
                                     loading="lazy" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIwIiBoZWlnaHQ9IjIyMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjBmMGYwIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxNiIgZmlsbD0iIzk5OSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPkltYWdlIE5vdCBGb3VuZDwvdGV4dD48L3N2Zz4='">
                            <?php elseif($item['media_type'] == 'video'): ?>
                                <video poster="<?php echo htmlspecialchars($item['thumbnail'] ?? ''); ?>" muted loop playsinline>
                                    <source src="<?php echo htmlspecialchars($item['file_path']); ?>" type="video/mp4">
                                </video>
                            <?php endif; ?>
                            
                            <div class="media-badge">
                                <i class="fas fa-<?php echo $item['media_type'] == 'image' ? 'image' : 'video'; ?>"></i> 
                                <?php echo ucfirst($item['media_type']); ?>
                            </div>
                            <?php if($item['featured']): ?>
                                <div class="featured-badge"><i class="fas fa-star"></i> Featured</div>
                            <?php endif; ?>
                            
                            <?php if($item['media_type'] == 'video' && $item['duration']): ?>
                                <div class="video-controls">
                                    <span><?php echo htmlspecialchars($item['duration']); ?></span>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="media-info">
                            <div class="media-title"><?php echo htmlspecialchars($item['title'] ?? 'Untitled'); ?></div>
                            <?php if($item['description']): ?>
                                <div class="media-desc"><?php echo htmlspecialchars(substr($item['description'], 0, 120)); ?>...</div>
                            <?php endif; ?>
                            
                            <div class="media-stats">
                                <div class="stats">
                                    <?php if($item['tags']): ?>
                                        <div class="stat">
                                            <i class="fas fa-tags"></i>
                                            <?php echo htmlspecialchars(explode(',', $item['tags'])[0] ?? ''); ?>
                                        </div>
                                    <?php endif; ?>
                                    <div class="stat"><i class="fas fa-eye"></i> <?php echo number_format($item['views']); ?></div>
                                    <div class="stat"><i class="fas fa-heart"></i> <?php echo number_format($item['likes']); ?></div>
                                </div>
                                <button class="like-btn" onclick="likeMedia(<?php echo $item['id']; ?>)">
                                    <i class="fas fa-heart"></i> Like
                                </button>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <?php if(empty($gallery_items)): ?>
                <div style="text-align: center; padding: 4rem; color: #64748b;">
                    <i class="fas fa-images" style="font-size: 4rem; margin-bottom: 1rem; opacity: 0.5;"></i>
                    <h3>No media found</h3>
                    <p>Gallery is empty. Upload some images and videos to get started.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Filter by category
        function filterCategory(category) {
            document.querySelectorAll('.category-btn').forEach(btn => btn.classList.remove('active'));
            event.target.classList.add('active');
            
            document.querySelectorAll('.media-card').forEach(card => {
                if (category === 'all' || card.dataset.category === category) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        }

        // Like media
        function likeMedia(id) {
            fetch('', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'action=like&id=' + id
            }).then(res => res.json()).then(data => {
                if (data.success) {
                    location.reload(); // Refresh to show updated count
                }
            });
        }

        // Auto increment views on load
        document.querySelectorAll('.media-card').forEach(card => {
            card.addEventListener('mouseenter', () => {
                const id = card.querySelector('.like-btn')?.dataset?.id;
                if (id) {
                    fetch('', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: 'action=view&id=' + id
                    });
                }
            });
        });
    </script>
</body>
</html>
