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

header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit();
}

try {
    $user_id = $_SESSION['user_id'];
    $user_role = $_SESSION['user_role'];
    
    // Only students can upload assignment files
    if ($user_role !== 'student') {
        echo json_encode(['success' => false, 'message' => 'Only students can upload assignment files']);
        exit();
    }
    
    // Check if file was uploaded
    if (!isset($_FILES['assignment_file']) || $_FILES['assignment_file']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'message' => 'File upload error']);
        exit();
    }
    
    $file = $_FILES['assignment_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) {
        echo json_encode(['success' => false, 'message' => 'File size exceeds 10MB limit']);
        exit();
    }
    
    // Validate file type
    $allowed_types = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'image/jpeg',
        'image/jpg',
        'image/png',
        'text/plain'
    ];
    
    if (!in_array($file_type, $allowed_types)) {
        echo json_encode(['success' => false, 'message' => 'Unsupported file format. Only PDF, DOC, DOCX, JPG, PNG, TXT files are allowed.']);
        exit();
    }
    
    // Get student ID
    $stmt = $pdo->prepare("SELECT id FROM students WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $student = $stmt->fetch();
    
    if (!$student) {
        echo json_encode(['success' => false, 'message' => 'Student record not found']);
        exit();
    }
    
    $student_id = $student['id'];
    
    // Generate unique filename
    $file_extension = pathinfo($original_name, PATHINFO_EXTENSION);
    $unique_name = 'assignment_' . $student_id . '_' . uniqid() . '_' . time() . '.' . $file_extension;
    
    // Determine upload directory
    $upload_dir = '../uploads/assignments/';
    
    // Create directory if not exists
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    $file_path = $upload_dir . $unique_name;
    $relative_path = 'online_learning/uploads/assignments/' . $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
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $description = 'Assignment submission file';
        $category = 'assignment';
        
        $stmt->execute([
            $user_role, $student_id, $unique_name, $original_name,
            $relative_path, $file_type, $file_size, $category, $description
        ]);
        
        $file_upload_id = $pdo->lastInsertId();
        
        echo json_encode([
            'success' => true, 
            'message' => 'File uploaded successfully',
            'file_upload_id' => $file_upload_id,
            'file_name' => $original_name
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to move uploaded file']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error uploading file: ' . $e->getMessage()]);
}
?>