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

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

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

// Get user info based on role
$user_info = null;
if ($user_role == 'student') {
    $stmt = $pdo->prepare("SELECT * FROM students WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $user_info = $stmt->fetch();
} elseif ($user_role == 'teacher') {
    $stmt = $pdo->prepare("SELECT * FROM teachers WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $user_info = $stmt->fetch();
}

// Get classes and subjects for teachers
$classes = [];
$subjects = [];
if ($user_role == 'teacher') {
    $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section");
    $classes = $stmt->fetchAll();
    
    $stmt = $pdo->query("SELECT id, name, code FROM subjects WHERE status = 'active' ORDER BY name");
    $subjects = $stmt->fetchAll();
}

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $description = trim($_POST['description']);
    $category = $_POST['category'];
    $is_public = isset($_POST['is_public']) ? 1 : 0;
    $target_class_id = !empty($_POST['target_class_id']) ? $_POST['target_class_id'] : null;
    $target_subject_id = !empty($_POST['target_subject_id']) ? $_POST['target_subject_id'] : null;
    
    // File upload handling
    if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
        $file = $_FILES['file'];
        $original_name = $file['name'];
        $file_size = $file['size'];
        $file_type = $file['type'];
        $tmp_name = $file['tmp_name'];
        
        // Validate file size (10MB max)
        if ($file_size > 10 * 1024 * 1024) {
            $error_message = 'ফাইল সাইজ ১০MB এর বেশি হতে পারবে না';
        } else {
            // Validate file type
            $allowed_types = [
                'application/pdf',
                'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'image/jpeg',
                'image/jpg',
                'image/png',
                'image/gif',
                'video/mp4',
                'video/avi',
                'text/plain'
            ];
            
            if (!in_array($file_type, $allowed_types)) {
                $error_message = 'অসমর্থিত ফাইল ফরম্যাট। শুধুমাত্র PDF, DOC, DOCX, JPG, PNG, GIF, MP4, AVI, TXT ফাইল আপলোড করা যাবে।';
            } else {
                try {
                    // Generate unique filename
                    $file_extension = pathinfo($original_name, PATHINFO_EXTENSION);
                    $unique_name = uniqid() . '_' . time() . '.' . $file_extension;
                    
                    // Determine upload directory based on user role
                    $upload_dir = $user_role == 'student' ? 'students' : 'teachers';
                    $upload_path = "../uploads/$upload_dir/";
                    
                    // Create directory if not exists
                    if (!is_dir($upload_path)) {
                        mkdir($upload_path, 0777, true);
                    }
                    
                    $file_path = $upload_path . $unique_name;
                    
                    // Move uploaded file
                    if (move_uploaded_file($tmp_name, $file_path)) {
                        // Save to database
                        $stmt = $pdo->prepare("
                            INSERT INTO file_uploads (
                                uploader_type, uploader_id, file_name, original_name, 
                                file_path, file_type, file_size, category, description, 
                                is_public, target_class_id, target_subject_id
                            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                        ");
                        
                        $uploader_id = $user_info ? $user_info['id'] : 0;
                        $relative_path = "uploads/$upload_dir/" . $unique_name;
                        
                        $stmt->execute([
                            $user_role, $uploader_id, $unique_name, $original_name,
                            $relative_path, $file_type, $file_size, $category, $description,
                            $is_public, $target_class_id, $target_subject_id
                        ]);
                        
                        $success_message = 'ফাইল সফলভাবে আপলোড হয়েছে!';
                        
                        // Clear form data
                        $_POST = array();
                        
                    } else {
                        $error_message = 'ফাইল আপলোড করতে সমস্যা হয়েছে';
                    }
                    
                } catch (Exception $e) {
                    $error_message = 'ডাটাবেস ত্রুটি: ' . $e->getMessage();
                }
            }
        }
    } else {
        $error_message = 'অনুগ্রহ করে একটি ফাইল নির্বাচন করুন';
    }
}
?>

<!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="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="index.php">
                    <i class="fas fa-arrow-left"></i> ফিরে যান
                </a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h4><i class="fas fa-cloud-upload-alt"></i> নতুন ফাইল আপলোড</h4>
                    </div>
                    <div class="card-body">
                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-dismissible fade show">
                                <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">
                                <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; ?>

                        <form method="POST" action="" enctype="multipart/form-data" class="needs-validation" novalidate>
                            <!-- File Upload -->
                            <div class="mb-4">
                                <label for="file" class="form-label">ফাইল নির্বাচন করুন <span class="text-danger">*</span></label>
                                <div class="file-upload" id="fileUploadArea">
                                    <div class="file-upload-icon">
                                        <i class="fas fa-cloud-upload-alt"></i>
                                    </div>
                                    <p class="mb-2">ফাইল এখানে ড্র্যাগ করুন অথবা ক্লিক করে নির্বাচন করুন</p>
                                    <input type="file" class="form-control" id="file" name="file" required style="display: none;">
                                    <button type="button" class="btn btn-outline-primary" onclick="document.getElementById('file').click()">
                                        <i class="fas fa-folder-open"></i> ফাইল নির্বাচন করুন
                                    </button>
                                    <div class="invalid-feedback">অনুগ্রহ করে একটি ফাইল নির্বাচন করুন</div>
                                </div>
                                <div id="fileInfo" class="mt-2" style="display: none;">
                                    <div class="alert alert-info">
                                        <i class="fas fa-file"></i> <span id="fileName"></span>
                                        <br><small>সাইজ: <span id="fileSize"></span></small>
                                    </div>
                                </div>
                                <small class="form-text text-muted">
                                    সমর্থিত ফরম্যাট: PDF, DOC, DOCX, JPG, PNG, GIF, MP4, AVI, TXT (সর্বোচ্চ ১০MB)
                                </small>
                            </div>

                            <!-- Category -->
                            <div class="mb-3">
                                <label for="category" class="form-label">ফাইলের ধরন</label>
                                <select class="form-select" id="category" name="category" required>
                                    <option value="">নির্বাচন করুন</option>
                                    <option value="document" <?php echo (isset($_POST['category']) && $_POST['category'] == 'document') ? 'selected' : ''; ?>>ডকুমেন্ট</option>
                                    <option value="assignment" <?php echo (isset($_POST['category']) && $_POST['category'] == 'assignment') ? 'selected' : ''; ?>>অ্যাসাইনমেন্ট</option>
                                    <option value="image" <?php echo (isset($_POST['category']) && $_POST['category'] == 'image') ? 'selected' : ''; ?>>ছবি</option>
                                    <option value="video" <?php echo (isset($_POST['category']) && $_POST['category'] == 'video') ? 'selected' : ''; ?>>ভিডিও</option>
                                    <option value="other" <?php echo (isset($_POST['category']) && $_POST['category'] == 'other') ? 'selected' : ''; ?>>অন্যান্য</option>
                                </select>
                                <div class="invalid-feedback">ফাইলের ধরন নির্বাচন করুন</div>
                            </div>

                            <!-- Description -->
                            <div class="mb-3">
                                <label for="description" class="form-label">বিবরণ</label>
                                <textarea class="form-control" id="description" name="description" rows="3" 
                                          placeholder="ফাইল সম্পর্কে সংক্ষিপ্ত বিবরণ লিখুন"><?php echo isset($_POST['description']) ? htmlspecialchars($_POST['description']) : ''; ?></textarea>
                            </div>

                            <?php if ($user_role == 'teacher'): ?>
                            <!-- Teacher specific options -->
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="target_class_id" class="form-label">নির্দিষ্ট ক্লাস (ঐচ্ছিক)</label>
                                        <select class="form-select" id="target_class_id" name="target_class_id">
                                            <option value="">সব ক্লাস</option>
                                            <?php foreach ($classes as $class): ?>
                                                <option value="<?php echo $class['id']; ?>" 
                                                        <?php echo (isset($_POST['target_class_id']) && $_POST['target_class_id'] == $class['id']) ? 'selected' : ''; ?>>
                                                    <?php echo $class['name'] . ' - ' . $class['section']; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="target_subject_id" class="form-label">নির্দিষ্ট বিষয় (ঐচ্ছিক)</label>
                                        <select class="form-select" id="target_subject_id" name="target_subject_id">
                                            <option value="">সব বিষয়</option>
                                            <?php foreach ($subjects as $subject): ?>
                                                <option value="<?php echo $subject['id']; ?>" 
                                                        <?php echo (isset($_POST['target_subject_id']) && $_POST['target_subject_id'] == $subject['id']) ? 'selected' : ''; ?>>
                                                    <?php echo $subject['name'] . ' (' . $subject['code'] . ')'; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <!-- Public checkbox -->
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="is_public" name="is_public" 
                                           <?php echo (isset($_POST['is_public'])) ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="is_public">
                                        <i class="fas fa-globe"></i> পাবলিক ফাইল (ছাত্রদের জন্য দৃশ্যমান)
                                    </label>
                                </div>
                                <small class="form-text text-muted">
                                    চেক করলে ছাত্ররা এই ফাইলটি দেখতে ও ডাউনলোড করতে পারবে
                                </small>
                            </div>
                            <?php endif; ?>

                            <!-- Submit Button -->
                            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                <a href="index.php" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> বাতিল
                                </a>
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-cloud-upload-alt"></i> আপলোড করুন
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Form validation
        (function() {
            'use strict';
            window.addEventListener('load', function() {
                var forms = document.getElementsByClassName('needs-validation');
                var validation = Array.prototype.filter.call(forms, function(form) {
                    form.addEventListener('submit', function(event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
        })();

        // File upload handling
        const fileInput = document.getElementById('file');
        const fileUploadArea = document.getElementById('fileUploadArea');
        const fileInfo = document.getElementById('fileInfo');
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');

        fileInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                fileName.textContent = file.name;
                fileSize.textContent = formatFileSize(file.size);
                fileInfo.style.display = 'block';
                fileUploadArea.style.borderColor = '#28a745';
                fileUploadArea.style.backgroundColor = '#f8fff9';
            }
        });

        // Drag and drop functionality
        fileUploadArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            fileUploadArea.style.borderColor = '#007bff';
            fileUploadArea.style.backgroundColor = '#f8f9ff';
        });

        fileUploadArea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            fileUploadArea.style.borderColor = '#667eea';
            fileUploadArea.style.backgroundColor = '#f8f9fa';
        });

        fileUploadArea.addEventListener('drop', function(e) {
            e.preventDefault();
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                fileInput.files = files;
                const event = new Event('change', { bubbles: true });
                fileInput.dispatchEvent(event);
            }
        });

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    </script>
</body>
</html>