<?php
session_start();
require_once '../../config/database.php';

// Check if user is logged in and has appropriate permissions
if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}

$user_role = $_SESSION['user_role'];
$user_name = $_SESSION['user_name'];

// Only admin and teachers can access this page
if ($user_role != 'admin' && $user_role != 'teacher') {
    header('Location: ../../index.php');
    exit();
}

$success_message = '';
$error_message = '';

// Handle image upload
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload_image'])) {
    try {
        $title = trim($_POST['title']);
        $description = trim($_POST['description']);
        $category = trim($_POST['category']);
        $student_id = !empty($_POST['student_id']) ? intval($_POST['student_id']) : null;
        
        // Handle image upload
        if (!empty($_FILES['image']['name']) && isset($_FILES['image']['error']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $allowed = ['jpg','jpeg','png','gif'];
            $origName = $_FILES['image']['name'];
            $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
            
            if (in_array($ext, $allowed)) {
                // Create upload directory if not exists
                $uploadDir = dirname(__DIR__) . '/../uploads/student_gallery';
                if (!is_dir($uploadDir)) {
                    @mkdir($uploadDir, 0777, true);
                }
                
                // Generate unique filename
                $newName = 'gallery_' . date('Ymd_His') . '_' . substr(sha1(uniqid('', true)), 0, 8) . '.' . $ext;
                $target = $uploadDir . '/' . $newName;
                
                if (@move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
                    // Store relative path in database
                    $image_path = 'uploads/student_gallery/' . $newName;
                    
                    // Insert into database
                    $stmt = $pdo->prepare("
                        INSERT INTO student_gallery (title, description, category, image_path, student_id, uploaded_by, created_at) 
                        VALUES (?, ?, ?, ?, ?, ?, NOW())
                    ");
                    $stmt->execute([$title, $description, $category, $image_path, $student_id, $_SESSION['user_id']]);
                    
                    $success_message = 'ছবি সফলভাবে আপলোড হয়েছে';
                } else {
                    $error_message = 'ছবি আপলোডে সমস্যা';
                }
            } else {
                $error_message = 'শুধুমাত্র JPG, JPEG, PNG, GIF ফাইল অনুমোদিত';
            }
        } else {
            $error_message = 'ছবি নির্বাচন করুন';
        }
    } catch (Exception $e) {
        $error_message = 'ছবি আপলোডে সমস্যা: ' . $e->getMessage();
    }
}

// Handle image deletion
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_image'])) {
    try {
        $image_id = intval($_POST['image_id']);
        
        // Get image path before deletion
        $stmt = $pdo->prepare("SELECT image_path FROM student_gallery WHERE id = ?");
        $stmt->execute([$image_id]);
        $image = $stmt->fetch();
        
        if ($image) {
            // Delete from database
            $stmt = $pdo->prepare("DELETE FROM student_gallery WHERE id = ?");
            $stmt->execute([$image_id]);
            
            // Delete file from server
            $image_path = dirname(__DIR__) . '/../' . $image['image_path'];
            if (file_exists($image_path)) {
                @unlink($image_path);
            }
            
            $success_message = 'ছবি সফলভাবে মুছে ফেলা হয়েছে';
        } else {
            $error_message = 'ছবি খুঁজে পাওয়া যায়নি';
        }
    } catch (Exception $e) {
        $error_message = 'ছবি মুছে ফেলতে সমস্যা: ' . $e->getMessage();
    }
}

// Create student_gallery table if not exists
try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS student_gallery (
            id INT PRIMARY KEY AUTO_INCREMENT,
            title VARCHAR(255),
            description TEXT,
            category VARCHAR(100) DEFAULT 'general',
            image_path VARCHAR(500),
            student_id INT NULL,
            uploaded_by INT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE SET NULL,
            FOREIGN KEY (uploaded_by) REFERENCES users(id) ON DELETE SET NULL
        )
    ");
} catch (Exception $e) {
    // Table creation might fail if already exists
}

// Get filter category
$filter_category = isset($_GET['category']) ? $_GET['category'] : 'all';

// Get all gallery images with optional filtering
$gallery_images = [];
try {
    $query = "
        SELECT sg.*, s.first_name, s.last_name, s.class_id, c.name as class_name, u.username as uploaded_by_name
        FROM student_gallery sg
        LEFT JOIN students s ON sg.student_id = s.id
        LEFT JOIN classes c ON s.class_id = c.id
        LEFT JOIN users u ON sg.uploaded_by = u.id
    ";
    
    $params = [];
    if ($filter_category !== 'all') {
        $query .= " WHERE sg.category = ?";
        $params[] = $filter_category;
    }
    
    $query .= " ORDER BY sg.created_at DESC";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $gallery_images = $stmt->fetchAll();
} catch (Exception $e) {
    $error_message = 'গ্যালারি ছবি আনতে সমস্যা: ' . $e->getMessage();
}

// Get all students for dropdown
$students = [];
try {
    $stmt = $pdo->query("
        SELECT s.id, s.first_name, s.last_name, c.name as class_name 
        FROM students s 
        LEFT JOIN classes c ON s.class_id = c.id 
        WHERE s.status = 'active' 
        ORDER BY c.name, s.roll_number
    ");
    $students = $stmt->fetchAll();
} catch (Exception $e) {
    $error_message = 'ছাত্র তালিকা আনতে সমস্যা: ' . $e->getMessage();
}

// Get categories for filter
$categories = [];
try {
    $stmt = $pdo->query("SELECT DISTINCT category FROM student_gallery ORDER BY category");
    $categories = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (Exception $e) {
    // Ignore errors
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>গ্যালারি - স্কুল ম্যানেজমেন্ট সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f8f9fa;
        }
        
        .gallery-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
        }
        
        .gallery-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
            overflow: hidden;
        }
        
        .gallery-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        }
        
        .gallery-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-bottom: 1px solid #eee;
        }
        
        .gallery-info {
            padding: 1rem;
        }
        
        .image-title {
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: #333;
        }
        
        .image-meta {
            font-size: 0.85rem;
            color: #666;
            margin-bottom: 0.5rem;
        }
        
        .category-badge {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
            border-radius: 10px;
        }
        
        .modal-image {
            max-width: 100%;
            max-height: 80vh;
            object-fit: contain;
        }
        
        .upload-section {
            background: white;
            border-radius: 10px;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .stats-number {
            font-size: 2rem;
            font-weight: bold;
            display: block;
        }
        
        .stats-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .filter-section {
            background: white;
            border-radius: 10px;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="gallery-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1><i class="fas fa-images"></i> গ্যালারি</h1>
                    <p class="mb-0">স্কুলের সব ধরনের ছবি সংগ্রহ ও প্রদর্শন</p>
                </div>
                <div class="col-md-4 text-md-end">
                    <a href="../../index.php" class="btn btn-light">
                        <i class="fas fa-arrow-left"></i> ড্যাশবোর্ডে ফিরে যান
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if ($error_message): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Upload Section -->
            <div class="col-md-4">
                <div class="upload-section">
                    <h4><i class="fas fa-upload"></i> নতুন ছবি আপলোড</h4>
                    <form method="POST" action="" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label for="title" class="form-label">শিরোনাম</label>
                            <input type="text" class="form-control" id="title" name="title" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="category" class="form-label">বিভাগ</label>
                            <select class="form-select" id="category" name="category" required>
                                <option value="event">ইভেন্ট</option>
                                <option value="activity">কার্যক্রম</option>
                                <option value="student">ছাত্র-ছাত্রী</option>
                                <option value="facility">সুবিধা</option>
                                <option value="general">সাধারণ</option>
                                <option value="achievement">অর্জন</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="description" class="form-label">বিবরণ</label>
                            <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="student_id" class="form-label">ছাত্র/ছাত্রী (ঐচ্ছিক)</label>
                            <select class="form-select" id="student_id" name="student_id">
                                <option value="">ছাত্র/ছাত্রী নির্বাচন করুন</option>
                                <?php foreach ($students as $student): ?>
                                    <option value="<?php echo $student['id']; ?>">
                                        <?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name'] . ' (' . $student['class_name'] . ')'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="image" class="form-label">ছবি নির্বাচন করুন</label>
                            <input type="file" class="form-control" id="image" name="image" accept="image/*" required>
                            <div class="form-text">শুধুমাত্র JPG, JPEG, PNG, GIF ফাইল অনুমোদিত</div>
                        </div>
                        
                        <button type="submit" name="upload_image" class="btn btn-primary w-100">
                            <i class="fas fa-upload"></i> আপলোড করুন
                        </button>
                    </form>
                </div>
                
                <!-- Filter Section -->
                <div class="filter-section">
                    <h5><i class="fas fa-filter"></i> ফিল্টার</h5>
                    <div class="list-group">
                        <a href="?category=all" class="list-group-item list-group-item-action <?php echo ($filter_category === 'all') ? 'active' : ''; ?>">
                            <i class="fas fa-globe"></i> সব ছবি (<?php echo count($gallery_images); ?>)
                        </a>
                        <?php foreach ($categories as $category): ?>
                            <?php 
                            // Count images in this category
                            $cat_count = 0;
                            foreach ($gallery_images as $img) {
                                if ($img['category'] == $category) $cat_count++;
                            }
                            ?>
                            <a href="?category=<?php echo urlencode($category); ?>" class="list-group-item list-group-item-action <?php echo ($filter_category === $category) ? 'active' : ''; ?>">
                                <i class="fas fa-folder"></i> <?php echo htmlspecialchars($category); ?> (<?php echo $cat_count; ?>)
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <!-- Statistics -->
                <div class="stats-card">
                    <div class="text-center">
                        <span class="stats-number"><?php echo count($gallery_images); ?></span>
                        <span class="stats-label">মোট ছবি</span>
                    </div>
                </div>
                
                <!-- Quick Links -->
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-bolt"></i> দ্রুত লিংক</h5>
                    </div>
                    <div class="card-body">
                        <a href="../../students/list.php" class="btn btn-outline-primary w-100 mb-2">
                            <i class="fas fa-list"></i> ছাত্র তালিকা
                        </a>
                        <a href="../../students/add.php" class="btn btn-outline-success w-100 mb-2">
                            <i class="fas fa-user-plus"></i> নতুন ভর্তি
                        </a>
                        <a href="settings.php" class="btn btn-outline-info w-100">
                            <i class="fas fa-cog"></i> সেটিংস
                        </a>
                    </div>
                </div>
            </div>
            
            <!-- Gallery Display -->
            <div class="col-md-8">
                <?php if (empty($gallery_images)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-images fa-5x text-muted mb-3"></i>
                        <h4>কোন ছবি পাওয়া যায়নি</h4>
                        <p class="text-muted">নতুন ছবি আপলোড করে গ্যালারি তৈরি করুন</p>
                    </div>
                <?php else: ?>
                    <div class="row">
                        <?php foreach ($gallery_images as $image): ?>
                            <div class="col-md-6 col-lg-4">
                                <div class="gallery-card">
                                    <img src="../../<?php echo htmlspecialchars($image['image_path']); ?>" 
                                         class="gallery-image" 
                                         alt="<?php echo htmlspecialchars($image['title']); ?>"
                                         data-bs-toggle="modal" 
                                         data-bs-target="#imageModal<?php echo $image['id']; ?>">
                                    
                                    <div class="gallery-info">
                                        <h6 class="image-title"><?php echo htmlspecialchars($image['title']); ?></h6>
                                        
                                        <?php if (!empty($image['category'])): ?>
                                            <span class="badge bg-primary category-badge">
                                                <?php echo htmlspecialchars($image['category']); ?>
                                            </span>
                                        <?php endif; ?>
                                        
                                        <?php if (!empty($image['description'])): ?>
                                            <p class="text-muted small mb-1 mt-2">
                                                <?php echo htmlspecialchars(substr($image['description'], 0, 60)) . (strlen($image['description']) > 60 ? '...' : ''); ?>
                                            </p>
                                        <?php endif; ?>
                                        
                                        <div class="image-meta">
                                            <?php if (!empty($image['first_name'])): ?>
                                                <div><i class="fas fa-user-graduate"></i> 
                                                    <?php echo htmlspecialchars($image['first_name'] . ' ' . $image['last_name']); ?>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($image['class_name'])): ?>
                                                <div><i class="fas fa-school"></i> <?php echo htmlspecialchars($image['class_name']); ?></div>
                                            <?php endif; ?>
                                            
                                            <div><i class="fas fa-calendar"></i> 
                                                <?php echo date('d/m/Y', strtotime($image['created_at'])); ?>
                                            </div>
                                            
                                            <div><i class="fas fa-user"></i> 
                                                <?php echo htmlspecialchars($image['uploaded_by_name']); ?>
                                            </div>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between mt-2">
                                            <button class="btn btn-sm btn-outline-primary" 
                                                    data-bs-toggle="modal" 
                                                    data-bs-target="#imageModal<?php echo $image['id']; ?>">
                                                <i class="fas fa-eye"></i> দেখুন
                                            </button>
                                            
                                            <?php if ($user_role == 'admin'): ?>
                                                <form method="POST" action="" class="d-inline">
                                                    <input type="hidden" name="image_id" value="<?php echo $image['id']; ?>">
                                                    <button type="submit" name="delete_image" 
                                                            class="btn btn-sm btn-outline-danger"
                                                            onclick="return confirm('আপনি কি নিশ্চিত যে এই ছবিটি মুছে ফেলতে চান?')">
                                                        <i class="fas fa-trash"></i> মুছুন
                                                    </button>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Image Modal -->
                            <div class="modal fade" id="imageModal<?php echo $image['id']; ?>" tabindex="-1">
                                <div class="modal-dialog modal-lg">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title"><?php echo htmlspecialchars($image['title']); ?></h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>
                                        <div class="modal-body text-center">
                                            <img src="../../<?php echo htmlspecialchars($image['image_path']); ?>" 
                                                 class="modal-image" 
                                                 alt="<?php echo htmlspecialchars($image['title']); ?>">
                                            
                                            <?php if (!empty($image['description'])): ?>
                                                <p class="mt-3"><?php echo htmlspecialchars($image['description']); ?></p>
                                            <?php endif; ?>
                                            
                                            <div class="text-start mt-3">
                                                <?php if (!empty($image['category'])): ?>
                                                    <p><strong>বিভাগ:</strong> <?php echo htmlspecialchars($image['category']); ?></p>
                                                <?php endif; ?>
                                                
                                                <?php if (!empty($image['first_name'])): ?>
                                                    <p><strong>ছাত্র/ছাত্রী:</strong> 
                                                        <?php echo htmlspecialchars($image['first_name'] . ' ' . $image['last_name']); ?>
                                                    </p>
                                                <?php endif; ?>
                                                
                                                <?php if (!empty($image['class_name'])): ?>
                                                    <p><strong>ক্লাস:</strong> <?php echo htmlspecialchars($image['class_name']); ?></p>
                                                <?php endif; ?>
                                                
                                                <p><strong>আপলোডকারী:</strong> <?php echo htmlspecialchars($image['uploaded_by_name']); ?></p>
                                                <p><strong>তারিখ:</strong> <?php echo date('d/m/Y H:i', strtotime($image['created_at'])); ?></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Image preview on upload
        document.getElementById('image').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const maxSize = 5 * 1024 * 1024; // 5MB
                if (file.size > maxSize) {
                    alert('ফাইলের সাইজ 5MB এর বেশি হতে পারবে না');
                    e.target.value = '';
                    return;
                }
                
                const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
                if (!allowedTypes.includes(file.type)) {
                    alert('শুধুমাত্র JPG, JPEG, PNG, GIF ফাইল অনুমোদিত');
                    e.target.value = '';
                    return;
                }
            }
        });
    </script>
</body>
</html>