<?php
class DocxImport {
    public static function extractText($filename) {
        $zip = new ZipArchive();
        if ($zip->open($filename) === TRUE) {
            // Try to find document.xml
            if (($index = $zip->locateName('word/document.xml')) !== false) {
                $xml = $zip->getFromIndex($index);
                $zip->close();
                
                $dom = new DOMDocument();
                // Suppress XML errors
                $prev = libxml_use_internal_errors(true);
                $dom->loadXML($xml, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
                libxml_clear_errors();
                libxml_use_internal_errors($prev);

                $text = '';
                // Namespaces
                $w = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
                
                $paragraphs = $dom->getElementsByTagNameNS($w, 'p');
                
                foreach ($paragraphs as $p) {
                    $texts = $p->getElementsByTagNameNS($w, 't');
                    $line = '';
                    foreach ($texts as $t) {
                        $line .= $t->nodeValue;
                    }
                    // Add newline only if line is not empty (or always to preserve structure?)
                    // Always adding newline helps separate blocks
                    $text .= $line . "\n";
                }
                return $text;
            }
            $zip->close();
        }
        return false;
    }

    public static function parse($filename) {
        if (!class_exists('ZipArchive')) {
            return "Error: PHP Zip extension is not enabled. Please enable 'extension=zip' in your php.ini file and restart the server.";
        }
        $text = self::extractText($filename);
        if ($text === false) return "Failed to read .docx file.";

        $lines = explode("\n", $text);
        $questions = [];
        $current_q = [];
        $current_key = null;

        foreach ($lines as $line) {
            $line = trim($line);
            if ($line === '') continue;

            // Check for keys
            // Keys: subject_id, question_type, question_text, points, difficulty, options, correct_indices
            if (preg_match('/^(subject_id|question_type|question_text|points|difficulty|options|correct_indices)\s*[:=]\s*(.*)$/i', $line, $matches)) {
                $key = strtolower($matches[1]);
                $value = trim($matches[2]);

                // Heuristic to detect new question start
                // If we encounter 'subject_id' or 'question_text' and we already have that key in current_q, start new
                if (isset($current_q[$key])) {
                    $questions[] = $current_q;
                    $current_q = [];
                    $current_key = null;
                }
                
                // Also if we encounter subject_id and we have a 'question_text', it's likely a new block
                if ($key == 'subject_id' && !empty($current_q)) {
                     $questions[] = $current_q;
                     $current_q = [];
                     $current_key = null;
                }

                $current_q[$key] = $value;
                $current_key = $key;
            } else {
                // Continuation of previous key value
                if ($current_key && isset($current_q[$current_key])) {
                    $current_q[$current_key] .= " " . $line;
                }
            }
        }
        
        if (!empty($current_q)) {
            $questions[] = $current_q;
        }

        return $questions;
    }
}
