<?php
require_once __DIR__ . '/../includes/functions.php';
requireLogin();

if (isStudent()) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

spl_autoload_register(function ($class) {
    $prefix = 'Smalot\\PdfParser\\';
    $base_dir = __DIR__ . '/../vendor/smalot/pdfparser/src/';
    if (strncmp($prefix, $class, strlen($prefix)) === 0) {
        $file = $base_dir . str_replace('\\', '/', $class) . '.php';
        if (file_exists($file)) { require $file; }
    }
});

$student_id = intval($_POST['student_id'] ?? 0);
requireStudentAccess($student_id);
$student = getStudent($student_id);
if (!$student || !isset($_FILES['pdf_file']) || $_FILES['pdf_file']['error'] !== UPLOAD_ERR_OK) {
    header('Location: ' . BASE_URL . '/students/view.php?id=' . $student_id . '&error=upload_failed');
    exit;
}

$upload_dir = __DIR__ . '/../uploads/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

$filename = 'transfer_' . $student_id . '_' . time() . '.pdf';
$filepath = $upload_dir . $filename;
move_uploaded_file($_FILES['pdf_file']['tmp_name'], $filepath);

// Extract text from PDF
$text = extractTextFromPDF($filepath);

if (empty(trim($text))) {
    header('Location: ' . BASE_URL . '/students/view.php?id=' . $student_id . '&error=no_text');
    exit;
}

// Log the extracted text for debugging
file_put_contents(__DIR__ . '/../uploads/last_extracted_text_' . $student_id . '.txt', $text);

// Parse course data from text
$parsed_courses = parseCoursesFromText($text);

// For each parsed course, try to match with curriculum courses
$db = getDB();
$curriculum_id = $student['curriculum_id'];

// Get all curriculum courses for matching
$curriculum_courses = $db->prepare("
    SELECT c.id, c.code, c.name_th, c.credits, cg.name_th AS group_name
    FROM courses c
    JOIN course_groups cg ON c.group_id = cg.id
    WHERE cg.curriculum_id = ?
");
$curriculum_courses->execute([$curriculum_id]);
$curriculum_map = [];
foreach ($curriculum_courses->fetchAll() as $cc) {
    $curriculum_map[$cc['code']] = $cc;
}

$added = 0;
$skipped = 0;
$check_stmt = $db->prepare("SELECT COUNT(*) FROM student_courses WHERE student_id = ? AND course_code = ? AND source_type = 'transfer'");

foreach ($parsed_courses as $course) {
    $code = $course['code'];

    // Only add courses that match the curriculum
    if (!isset($curriculum_map[$code])) {
        $skipped++;
        continue;
    }

    $cc = $curriculum_map[$code];

    // Skip if already added
    $check_stmt->execute([$student_id, $code]);
    if ($check_stmt->fetchColumn() > 0) {
        $skipped++;
        continue;
    }

    // Add the course as transfer credit
    $stmt = $db->prepare("INSERT INTO student_courses (student_id, course_id, course_code, course_name_th, credits, lecture_hours, practice_hours, self_study_hours, grade, course_type, source_type, source_file) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'S', 'เทียบโอนรายวิชา', 'transfer', ?)");
    $stmt->execute([
        $student_id,
        $cc['id'],
        $code,
        $cc['name_th'],
        $cc['credits'],
        $course['lecture'],
        $course['practice'],
        $course['self_study'],
        $filename
    ]);
    $added++;
}

$msg = $added > 0 ? "added=$added" : "added=0";
header('Location: ' . BASE_URL . '/students/view.php?id=' . $student_id . '&' . $msg);
exit;
