<?php
// bible_loader.php
// Efficient Bible data loading using pre-generated indexes

class BibleLoader {
    private $indexDir;
    private $dataFile;
    private $translations = null;
    private $bookIndex = null;

    public function __construct($dataFile = 'bibles.csv', $indexDir = null) {
        $this->dataFile = $dataFile;
        $this->indexDir = $indexDir ?: __DIR__ . '/bible_index/';

        // Check if indexes exist
        if (!is_dir($this->indexDir)) {
            throw new Exception("Bible indexes not found. Please run generate_indexes.php first.");
        }
    }

    // Get list of all translations
    public function getTranslations() {
        if ($this->translations === null) {
            $translationsFile = $this->indexDir . 'translations.json';
            if (!file_exists($translationsFile)) {
                throw new Exception("Translations index not found.");
            }
            $this->translations = json_decode(file_get_contents($translationsFile), true);
        }
        return $this->translations;
    }

    // Get list of all book names
    public function getBookNames() {
        $this->loadBookIndex();
        return array_keys($this->bookIndex);
    }

    // Load book index (only when needed)
    private function loadBookIndex() {
        if ($this->bookIndex === null) {
            $bookIndexFile = $this->indexDir . 'book_index.json';
            if (!file_exists($bookIndexFile)) {
                throw new Exception("Book index not found.");
            }
            $this->bookIndex = json_decode(file_get_contents($bookIndexFile), true);
        }
    }

    // Get verse(s) from a specific book/chapter
    // This loads ONLY the requested book's data, not the entire Bible
    public function getVerses($book, $chapter, $startVerse, $endVerse) {
        $bookFile = $this->indexDir . 'book_' . $this->sanitizeBookName($book) . '.json';

        if (!file_exists($bookFile)) {
            return [];
        }

        // Load only this book's data
        $bookData = json_decode(file_get_contents($bookFile), true);

        if (!isset($bookData[$chapter])) {
            return [];
        }

        $results = [];
        for ($v = $startVerse; $v <= $endVerse; $v++) {
            if (isset($bookData[$chapter][$v])) {
                $results[$v] = $bookData[$chapter][$v];
            }
        }

        return $results;
    }

    // Search for keyword across all books
    // This is slower as it needs to check all books, but still more efficient
    // than loading everything into memory at once
    public function searchKeyword($keyword, $selectedTranslations = null) {
        $keywordLower = strtolower($keyword);
        $results = [];
        $bookNames = $this->getBookNames();
        $translations = $this->getTranslations();

        foreach ($bookNames as $book) {
            $bookFile = $this->indexDir . 'book_' . $this->sanitizeBookName($book) . '.json';

            if (!file_exists($bookFile)) {
                continue;
            }

            // Load one book at a time
            $bookData = json_decode(file_get_contents($bookFile), true);

            if (!$bookData) {
                continue; // Skip empty or malformed book files
            }

            foreach ($bookData as $chapter => $verses) {
                foreach ($verses as $verse => $texts) {
                    // Check selected translations
                    if ($selectedTranslations === null) {
                        $transIndexes = array_keys($texts);
                    } else {
                        $transIndexes = $selectedTranslations;
                    }

                    foreach ($transIndexes as $transIndex) {
                        if (isset($texts[$transIndex])) {
                            $text = $texts[$transIndex];
                            if (stripos($text, $keywordLower) !== false) {
                                $results[] = [
                                    'book' => $book,
                                    'chapter' => $chapter,
                                    'verse' => $verse,
                                    'translation_index' => $transIndex,
                                    'translation' => $translations[$transIndex],
                                    'text' => $text
                                ];
                            }
                        }
                    }
                }
            }

            // Free memory after each book
            unset($bookData);
        }

        return $results;
    }

    // Helper function to create safe filenames from book names
    private function sanitizeBookName($bookName) {
        return str_replace([' ', "'"], ['_', ''], strtolower($bookName));
    }

    // Check if indexes are up to date
    public function indexesExist() {
        return is_dir($this->indexDir) &&
               file_exists($this->indexDir . 'translations.json') &&
               file_exists($this->indexDir . 'book_index.json');
    }

    // Get index directory path
    public function getIndexDir() {
        return $this->indexDir;
    }
}
