<?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'])) {
    $material_id = (int)$_POST['material_id'];
    $status = isset($_POST['status']) ? $_POST['status'] : 'in_progress';
    $time_spent = isset($_POST['time_spent']) ? (int)$_POST['time_spent'] : 0;
    $progress_percentage = isset($_POST['progress_percentage']) ? (float)$_POST['progress_percentage'] : 50;

    // Get student ID
    $sql = "SELECT studentID 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 and student has access
    $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();
    }

    // Validate status
    if (!in_array($status, ['not_started', 'in_progress', 'completed'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid status']);
        exit();
    }

    // Validate progress percentage
    if ($progress_percentage < 0 || $progress_percentage > 100) {
        echo json_encode(['success' => false, 'message' => 'Invalid progress percentage']);
        exit();
    }

    // Update or insert progress
    $progress_data = [
        'status' => $status,
        'progress_percentage' => $progress_percentage,
        'time_spent' => $time_spent
    ];

    $result = $elearning->updateProgress($student_id, $material_id, $progress_data);

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