<?php
session_start();
require_once '../../admin/includes/database.php';
require_once '../../admin/Classes/ELearning.php';

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

$conn = new Database();
$elearning = new ELearning();

if (!isset($_SESSION['student'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

if (isset($_POST['material_id']) && isset($_POST['comment_text'])) {
    $material_id = (int)$_POST['material_id'];
    $comment_text = htmlspecialchars(trim($_POST['comment_text']));

    // Validate comment
    if (empty($comment_text) || strlen($comment_text) < 2) {
        echo json_encode(['success' => false, 'message' => 'Comment is too short']);
        exit();
    }

    if (strlen($comment_text) > 5000) {
        echo json_encode(['success' => false, 'message' => 'Comment is too long (max 5000 characters)']);
        exit();
    }

    // Get student ID and name
    $sql = "SELECT studentID, name FROM student WHERE username = :username";
    $conn->query($sql);
    $conn->bind(':username', $_SESSION['student']);
    $student = $conn->fetchSingle();

    if (!$student) {
        echo json_encode(['success' => false, 'message' => 'Student not found']);
        exit();
    }

    $student_id = $student->studentID;

    // Verify material exists
    $material = $elearning->getMaterialById($material_id);
    if (!$material) {
        echo json_encode(['success' => false, 'message' => 'Material not found']);
        exit();
    }

    // Get student's class and section
    $sql2 = "SELECT classesID, sectionid FROM student WHERE studentID = :student_id";
    $conn->query($sql2);
    $conn->bind(':student_id', $student_id);
    $student_info = $conn->fetchSingle();

    // Verify student has access to this material
    if ($material->class_id != $student_info->classesID || $material->section_id != $student_info->sectionid) {
        echo json_encode(['success' => false, 'message' => 'You do not have access to this material']);
        exit();
    }

    // Add comment
    $result = $elearning->addComment($material_id, $student_id, 'student', $comment_text);

    echo json_encode($result);
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}