<?php

session_start();

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {

    echo json_encode(['success' => false, 'message' => 'Unauthorized']);

    exit;

}



require_once '../config.php';
require_once '../../vendor/autoload.php';

use Smalot\PdfParser\Parser;

@set_time_limit(30);


$material_id = intval($_POST['id'] ?? 0);



if (!$material_id) {

    echo json_encode(['success' => false, 'message' => 'Invalid material ID']);

    exit;

}



$conn = getDBConnection();

$query = "SELECT * FROM learning_materials WHERE id = ?";

$stmt = $conn->prepare($query);

$stmt->bind_param("i", $material_id);

$stmt->execute();

$result = $stmt->get_result();

$material = $result->fetch_assoc();

$stmt->close();



if (!$material) {

    echo json_encode(['success' => false, 'message' => 'Material not found']);

    exit;

}



if (empty($material['file_path']) || !file_exists('../' . $material['file_path'])) {

    echo json_encode(['success' => false, 'message' => 'PDF file not found']);

    exit;

}



try {
    $absoluteFile = '../' . $material['file_path'];
    $maxExtractSize = 8 * 1024 * 1024;
    if (@filesize($absoluteFile) > $maxExtractSize) {
        throw new RuntimeException('PDF is too large for inline extraction. Use a smaller PDF or extract it offline.');
    }

    $parser = new Parser();
    $pdf = $parser->parseFile($absoluteFile);
    $text = trim(preg_replace('/\s+/', ' ', $pdf->getText()));
    

    // Save to database

    $updateStmt = $conn->prepare("UPDATE learning_materials SET extracted_text = ? WHERE id = ?");

    $updateStmt->bind_param("si", $text, $material_id);

    $updateStmt->execute();

    $updateStmt->close();

    

    echo json_encode([

        'success' => true,

        'message' => 'Text extracted successfully',

        'preview' => substr($text, 0, 500) . '...',

        'length' => strlen($text)

    ]);

    

} catch (Exception $e) {

    echo json_encode(['success' => false, 'message' => 'Error extracting text: ' . $e->getMessage()]);

}



$conn->close();

?>
