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

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

// Check if user is logged in and is admin/teacher
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'teacher')) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

try {
    $user_id = $_SESSION['user_id'];
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    if (!$input || !isset($input['title']) || !isset($input['class_id']) || !isset($input['subject_id']) || 
        !isset($input['category']) || !isset($input['file_upload_id'])) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit();
    }
    
    $title = trim($input['title']);
    $description = isset($input['description']) ? trim($input['description']) : '';
    $class_id = (int)$input['class_id'];
    $subject_id = (int)$input['subject_id'];
    $category = $input['category'];
    $file_upload_id = (int)$input['file_upload_id'];
    $allow_download = isset($input['allow_download']) ? (int)$input['allow_download'] : 1;
    $allow_share = isset($input['allow_share']) ? (int)$input['allow_share'] : 1;
    $allow_print = isset($input['allow_print']) ? (int)$input['allow_print'] : 1;
    $access_control = isset($input['access_control']) ? $input['access_control'] : 'all';
    $specific_student_ids = isset($input['specific_student_ids']) ? $input['specific_student_ids'] : [];
    $specific_student_ids = isset($input['specific_student_ids']) ? $input['specific_student_ids'] : [];
    
    // Validate category
    $valid_categories = ['lecture_notes', 'presentation', 'video_lecture', 'audio_lecture', 'assignment', 'practice_questions'];
    if (!in_array($category, $valid_categories)) {
        echo json_encode(['success' => false, 'message' => 'Invalid category']);
        exit();
    }
    
    // Validate access control
    $valid_access_controls = ['all', 'class_only', 'specific_students'];
    if (!in_array($access_control, $valid_access_controls)) {
        echo json_encode(['success' => false, 'message' => 'Invalid access control option']);
        exit();
    }
    
    // Validate class exists
    $stmt = $pdo->prepare("SELECT id FROM classes WHERE id = ?");
    $stmt->execute([$class_id]);
    if (!$stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'Invalid class']);
        exit();
    }
    
    // Validate subject exists
    $stmt = $pdo->prepare("SELECT id FROM subjects WHERE id = ?");
    $stmt->execute([$subject_id]);
    if (!$stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'Invalid subject']);
        exit();
    }
    
    // Validate file upload exists
    $stmt = $pdo->prepare("SELECT id FROM file_uploads WHERE id = ? AND status = 'active'");
    $stmt->execute([$file_upload_id]);
    if (!$stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'Invalid file upload']);
        exit();
    }
    
    // Insert learning material
    $stmt = $pdo->prepare("
        INSERT INTO learning_materials 
        (title, description, class_id, subject_id, category, file_upload_id, allow_download, allow_share, allow_print, access_control, created_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $result = $stmt->execute([
        $title, $description, $class_id, $subject_id, $category, $file_upload_id,
        $allow_download, $allow_share, $allow_print, $access_control, $user_id
    ]);
    
    if ($result) {
        $material_id = $pdo->lastInsertId();
        
        // If access control is specific_students, insert the specific student IDs
        if ($access_control === 'specific_students' && !empty($specific_student_ids)) {
            try {
                $pdo->beginTransaction();
                
                // Insert specific student IDs
                $stmt = $pdo->prepare("INSERT INTO learning_materials_specific_students (material_id, student_id) VALUES (?, ?)");
                foreach ($specific_student_ids as $student_id) {
                    $stmt->execute([$material_id, (int)$student_id]);
                }
                
                $pdo->commit();
            } catch (Exception $e) {
                $pdo->rollback();
                // Log error but don't fail the entire operation
                error_log("Error inserting specific students for material $material_id: " . $e->getMessage());
            }
        }
        
        echo json_encode(['success' => true, 'message' => 'Learning material added successfully', 'material_id' => $material_id]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to add learning material']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error adding learning material: ' . $e->getMessage()]);
}
?>