<?php
require_once 'config.php';
requireLogin();

// Only students can upload tasks
if ($_SESSION['role'] !== 'siswa') {
    header('Location: dashboard.php?error=access_denied');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $subject = sanitizeInput($_POST['subject'] ?? '');
    $title = sanitizeInput($_POST['title'] ?? '');
    $description = sanitizeInput($_POST['description'] ?? '');
    
    $errors = [];
    
    // Validate required fields
    if (empty($subject)) {
        $errors[] = 'Mata pelajaran harus dipilih';
    }
    
    if (empty($title)) {
        $errors[] = 'Judul tugas harus diisi';
    }
    
    if (empty($errors)) {
        $fileName = '';
        $filePath = '';
        $fileSize = 0;
        
        // Handle file upload
        if (isset($_FILES['file']) && $_FILES['file']['error'] === 0) {
            $uploadDir = 'uploads/tasks/';
            
            // Create upload directory if it doesn't exist
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            $originalName = $_FILES['file']['name'];
            $fileExtension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
            $allowedExtensions = ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png', 'zip', 'rar'];
            $maxFileSize = 10 * 1024 * 1024; // 10MB
            
            // Validate file extension
            if (!in_array($fileExtension, $allowedExtensions)) {
                $errors[] = 'Format file tidak diizinkan. Gunakan: ' . implode(', ', $allowedExtensions);
            }
            
            // Validate file size
            if ($_FILES['file']['size'] > $maxFileSize) {
                $errors[] = 'Ukuran file terlalu besar. Maksimal 10MB';
            }
            
            if (empty($errors)) {
                // Generate unique filename
                $fileName = time() . '_' . $_SESSION['user_id'] . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $originalName);
                $filePath = $uploadDir . $fileName;
                $fileSize = $_FILES['file']['size'];
                
                if (!move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
                    $errors[] = 'Gagal upload file. Silakan coba lagi';
                }
            }
        }
        
        // Save to database if no errors
        if (empty($errors)) {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO tasks (student_id, subject, title, description, file_name, file_path, file_size) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                
                if ($stmt->execute([$_SESSION['user_id'], $subject, $title, $description, $fileName, $filePath, $fileSize])) {
                    header('Location: dashboard.php?success=1');
                    exit();
                } else {
                    $errors[] = 'Gagal menyimpan tugas ke database';
                }
            } catch(PDOException $e) {
                $errors[] = 'Terjadi kesalahan sistem: ' . $e->getMessage();
            }
        }
    }
    
    // If there are errors, redirect back with error message
    if (!empty($errors)) {
        $_SESSION['upload_errors'] = $errors;
        header('Location: dashboard.php?error=upload_failed');
        exit();
    }
} else {
    // If not POST request, redirect to dashboard
    header('Location: dashboard.php');
    exit();
}
?>