<?php

session_start();

if (!isset($_SESSION['user_id'])) {

    header('Location: ../index.php');

    exit;

}



require_once '../config.php';

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



use Smalot\PdfParser\Parser;



// Handle AJAX requests FIRST

if (isset($_POST['action']) && $_POST['action'] == 'extract_text') {

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

    @set_time_limit(30);

    

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

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

        exit;

    }

    

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

    

    if (!$material_id) {

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

        exit;

    }

    

    $conn = getDBConnection();

    

    // Get material details

    $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']);

        $conn->close();

        exit;

    }

    

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

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

        $conn->close();

        exit;

    }

    

    $extracted_text = '';

    $extraction_method = 'smalot_pdfparser';

    $absoluteFile = '../' . $material['file_path'];

    $maxExtractSize = 8 * 1024 * 1024;



    try {

        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);

        $extracted_text = trim(preg_replace('/\s+/', ' ', $pdf->getText()));

    } catch (Throwable $e) {

        echo json_encode(['success' => false, 'message' => 'Text extraction failed: ' . $e->getMessage()]);

        $conn->close();

        exit;

    }

    

    // Update the material with extracted text (store in extracted_text column)

    $updateQuery = "UPDATE learning_materials SET extracted_text = ? WHERE id = ?";

    $updateStmt = $conn->prepare($updateQuery);

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

    $updateSuccess = $updateStmt->execute();

    $updateStmt->close();

    

    if ($updateSuccess) {

        echo json_encode([

            'success' => true,

            'message' => 'Text extracted successfully',

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

            'length' => strlen($extracted_text),

            'method' => $extraction_method,

            'pages' => count($pages ?? [])

        ]);

    } else {

        echo json_encode(['success' => false, 'message' => 'Failed to update database']);

    }

    

    $conn->close();

    exit;

}



// Handle form submission (regular POST)

if ($_SERVER['REQUEST_METHOD'] == 'POST' && !isset($_POST['action'])) {

    $class_name = $_POST['class_name'] ?? '';

    $subject_id = $_POST['subject_id'] ?? '';

    $material_type = $_POST['material_type'] ?? '';

    $title = $_POST['title'] ?? '';

    $content = $_POST['content'] ?? '';

    

    // Handle file upload

    $file_path = '';

    $file_size = 0;

    $extracted_text = '';

    

    if (isset($_FILES['material_file']) && $_FILES['material_file']['error'] == 0) {

        $target_dir = 'uploads/materials/';

        if (!is_dir($target_dir)) {

            mkdir($target_dir, 0777, true);

        }

        

        $file_name = time() . '_' . basename($_FILES['material_file']['name']);

        $target_file = $target_dir . $file_name;

        $file_size = $_FILES['material_file']['size'];

        $file_ext = strtolower(pathinfo($_FILES['material_file']['name'], PATHINFO_EXTENSION));

        

        if (move_uploaded_file($_FILES['material_file']['tmp_name'], $target_file)) {

            $file_path = $target_file;



            // Do not extract PDF text during the upload request.

            // Large PDFs can exceed PHP execution time limits and block the upload entirely.

            if ($file_ext == 'pdf') {

                $extracted_text = '';

            }

        }

    }

    

    if ($class_name && $subject_id && $title) {

        $conn = getDBConnection();

        

        // Insert with both content and extracted_text

        $query = "INSERT INTO learning_materials 

                  (class_name, subject_id, material_type, title, content, extracted_text, file_path, file_size, uploaded_by) 

                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

        

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

        $stmt->bind_param("sisssssii", 

            $class_name, 

            $subject_id, 

            $material_type, 

            $title, 

            $content, 

            $extracted_text, 

            $file_path, 

            $file_size, 

            $_SESSION['user_id']

        );

        

        if ($stmt->execute()) {

            $material_id = $stmt->insert_id;

            $message = "Material uploaded successfully!";

            $messageType = "success";

            

            if ($file_ext === 'pdf') {

                $message .= " PDF uploaded successfully. Text extraction can be done afterward if needed.";

            } elseif (!empty($extracted_text)) {

                $message .= " Text saved successfully.";

            }

        } else {

            $message = "Error uploading material: " . $stmt->error;

            $messageType = "danger";

        }

        $stmt->close();

    } else {

        $message = "Please fill all required fields";

        $messageType = "danger";

    }

}



// Get classes and subjects

$conn = getDBConnection();

$classes = [];

$_cr = $conn->query("SELECT class_name FROM classes WHERE is_active = 1 ORDER BY class_name");

if ($_cr) { while ($_row = $_cr->fetch_assoc()) $classes[] = $_row['class_name']; }

$subjects = [];

$result = $conn->query("SELECT id, subject_name FROM subjects WHERE active = 'yes' OR active = 1 ORDER BY subject_name");

while ($row = $result->fetch_assoc()) {

    $subjects[] = $row;

}



// Get recent uploads - show extracted_text status

$recentUploads = [];

$result = $conn->query("SELECT lm.*, s.subject_name, u.full_name as uploader 

                        FROM learning_materials lm

                        LEFT JOIN subjects s ON lm.subject_id = s.id

                        LEFT JOIN users u ON lm.uploaded_by = u.id

                        ORDER BY lm.uploaded_at DESC LIMIT 20");

while ($row = $result->fetch_assoc()) {

    $recentUploads[] = $row;

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Upload Learning Materials - EduTrack PRO</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <link rel="stylesheet" href="../css/style.css">

    <style>

        .upload-container { max-width: 1400px; margin: 30px auto; padding: 20px; }

        .form-card { background: white; border-radius: 15px; padding: 25px; box-shadow: 0 5px 20px rgba(0,0,0,0.1); }

        .material-item { 

            background: white; 

            padding: 15px; 

            border-radius: 8px; 

            margin-bottom: 10px; 

            border-left: 4px solid #28a745;

            transition: all 0.3s;

        }

        .material-item:hover { box-shadow: 0 5px 15px rgba(0,0,0,0.1); }

        .material-pdf { border-left-color: #dc3545; }

        .material-extracted { border-left-color: #28a745; background-color: #f0fff0; }

        .extract-btn { transition: all 0.3s; }

        .text-preview { 

            max-height: 60px; 

            overflow: hidden; 

            font-size: 12px; 

            color: #666;

            background: #f8f9fa;

            padding: 8px;

            border-radius: 4px;

            margin-top: 8px;

        }

        .stats-badge {

            font-size: 11px;

            padding: 3px 8px;

            border-radius: 12px;

            background: #e9ecef;

            margin-left: 5px;

        }

    </style>

</head>

<body>

    <div class="wrapper">

        <!-- Sidebar -->

        <nav id="sidebar" class="sidebar">

        <?php echo buildSidebar('exams_generator/' . basename($_SERVER['PHP_SELF'])); ?>

        </nav>



        <!-- Main Content -->

        <div class="main-content">

            <header class="header">

                <button class="btn-toggle" id="sidebarToggle">

                    <i class="fas fa-bars"></i>

                </button>

                <div class="header-right">

                    <div class="dropdown">

                        <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">

                            <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string) ($_SESSION['full_name'] ?? '')); ?>

                        </button>

                        <ul class="dropdown-menu dropdown-menu-end">

                            <li><a class="dropdown-item" href="../logout.php">Logout</a></li>

                        </ul>

                    </div>

                </div>

            </header>



            <main class="content">

                <div class="upload-container">

                    <!-- Header -->

                    <div class="d-flex justify-content-between align-items-center mb-4">

                        <h2><i class="fas fa-upload text-primary me-2"></i>Upload Learning Materials</h2>

                        <a href="index.php" class="btn btn-outline-primary">

                            <i class="fas fa-arrow-left me-2"></i>Back to Exam Generator

                        </a>

                    </div>



                    <?php if (isset($message)): ?>

                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show">

                        <?php echo $message; ?>

                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>

                    </div>

                    <?php endif; ?>



                    <!-- Info Notice -->

                    <div class="alert alert-info mb-4">

                        <i class="fas fa-info-circle me-2"></i>

                        <strong>Auto-Extraction Active:</strong> PDF text is automatically extracted during upload. 

                        No manual extraction needed!

                    </div>



                    <div class="row">

                        <!-- Upload Form -->

                        <div class="col-md-5">

                            <div class="form-card">

                                <h4 class="mb-4"><i class="fas fa-cloud-upload-alt me-2"></i>Upload New Material</h4>

                                

                                <form method="POST" enctype="multipart/form-data">

                                    <div class="mb-3">

                                        <label class="form-label fw-bold">Class <span class="text-danger">*</span></label>

                                        <select name="class_name" class="form-select" required>

                                            <option value="">Select Class</option>

                                            <?php foreach($classes as $class): ?>

                                            <option value="<?php echo $class; ?>"><?php echo $class; ?></option>

                                            <?php endforeach; ?>

                                        </select>

                                    </div>

                                    

                                    <div class="mb-3">

                                        <label class="form-label fw-bold">Subject <span class="text-danger">*</span></label>

                                        <select name="subject_id" class="form-select" required>

                                            <option value="">Select Subject</option>

                                            <?php foreach($subjects as $subject): ?>

                                            <option value="<?php echo $subject['id']; ?>"><?php echo $subject['subject_name']; ?></option>

                                            <?php endforeach; ?>

                                        </select>

                                    </div>

                                    

                                    <div class="mb-3">

                                        <label class="form-label fw-bold">Material Type</label>

                                        <select name="material_type" class="form-select">

                                            <option value="textbook">📚 Textbook</option>

                                            <option value="lesson_note">📝 Lesson Note</option>

                                            <option value="syllabus">📋 Syllabus</option>

                                            <option value="past_question">📄 Past Question</option>

                                            <option value="reference">🔖 Reference Material</option>

                                        </select>

                                    </div>

                                    

                                    <div class="mb-3">

                                        <label class="form-label fw-bold">Title <span class="text-danger">*</span></label>

                                        <input type="text" name="title" class="form-control" required 

                                               placeholder="e.g., Social Studies Methodology for JHS 3">

                                    </div>

                                    

                                    <div class="mb-3">

                                        <label class="form-label fw-bold">Manual Content (Optional)</label>

                                        <textarea name="content" class="form-control" rows="4" 

                                                  placeholder="Paste text here if you prefer manual entry..."></textarea>

                                    </div>

                                    

                                    <div class="mb-3">

                                        <label class="form-label fw-bold">Upload PDF File <span class="text-danger">*</span></label>

                                        <input type="file" name="material_file" class="form-control" accept=".pdf" required>

                                        <small class="text-muted">

                                            <i class="fas fa-check-circle text-success me-1"></i>

                                            PDF will upload immediately without blocking on text extraction

                                        </small>

                                    </div>

                                    

                                    <button type="submit" class="btn btn-primary w-100">

                                        <i class="fas fa-upload me-2"></i>Upload Material

                                    </button>

                                </form>

                            </div>

                        </div>

                        

                        <!-- Recent Uploads -->

                        <div class="col-md-7">

                            <div class="form-card">

                                <h4 class="mb-4"><i class="fas fa-history me-2"></i>Recent Uploads</h4>

                                

                                <?php if (empty($recentUploads)): ?>

                                <p class="text-muted text-center py-4">No materials uploaded yet.</p>

                                <?php else: ?>

                                    <div style="max-height: 600px; overflow-y: auto;">

                                        <?php foreach($recentUploads as $material): 

                                            $file_ext = $material['file_path'] ? strtolower(pathinfo($material['file_path'], PATHINFO_EXTENSION)) : '';

                                            $hasExtracted = !empty($material['extracted_text']) && strlen($material['extracted_text']) > 100;

                                            $materialClass = $hasExtracted ? 'material-extracted' : ($file_ext == 'pdf' ? 'material-pdf' : '');

                                        ?>

                                        <div class="material-item <?php echo $materialClass; ?>" id="material-<?php echo $material['id']; ?>">

                                            <div class="d-flex justify-content-between align-items-start">

                                                <div>

                                                    <strong><?php echo htmlspecialchars($material['title']); ?></strong>

                                                    <div class="mt-1">

                                                        <span class="badge bg-info"><?php echo $material['class_name']; ?></span>

                                                        <span class="badge bg-secondary"><?php echo $material['subject_name']; ?></span>

                                                        <span class="badge bg-success"><?php echo $material['material_type']; ?></span>

                                                    </div>

                                                </div>

                                                <small class="text-muted"><?php echo date('d M Y', strtotime($material['uploaded_at'])); ?></small>

                                            </div>

                                            

                                            <?php if ($material['file_path']): ?>

                                            <div class="mt-2">

                                                <small class="text-muted">

                                                    <i class="fas fa-file me-1"></i><?php echo basename($material['file_path']); ?> 

                                                    (<?php echo round($material['file_size'] / 1024); ?> KB)

                                                </small>

                                            </div>

                                            <?php endif; ?>

                                            

                                            <div class="mt-2">

                                                <?php if ($hasExtracted): ?>

                                                <span class="badge bg-success">

                                                    <i class="fas fa-check-circle me-1"></i>

                                                    Extracted (<?php echo round(strlen($material['extracted_text']) / 1000); ?>K chars)

                                                </span>

                                                <span class="stats-badge">

                                                    <?php echo substr_count($material['extracted_text'], "\n\n"); ?> pages

                                                </span>

                                                <?php else: ?>

                                                <span class="badge bg-warning">

                                                    <i class="fas fa-hourglass-half me-1"></i>

                                                    Pending Extraction

                                                </span>

                                                <?php endif; ?>

                                            </div>

                                            

                                            <?php if ($hasExtracted): ?>

                                            <div class="text-preview">

                                                <?php echo htmlspecialchars(substr($material['extracted_text'], 0, 300)); ?>...

                                            </div>

                                            <?php endif; ?>

                                        </div>

                                        <?php endforeach; ?>

                                    </div>

                                <?php endif; ?>

                            </div>

                        </div>

                    </div>

                </div>

            </main>

        </div>

    </div>



    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

</body>

</html>

