<?php
session_start();
ob_start();
include "../include/config.php";

// Check if user is logged in
if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit();
}

$userlogin = $_SESSION['email'];
$email = $_SESSION['email'];

// Handle file upload
$message = "";
if (isset($_POST['add_material'])) {
    $title = mysqli_real_escape_string($conn, $_POST['title']);
    $author = mysqli_real_escape_string($conn, $_POST['author']);
    $category = mysqli_real_escape_string($conn, $_POST['category']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $course_code = mysqli_real_escape_string($conn, $_POST['course_code']);
    $tags = mysqli_real_escape_string($conn, $_POST['tags']);
    
    // Handle file upload
    $file_path = "";
    $file_type = "";
    $file_size = "";
    $thumbnail = "";
    
    if (!empty($_FILES['file']['name'])) {
        $target_dir = "repository_files/";
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }
        
        $file_name = basename($_FILES["file"]["name"]);
        $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $new_file_name = uniqid() . '_' . $file_name;
        $target_file = $target_dir . $new_file_name;
        
        // Allowed file types
        $allowed_types = array('pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'txt', 'zip', 'jpg', 'jpeg', 'png');
        
        if (in_array($file_extension, $allowed_types)) {
            if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
                $file_path = $target_file;
                $file_type = $file_extension;
                $file_size = formatFileSize($_FILES["file"]["size"]);
                
                // Generate thumbnail for images
                if (in_array($file_extension, ['jpg', 'jpeg', 'png'])) {
                    $thumbnail = generateThumbnail($target_file, $file_extension);
                }
            }
        }
    }
    
    // Insert into database
    $sql = "INSERT INTO repository (title, author, category, description, file_path, file_type, file_size, uploaded_by, tags, course_code, thumbnail) 
            VALUES ('$title', '$author', '$category', '$description', '$file_path', '$file_type', '$file_size', '$userlogin', '$tags', '$course_code', '$thumbnail')";
    
    if ($conn->query($sql)) {
        $_SESSION['message'] = "Material added successfully!";
        $_SESSION['message_type'] = "success";
        header("Location: repository.php");
        exit();
    } else {
        $_SESSION['message'] = "Error: " . $conn->error;
        $_SESSION['message_type'] = "danger";
    }
}

// Handle file deletion
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    
    // Check if the current user is the one who uploaded the material
    $check_query = $conn->query("SELECT uploaded_by, file_path, thumbnail FROM repository WHERE id = $id");
    if ($check_query->num_rows > 0) {
        $row = $check_query->fetch_assoc();
        
        // Only allow deletion if the current user is the uploader
        if ($row['uploaded_by'] === $userlogin) {
            // Delete physical files
            if (file_exists($row['file_path'])) {
                unlink($row['file_path']);
            }
            if (!empty($row['thumbnail']) && file_exists($row['thumbnail'])) {
                unlink($row['thumbnail']);
            }
            
            $conn->query("DELETE FROM repository WHERE id = $id");
            $_SESSION['message'] = "Material deleted successfully!";
            $_SESSION['message_type'] = "success";
        } else {
            $_SESSION['message'] = "You can only delete materials that you uploaded!";
            $_SESSION['message_type'] = "danger";
        }
    }
    
    header("Location: repository.php");
    exit();
}

// Handle download count
if (isset($_GET['download'])) {
    $id = intval($_GET['download']);
    $conn->query("UPDATE repository SET download_count = download_count + 1 WHERE id = $id");
    
    $result = $conn->query("SELECT file_path FROM repository WHERE id = $id");
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $file_path = $row['file_path'];
        
        if (file_exists($file_path)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file_path));
            readfile($file_path);
            exit;
        }
    }
}

// Helper functions
function formatFileSize($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' bytes';
    }
}

function generateThumbnail($file_path, $extension) {
    $thumb_dir = "repository_thumbs/";
    if (!is_dir($thumb_dir)) {
        mkdir($thumb_dir, 0777, true);
    }
    
    $thumb_name = uniqid() . '_thumb.jpg';
    $thumb_path = $thumb_dir . $thumb_name;
    
    try {
        if ($extension == 'jpg' || $extension == 'jpeg') {
            $image = imagecreatefromjpeg($file_path);
        } elseif ($extension == 'png') {
            $image = imagecreatefrompng($file_path);
        }
        
        if (isset($image)) {
            $width = imagesx($image);
            $height = imagesy($image);
            
            $new_width = 300;
            $new_height = ($height / $width) * $new_width;
            
            $thumb = imagecreatetruecolor($new_width, $new_height);
            imagecopyresampled($thumb, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            
            imagejpeg($thumb, $thumb_path, 80);
            imagedestroy($image);
            imagedestroy($thumb);
            
            return $thumb_path;
        }
    } catch (Exception $e) {
        return "";
    }
    
    return "";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>College Repository</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #238665;
            --secondary-color: #2c3e50;
            --accent-color: #3498db;
            --light-bg: #f8f9fa;
            --card-shadow: 0 4px 6px rgba(0,0,0,0.1);
            --hover-shadow: 0 8px 15px rgba(0,0,0,0.2);
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: var(--light-bg);
            color: #333;
        }
        
        .content {
            margin-left: 200px;
            padding: 20px;
            transition: margin-left 0.3s;
        }
        
        @media (max-width: 768px) {
            .content {
                margin-left: 0;
            }
        }
        
        .repository-header {
            background: var(--primary-color);
            color: white;
            padding: 30px 20px;
            border-radius: 10px;
            margin-bottom: 30px;
        }
        
        .material-card {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: var(--card-shadow);
            transition: all 0.3s ease;
            margin-bottom: 25px;
            border: none;
        }
        
        .material-card:hover {
            transform: translateY(-5px);
            box-shadow: var(--hover-shadow);
        }
        
        .material-thumbnail {
            height: 200px;
            background: #667eea;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 48px;
            position: relative;
            overflow: hidden;
        }
        
        .material-thumbnail img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .material-content {
            padding: 20px;
        }
        
        .material-title {
            font-weight: 600;
            font-size: 1.1rem;
            margin-bottom: 10px;
            color: var(--secondary-color);
            line-height: 1.4;
        }
        
        .material-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            font-size: 0.85rem;
            color: #666;
        }
        
        .material-author {
            font-weight: 500;
        }
        
        .material-category {
            background: var(--primary-color);
            color: white;
            padding: 3px 8px;
            border-radius: 15px;
            font-size: 0.75rem;
        }
        
        .material-description {
            color: #666;
            font-size: 0.9rem;
            margin-bottom: 15px;
            line-height: 1.5;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }
        
        .material-stats {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.8rem;
            color: #888;
            border-top: 1px solid #eee;
            padding-top: 15px;
        }
        
        .material-actions {
            display: flex;
            gap: 8px;
        }
        
        .btn-repo {
            background: var(--primary-color);
            border: none;
            color: white;
            padding: 8px 15px;
            border-radius: 5px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            transition: all 0.3s;
        }
        
        .btn-repo:hover {
            background: #1a6b4f;
            color: white;
            transform: translateY(-2px);
        }
        
        .btn-download {
            background: var(--accent-color);
        }
        
        .btn-download:hover {
            background: #2980b9;
        }
        
        .btn-danger-repo {
            background: #e74c3c;
        }
        
        .btn-danger-repo:hover {
            background: #c0392b;
        }
        
        .search-section {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: var(--card-shadow);
            margin-bottom: 30px;
        }
        
        .filter-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 15px;
        }
        
        .filter-btn {
            background: white;
            border: 2px solid var(--primary-color);
            color: var(--primary-color);
            padding: 5px 15px;
            border-radius: 20px;
            transition: all 0.3s;
        }
        
        .filter-btn.active, .filter-btn:hover {
            background: var(--primary-color);
            color: white;
        }
        
        .file-icon {
            font-size: 3rem;
            opacity: 0.8;
        }
        
        .stats-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: var(--card-shadow);
            margin-bottom: 20px;
        }
        
        .stats-number {
            font-size: 2rem;
            font-weight: bold;
            color: var(--primary-color);
            margin-bottom: 5px;
        }
        
        .stats-label {
            color: #666;
            font-size: 0.9rem;
        }
        
        .uploaded-by {
            font-size: 0.8rem;
            color: #888;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
<?php include "../include/nav.php"; ?>

<div class="content">
    <!-- Header Section -->
    <div class="repository-header">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h1><i class="fas fa-graduation-cap me-3"></i>Unicohs Repository</h1>
                <p class="mb-0">Access and share academic materials, research papers, and learning resources</p>
            </div>
            <div class="col-md-4 text-end">
                <button class="btn btn-light btn-lg" data-bs-toggle="modal" data-bs-target="#addMaterialModal">
                    <i class="fas fa-plus me-2"></i>Upload Material
                </button>
            </div>
        </div>
    </div>

    <?php
    // Display session messages
    if (isset($_SESSION['message'])) {
        echo "<div class='alert alert-{$_SESSION['message_type']} alert-dismissible fade show text-center'>
                <i class='fas fa-info-circle me-2'></i>{$_SESSION['message']}
                <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
              </div>";
        unset($_SESSION['message']);
        unset($_SESSION['message_type']);
    }
    ?>

    <!-- Statistics Section -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="stats-card">
                <div class="stats-number">
                    <?php
                    $total_query = $conn->query("SELECT COUNT(*) as total FROM repository");
                    echo $total_query->fetch_assoc()['total'];
                    ?>
                </div>
                <div class="stats-label">Total Materials</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card">
                <div class="stats-number">
                    <?php
                    $download_query = $conn->query("SELECT SUM(download_count) as downloads FROM repository");
                    echo $download_query->fetch_assoc()['downloads'] ?? 0;
                    ?>
                </div>
                <div class="stats-label">Total Downloads</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card">
                <div class="stats-number">
                    <?php
                    $categories_query = $conn->query("SELECT COUNT(DISTINCT category) as categories FROM repository");
                    echo $categories_query->fetch_assoc()['categories'];
                    ?>
                </div>
                <div class="stats-label">Categories</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card">
                <div class="stats-number">
                    <?php
                    $recent_query = $conn->query("SELECT COUNT(*) as recent FROM repository WHERE upload_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
                    echo $recent_query->fetch_assoc()['recent'];
                    ?>
                </div>
                <div class="stats-label">This Week</div>
            </div>
        </div>
    </div>

    <!-- Search and Filter Section -->
    <div class="search-section">
        <div class="row">
            <div class="col-md-8">
                <input type="text" id="searchInput" class="form-control form-control-lg" placeholder="Search materials by title, author, course code, or tags...">
            </div>
            <div class="col-md-4">
                <select id="categoryFilter" class="form-control form-control-lg">
                    <option value="">All Categories</option>
                    <?php
                    $categories = $conn->query("SELECT DISTINCT category FROM repository ORDER BY category");
                    while ($cat = $categories->fetch_assoc()) {
                        echo "<option value='{$cat['category']}'>{$cat['category']}</option>";
                    }
                    ?>
                </select>
            </div>
        </div>
        
        <div class="filter-buttons">
            <button class="filter-btn active" data-filter="all">All Materials</button>
            <button class="filter-btn" data-filter="pdf">PDF Documents</button>
            <button class="filter-btn" data-filter="doc">Word Documents</button>
            <button class="filter-btn" data-filter="ppt">Presentations</button>
            <button class="filter-btn" data-filter="image">Images</button>
            <button class="filter-btn" data-filter="other">Other Files</button>
        </div>
    </div>

    <!-- Materials Grid -->
    <div class="row" id="materialsContainer">
        <?php
        $sql = "SELECT * FROM repository WHERE status = 'active' ORDER BY upload_date DESC";
        $result = $conn->query($sql);
        
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $file_icon = getFileIcon($row['file_type']);
                $thumbnail = !empty($row['thumbnail']) ? $row['thumbnail'] : '';
                $canDelete = ($row['uploaded_by'] === $userlogin);
                ?>
                <div class="col-xl-4 col-lg-4 col-md-6 material-item" data-category="<?php echo $row['category']; ?>" data-type="<?php echo $row['file_type']; ?>">
                    <div class="material-card">
                        <div class="material-thumbnail">
                            <?php if (!empty($thumbnail)): ?>
                                <img src="<?php echo $thumbnail; ?>" alt="Thumbnail">
                            <?php else: ?>
                                <i class="<?php echo $file_icon; ?> file-icon"></i>
                            <?php endif; ?>
                        </div>
                        
                        <div class="material-content">
                            <div class="material-title"><?php echo htmlspecialchars($row['title']); ?></div>
                            
                            <div class="material-meta">
                                <span class="material-author">
                                    <i class="fas fa-user me-1"></i><?php echo htmlspecialchars($row['author']); ?>
                                </span>
                                <span class="material-category"><?php echo htmlspecialchars($row['category']); ?></span>
                            </div>
                            
                            <div class="uploaded-by">
                                <small>
                                    <i class="fas fa-user-circle me-1"></i>Uploaded by: <?php echo htmlspecialchars($row['uploaded_by']); ?>
                                </small>
                            </div>
                            
                            <?php if (!empty($row['description'])): ?>
                                <div class="material-description"><?php echo htmlspecialchars($row['description']); ?></div>
                            <?php endif; ?>
                            
                            <?php if (!empty($row['course_code'])): ?>
                                <div class="mb-2">
                                    <small class="text-muted">
                                        <i class="fas fa-book me-1"></i><?php echo htmlspecialchars($row['course_code']); ?>
                                    </small>
                                </div>
                            <?php endif; ?>
                            
                            <div class="material-stats">
                                <div>
                                    <small>
                                        <i class="fas fa-download me-1"></i><?php echo $row['download_count']; ?> downloads
                                    </small>
                                </div>
                                <div class="material-actions">
                                    <a href="?download=<?php echo $row['id']; ?>" class="btn-repo btn-download btn-sm">
                                        <i class="fas fa-download"></i>
                                    </a>
                                    <?php if ($canDelete): ?>
                                    <a href="?delete=<?php echo $row['id']; ?>" class="btn-repo btn-danger-repo btn-sm" 
                                       onclick="return confirm('Are you sure you want to delete this material?');">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php
            }
        } else {
            echo '<div class="col-12 text-center py-5">
                    <i class="fas fa-folder-open fa-3x text-muted mb-3"></i>
                    <h4 class="text-muted">No materials found</h4>
                    <p class="text-muted">Upload the first material to get started!</p>
                  </div>';
        }
        
        function getFileIcon($file_type) {
            switch ($file_type) {
                case 'pdf': return 'fas fa-file-pdf';
                case 'doc': case 'docx': return 'fas fa-file-word';
                case 'ppt': case 'pptx': return 'fas fa-file-powerpoint';
                case 'xls': case 'xlsx': return 'fas fa-file-excel';
                case 'jpg': case 'jpeg': case 'png': return 'fas fa-file-image';
                case 'zip': return 'fas fa-file-archive';
                default: return 'fas fa-file';
            }
        }
        ?>
    </div>
</div>

<!-- Add Material Modal -->
<div class="modal fade" id="addMaterialModal" tabindex="-1" aria-labelledby="addMaterialModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="addMaterialModalLabel">
                    <i class="fas fa-upload me-2"></i>Upload New Material
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="title" class="form-label">Title *</label>
                                <input type="text" class="form-control" id="title" name="title" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="author" class="form-label">Author *</label>
                                <input type="text" class="form-control" id="author" name="author" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="category" class="form-label">Category *</label>
                                <select class="form-control" id="category" name="category" required>
                                    <option value="">Select Category</option>
                                    <option value="Lecture Notes">Lecture Notes</option>
                                    <option value="Research Papers">Research Papers</option>
                                    <option value="Assignments">Assignments</option>
                                    <option value="Projects">Projects</option>
                                    <option value="Tutorials">Tutorials</option>
                                    <option value="Exams">Exams</option>
                                    <option value="Textbooks">Textbooks</option>
                                    <option value="Presentations">Presentations</option>
                                    <option value="Lab Manuals">Lab Manuals</option>
                                    <option value="Case Studies">Case Studies</option>
                                    <option value="Other">Other</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="course_code" class="form-label">Course Code</label>
                                <input type="text" class="form-control" id="course_code" name="course_code" placeholder="e.g., CS101, MATH202">
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="file" class="form-label">File *</label>
                        <input type="file" class="form-control" id="file" name="file" accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.zip,.jpg,.jpeg,.png" required>
                        <small class="form-text text-muted">Supported formats: PDF, Word, PowerPoint, Excel, Images, ZIP</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="3" placeholder="Brief description of the material..."></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="tags" class="form-label">Tags</label>
                        <input type="text" class="form-control" id="tags" name="tags" placeholder="e.g., programming, algorithms, data-structures (separate with commas)">
                        <small class="form-text text-muted">Add relevant tags to make your material easier to find</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_material" class="btn btn-primary">
                        <i class="fas fa-upload me-2"></i>Upload Material
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Search and filter functionality
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('searchInput');
    const categoryFilter = document.getElementById('categoryFilter');
    const filterButtons = document.querySelectorAll('.filter-btn');
    const materialItems = document.querySelectorAll('.material-item');
    
    function filterMaterials() {
        const searchTerm = searchInput.value.toLowerCase();
        const selectedCategory = categoryFilter.value;
        const activeFilter = document.querySelector('.filter-btn.active').dataset.filter;
        
        materialItems.forEach(item => {
            const title = item.querySelector('.material-title').textContent.toLowerCase();
            const author = item.querySelector('.material-author').textContent.toLowerCase();
            const category = item.dataset.category;
            const type = item.dataset.type;
            
            const matchesSearch = title.includes(searchTerm) || author.includes(searchTerm);
            const matchesCategory = !selectedCategory || category === selectedCategory;
            const matchesType = activeFilter === 'all' || 
                               (activeFilter === 'pdf' && type === 'pdf') ||
                               (activeFilter === 'doc' && (type === 'doc' || type === 'docx')) ||
                               (activeFilter === 'ppt' && (type === 'ppt' || type === 'pptx')) ||
                               (activeFilter === 'image' && (type === 'jpg' || type === 'jpeg' || type === 'png')) ||
                               (activeFilter === 'other' && !['pdf','doc','docx','ppt','pptx','jpg','jpeg','png'].includes(type));
            
            if (matchesSearch && matchesCategory && matchesType) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    }
    
    searchInput.addEventListener('input', filterMaterials);
    categoryFilter.addEventListener('change', filterMaterials);
    
    filterButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            filterButtons.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            filterMaterials();
        });
    });
    
    // Auto-hide alerts after 5 seconds
    setTimeout(function() {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 5000);
});
</script>
</body>
</html>