<?php
// bible_website.php
// Bib version 4.0 by Amfile.org
// This PHP script creates a website for querying Bible verses from a TSV file.
// It supports queries by book/chapter/verse with context verses and keyword searches, with translation selection.
// Version 4.0: Major performance optimization using indexed data loading

// Counter files
$counterDir = __DIR__ . '/counters/';
if (!is_dir($counterDir)) {
    mkdir($counterDir, 0755, true);
}

$totalHitsFile = $counterDir . 'total_hits.txt';
$humanHitsFile = $counterDir . 'human_hits.txt';
$searchCountFile = $counterDir . 'search_count.txt';
$ipLogFile = $counterDir . 'unique_ips.txt';
$humanIpLogFile = $counterDir . 'unique_human_ips.txt';

// Initialize counter files if they don't exist
if (!file_exists($totalHitsFile)) file_put_contents($totalHitsFile, '0');
if (!file_exists($humanHitsFile)) file_put_contents($humanHitsFile, '0');
if (!file_exists($searchCountFile)) file_put_contents($searchCountFile, '0');
if (!file_exists($ipLogFile)) file_put_contents($ipLogFile, '');
if (!file_exists($humanIpLogFile)) file_put_contents($humanIpLogFile, '');

// Function to detect if visitor is a bot
function isBot() {
    if (!isset($_SERVER['HTTP_USER_AGENT'])) return true;

    $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
    $botPatterns = [
        'bot', 'crawl', 'spider', 'slurp', 'google', 'bing', 'yahoo',
        'baidu', 'yandex', 'duckduck', 'facebook', 'twitter', 'whatsapp',
        'telegram', 'slack', 'discord', 'preview', 'parser', 'scraper',
        'curl', 'wget', 'python', 'java', 'perl', 'ruby', 'php'
    ];

    foreach ($botPatterns as $pattern) {
        if (strpos($userAgent, $pattern) !== false) {
            return true;
        }
    }
    return false;
}

// Function to get visitor IP
function getVisitorIP() {
    $ipKeys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED',
               'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'];
    foreach ($ipKeys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = $_SERVER[$key];
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                return $ip;
            }
        }
    }
    return 'unknown';
}

// Increment hit counters
$totalHits = (int)file_get_contents($totalHitsFile);
$totalHits++;
file_put_contents($totalHitsFile, $totalHits);

// Get visitor IP
$visitorIP = getVisitorIP();
$isHuman = !isBot();

// Track human hits and unique human IPs
$humanHits = (int)file_get_contents($humanHitsFile);
if ($isHuman) {
    $humanHits++;
    file_put_contents($humanHitsFile, $humanHits);

    // Track unique human IPs
    $humanIpLog = file_get_contents($humanIpLogFile);
    $humanIps = array_filter(explode("\n", $humanIpLog));

    if (!in_array($visitorIP, $humanIps)) {
        file_put_contents($humanIpLogFile, $visitorIP . "\n", FILE_APPEND);
        $humanIps[] = $visitorIP;
    }
    $uniqueHumans = count($humanIps);
} else {
    // Just count existing unique humans if visitor is a bot
    $humanIpLog = file_get_contents($humanIpLogFile);
    $humanIps = array_filter(explode("\n", $humanIpLog));
    $uniqueHumans = count($humanIps);
}

// Read search count
$searchCount = (int)file_get_contents($searchCountFile);

// Include the efficient Bible loader
require_once 'bible_loader.php';

// Initialize the Bible loader
try {
    $bibleLoader = new BibleLoader('bibles.csv');

    // Check if indexes exist, if not show error message
    if (!$bibleLoader->indexesExist()) {
        die('<h1>Setup Required</h1><p>Bible indexes not found. Please run <code>php generate_indexes.php</code> from the command line to generate the indexes first.</p>');
    }

    // Load only the metadata (translations and book names) - FAST!
    $translations = $bibleLoader->getTranslations();
    $bookNames = $bibleLoader->getBookNames();

} catch (Exception $e) {
    die('<h1>Error</h1><p>' . htmlspecialchars($e->getMessage()) . '</p><p>Please run <code>php generate_indexes.php</code> to generate the Bible indexes.</p>');
}

// Create translation abbreviations mapping
$translationAbbrev = [
    'King James Bible' => 'KJV',
    'American Standard Version' => 'ASV',
    'Douay-Rheims Bible' => 'DRB',
    'Darby Bible Translation' => 'DBT',
    'English Revised Version' => 'ERV',
    'Webster Bible Translation' => 'WBT',
    'World English Bible' => 'WEB',
    'Young\'s Literal Translation' => 'YLT',
    'American King James Version' => 'AKJ',
    'Weymouth New Testament' => 'WNT'
];

// Handle CSV download
if (isset($_GET['download_csv']) && isset($_GET['csv_data'])) {
    $csvData = json_decode(base64_decode($_GET['csv_data']), true);
    if ($csvData) {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="bible_search_results.csv"');
        $output = fopen('php://output', 'w');
        fputcsv($output, ['Verse Reference', 'Translation', 'Text']);
        foreach ($csvData as $row) {
            fputcsv($output, [$row['verse_ref'], $row['translation'], $row['text']]);
        }
        fclose($output);
        exit;
    }
}

// Handle form submissions
$results = [];
$queryType = isset($_GET['query_type']) ? $_GET['query_type'] : 'verse';

// Default to WEB (World English Bible) only - index 6
$webIndex = array_search('World English Bible', $translations);
$defaultTranslations = $webIndex !== false ? [$webIndex] : [6];
$selectedTranslations = isset($_GET['translations']) ? $_GET['translations'] : $defaultTranslations;
if (!is_array($selectedTranslations)) $selectedTranslations = [$selectedTranslations];

// Initialize variables for form fields
$book = isset($_GET['book']) ? trim($_GET['book']) : '';
$chapter = isset($_GET['chapter']) ? (int)$_GET['chapter'] : 1;
$verse = isset($_GET['verse']) ? (int)$_GET['verse'] : 1;
$versesBefore = isset($_GET['verses_before']) ? (int)$_GET['verses_before'] : 0;
$versesAfter = isset($_GET['verses_after']) ? (int)$_GET['verses_after'] : 0;
$keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Increment search counter if a search is being performed
    $isSearch = ($book != '') || ($keyword != '');
    if ($isSearch) {
        $searchCount++;
        file_put_contents($searchCountFile, $searchCount);
    }

    if ($queryType === 'verse') {

        if ($book && $chapter && $verse) {
            // Fetch verses in the range [verse - versesBefore, verse + versesAfter]
            $startVerse = max(1, $verse - $versesBefore);
            $endVerse = $verse + $versesAfter;

            // Load only the verses we need from this specific book/chapter
            $verses = $bibleLoader->getVerses($book, $chapter, $startVerse, $endVerse);

            foreach ($verses as $v => $verseData) {
                foreach ($selectedTranslations as $transIndex) {
                    $transIndex = (int)$transIndex; // Ensure index is integer
                    if (isset($verseData[$transIndex])) {
                        $transName = $translations[$transIndex];
                        $results[] = [
                            'verse_ref' => "$book $chapter:$v",
                            'translation' => $transName,
                            'text' => $verseData[$transIndex]
                        ];
                    }
                }
            }
        }
    } elseif ($queryType === 'keyword') {
        if ($keyword) {
            // Use the efficient search that loads one book at a time
            $searchResults = $bibleLoader->searchKeyword($keyword, $selectedTranslations);

            foreach ($searchResults as $result) {
                $results[] = [
                    'verse_ref' => $result['book'] . ' ' . $result['chapter'] . ':' . $result['verse'],
                    'translation' => $result['translation'],
                    'text' => $result['text']
                ];
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bib 4.0 by Amfile.org</title>
    <meta name="description" content="Search and explore the Bible with multiple translations. Bib 4.0 offers verse lookup, keyword search, and easy sharing across 10 Bible translations including KJV, ASV, and YLT.">

    <?php
    // Detect protocol (fix for when REQUEST_SCHEME is not set)
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
                (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) ||
                (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') ||
                (!empty($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] === 'https')
                ? 'https' : 'http';
    $baseUrl = $protocol . '://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/');
    $currentUrl = $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $ogImageUrl = $baseUrl . '/logo-og.jpg?v=' . filemtime(__DIR__ . '/logo-og.jpg');
    ?>
    <!-- Open Graph / Facebook / Telegram -->
    <meta property="og:type" content="website">
    <meta property="og:url" content="<?php echo htmlspecialchars($currentUrl); ?>">
    <meta property="og:title" content="Bib 4.0 - Bible Search by Amfile.org">
    <meta property="og:description" content="Search the Bible with multiple translations including KJV, ASV, YLT and more. Easy verse lookup and keyword search.">
    <meta property="og:image" content="<?php echo htmlspecialchars($ogImageUrl); ?>">
    <meta property="og:image:secure_url" content="<?php echo htmlspecialchars(str_replace('http://', 'https://', $ogImageUrl)); ?>">
    <meta property="og:image:width" content="815">
    <meta property="og:image:height" content="510">
    <meta property="og:image:type" content="image/jpeg">
    <meta property="og:image:alt" content="Bib 4.0 - Bible Search Tool Logo">

    <!-- Twitter -->
    <meta property="twitter:card" content="summary_large_image">
    <meta property="twitter:url" content="<?php echo htmlspecialchars($currentUrl); ?>">
    <meta property="twitter:title" content="Bib 4.0 - Bible Search by Amfile.org">
    <meta property="twitter:description" content="Search the Bible with multiple translations including KJV, ASV, YLT and more. Easy verse lookup and keyword search.">
    <meta property="twitter:image" content="<?php echo htmlspecialchars($ogImageUrl); ?>">

    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Bib 4.0 by <a href="https://amfile.org" target="_blank" rel="noopener noreferrer" class="header-link">Amfile.org</a> <a href="changelog.php" style="font-size: 0.5em; text-decoration: none; color: #888;" title="View changelog">📋</a></h1>
    <div class="stats-bar">
        <span class="stat-item" title="Total page visits">Total Hits: <?php echo number_format($totalHits); ?></span>
        <span class="stat-item" title="Page visits excluding bots">Human Hits: <?php echo number_format($humanHits); ?></span>
        <span class="stat-item" title="Unique human visitors (by IP address)">Unique Humans: <?php echo number_format($uniqueHumans); ?></span>
        <span class="stat-item" title="Searches performed since November 19, 2025">Searches: <?php echo number_format($searchCount); ?></span>
        <a href="changelog.php" class="stat-item" style="cursor: pointer; text-decoration: none;" title="View version history and changelog">Changelog</a>
    </div>
    
    <form method="GET">
        <!-- Line 1: Query Type Selection -->
        <div class="form-line">
            <label>Query Type:</label>
            <label class="radio-inline"><input type="radio" name="query_type" value="verse" <?php echo $queryType === 'verse' ? 'checked' : ''; ?>> Verse Reference</label>
            <label class="radio-inline"><input type="radio" name="query_type" value="keyword" <?php echo $queryType === 'keyword' ? 'checked' : ''; ?>> Keyword Search</label>
        </div>

        <!-- Line 2: Query Parameters -->
        <div class="form-line">
            <!-- Verse Query Fields -->
            <div id="verse_fields" class="query-fields" style="display: <?php echo $queryType === 'verse' ? 'flex' : 'none'; ?>;">
                <div class="field-inline">
                    <label>Book:</label>
                    <select name="book">
                        <option value="">-- Select --</option>
                        <?php foreach ($bookNames as $bookName): ?>
                            <option value="<?php echo htmlspecialchars($bookName); ?>" <?php echo (isset($book) && $book === $bookName) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($bookName); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="field-inline">
                    <label>Ch:</label>
                    <input type="number" name="chapter" value="<?php echo isset($chapter) ? $chapter : '1'; ?>" placeholder="1" min="1">
                </div>
                <div class="field-inline">
                    <label>V:</label>
                    <input type="number" name="verse" value="<?php echo isset($verse) ? $verse : '1'; ?>" placeholder="1" min="1">
                </div>
                <div class="field-inline">
                    <label>Before:</label>
                    <input type="number" name="verses_before" value="<?php echo isset($verses_before) ? $verses_before : '1'; ?>" placeholder="1" min="0">
                </div>
                <div class="field-inline">
                    <label>After:</label>
                    <input type="number" name="verses_after" value="<?php echo isset($verses_after) ? $verses_after : '1'; ?>" placeholder="1" min="0">
                </div>
            </div>

            <!-- Keyword Query Fields -->
            <div id="keyword_fields" class="query-fields" style="display: <?php echo $queryType === 'keyword' ? 'flex' : 'none'; ?>;">
                <div class="field-inline" style="flex: 1;">
                    <label>Keyword:</label>
                    <input type="text" name="keyword" value="<?php echo htmlspecialchars($keyword); ?>" placeholder="e.g., beginning">
                </div>
            </div>
        </div>

        <!-- Line 3: Translation Selection -->
        <div class="form-line">
            <label>Translations:</label>
            <div class="checkbox-group">
                <?php foreach ($translations as $index => $trans): ?>
                    <?php $abbrev = isset($translationAbbrev[$trans]) ? $translationAbbrev[$trans] : substr($trans, 0, 3); ?>
                    <label class="checkbox-inline translation-checkbox" title="<?php echo htmlspecialchars($trans); ?>">
                        <input type="checkbox" name="translations[]" value="<?php echo $index; ?>"
                            <?php echo in_array($index, $selectedTranslations) ? 'checked' : ''; ?>>
                        <span class="translation-abbrev"><?php echo htmlspecialchars($abbrev); ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
        </div>

        <input type="submit" value="Query">
    </form>
    
    <?php if (!empty($results)): ?>
        <div class="results-container">
            <div class="results-header">
                <h2 style="margin: 0;">Results</h2>
                <div style="display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;">
                    <span class="result-count" id="resultCount"><?php echo count($results); ?> results</span>
                    <button type="button" onclick="copyQueryURL(event)" style="width: auto; padding: 0.6rem 1.2rem; font-size: 1.1rem;">Copy URL</button>
                    <button type="button" onclick="downloadCSV()" style="width: auto; padding: 0.6rem 1.2rem; font-size: 1.1rem;">Download CSV</button>
                </div>
            </div>

            <div class="filter-controls">
                <label for="filterInput">Filter results:</label>
                <input type="text" id="filterInput" placeholder="Type to filter..." onkeyup="filterResults()">
                <select id="filterColumn" onchange="filterResults()" style="width: auto; padding: 0.5rem;">
                    <option value="all">All columns</option>
                    <option value="0">Verse Reference</option>
                    <option value="1">Translation</option>
                    <option value="2">Text</option>
                </select>
            </div>

            <table id="resultsTable">
                <thead>
                    <tr>
                        <th>Verse Reference</th>
                        <th>Translation</th>
                        <th>Text</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($results as $result): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($result['verse_ref']); ?></td>
                            <td><?php echo htmlspecialchars($result['translation']); ?></td>
                            <td><?php echo html_entity_decode($result['text'], ENT_QUOTES | ENT_HTML5, 'UTF-8'); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && (isset($_GET['book']) || isset($_GET['keyword']))): ?>
        <p>No results found.</p>
    <?php endif; ?>

    <!-- Floating Notes Panel (Desktop Only) -->
    <div id="notesPanel" class="notes-panel">
        <div class="notes-header" id="notesDragHandle">
            <span class="drag-icon" title="Drag to move">⋮⋮</span>
            <h3>Study Notes</h3>
            <div class="notes-buttons">
                <button type="button" onclick="downloadNotes()" class="notes-download-btn" title="Download notes as text file">Download</button>
                <button type="button" onclick="saveNotesToServer()" class="notes-save-btn" title="Save notes to server anonymously">Save to Server</button>
            </div>
        </div>
        <textarea id="notesTextarea" placeholder="Type your Bible study notes here..."></textarea>
        <div class="notes-footer">
            <a href="notes_list.php" target="_blank" class="notes-link">View Saved Notes</a>
        </div>
        <div class="notes-resize-handle" title="Drag to resize"></div>
    </div>

    <script>
        // Query type toggle
        document.querySelectorAll('input[name="query_type"]').forEach(radio => {
            radio.addEventListener('change', function() {
                document.getElementById('verse_fields').style.display = this.value === 'verse' ? 'flex' : 'none';
                document.getElementById('keyword_fields').style.display = this.value === 'keyword' ? 'flex' : 'none';
            });
        });

        // Helper function to highlight text
        function highlightText(text, search) {
            if (!search) return text;
            const regex = new RegExp('(' + search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
            return text.replace(regex, '<mark style="background-color: yellow; padding: 0 2px;">$1</mark>');
        }

        // Helper function to remove highlights
        function removeHighlights(element) {
            const marks = element.querySelectorAll('mark');
            marks.forEach(mark => {
                const parent = mark.parentNode;
                parent.replaceChild(document.createTextNode(mark.textContent), mark);
                parent.normalize();
            });
        }

        // Filter results function
        function filterResults() {
            const filterInput = document.getElementById('filterInput');
            const filterColumn = document.getElementById('filterColumn');
            const table = document.getElementById('resultsTable');
            const tbody = table.querySelector('tbody');
            const rows = tbody.getElementsByTagName('tr');

            const filter = filterInput.value.trim();
            const filterLower = filter.toLowerCase();
            const columnIndex = filterColumn.value;
            let visibleCount = 0;

            for (let i = 0; i < rows.length; i++) {
                const row = rows[i];
                const cells = row.getElementsByTagName('td');
                let found = false;

                // Remove existing highlights
                for (let j = 0; j < cells.length; j++) {
                    removeHighlights(cells[j]);
                }

                if (columnIndex === 'all') {
                    // Search all columns
                    for (let j = 0; j < cells.length; j++) {
                        const cellText = cells[j].textContent || cells[j].innerText;
                        if (cellText.toLowerCase().indexOf(filterLower) > -1) {
                            found = true;
                            if (filter !== '') {
                                cells[j].innerHTML = highlightText(cellText, filter);
                            }
                        }
                    }
                } else {
                    // Search specific column
                    const colIdx = parseInt(columnIndex);
                    const cell = cells[colIdx];
                    const cellText = cell.textContent || cell.innerText;
                    if (cellText.toLowerCase().indexOf(filterLower) > -1) {
                        found = true;
                        if (filter !== '') {
                            cell.innerHTML = highlightText(cellText, filter);
                        }
                    }
                }

                if (found || filter === '') {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            }

            // Update result count
            const resultCount = document.getElementById('resultCount');
            if (resultCount) {
                if (filter === '') {
                    resultCount.textContent = rows.length + ' results';
                } else {
                    resultCount.textContent = visibleCount + ' of ' + rows.length + ' results';
                }
            }
        }

        // Copy current query URL to clipboard
        function copyQueryURL(event) {
            const url = window.location.href;
            const btn = event.target;

            // Modern clipboard API
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(url).then(function() {
                    // Show success feedback
                    const originalText = btn.textContent;
                    btn.textContent = 'Copied!';
                    btn.style.backgroundColor = '#4CAF50';
                    setTimeout(function() {
                        btn.textContent = originalText;
                        btn.style.backgroundColor = '';
                    }, 2000);
                }).catch(function(err) {
                    alert('Failed to copy URL: ' + err);
                });
            } else {
                // Fallback for older browsers
                const textArea = document.createElement('textarea');
                textArea.value = url;
                textArea.style.position = 'fixed';
                textArea.style.left = '-999999px';
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();
                try {
                    document.execCommand('copy');
                    const originalText = btn.textContent;
                    btn.textContent = 'Copied!';
                    btn.style.backgroundColor = '#4CAF50';
                    setTimeout(function() {
                        btn.textContent = originalText;
                        btn.style.backgroundColor = '';
                    }, 2000);
                } catch (err) {
                    alert('Failed to copy URL: ' + err);
                }
                document.body.removeChild(textArea);
            }
        }

        // Download CSV function
        function downloadCSV() {
            const table = document.getElementById('resultsTable');
            const tbody = table.querySelector('tbody');
            const rows = tbody.getElementsByTagName('tr');
            const results = [];

            // Collect all visible rows
            for (let i = 0; i < rows.length; i++) {
                const row = rows[i];
                if (row.style.display !== 'none') {
                    const cells = row.getElementsByTagName('td');
                    results.push({
                        verse_ref: cells[0].textContent,
                        translation: cells[1].textContent,
                        text: cells[2].textContent
                    });
                }
            }

            // Create CSV content
            let csvContent = 'Verse Reference,Translation,Text\n';
            results.forEach(result => {
                const verse = '"' + result.verse_ref.replace(/"/g, '""') + '"';
                const translation = '"' + result.translation.replace(/"/g, '""') + '"';
                const text = '"' + result.text.replace(/"/g, '""') + '"';
                csvContent += verse + ',' + translation + ',' + text + '\n';
            });

            // Create download link
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            if (link.download !== undefined) {
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', 'bible_search_results.csv');
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }

        // Download notes function
        function downloadNotes() {
            const notesTextarea = document.getElementById('notesTextarea');
            const notesContent = notesTextarea.value;

            if (!notesContent.trim()) {
                alert('Notes are empty. Please add some notes before downloading.');
                return;
            }

            // Generate filename with current date and time
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            const filename = `biblestudy_${year}${month}${day}_${hours}${minutes}${seconds}.txt`;

            // Create download
            const blob = new Blob([notesContent], { type: 'text/plain;charset=utf-8;' });
            const link = document.createElement('a');
            if (link.download !== undefined) {
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', filename);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(url);
            }
        }

        // Save notes to server function
        function saveNotesToServer() {
            const notesTextarea = document.getElementById('notesTextarea');
            const notesContent = notesTextarea.value;

            if (!notesContent.trim()) {
                alert('Notes are empty. Please add some notes before saving to server.');
                return;
            }

            // Confirm with user
            if (!confirm('Save your notes anonymously to the server? Anyone with the link will be able to view them.')) {
                return;
            }

            // Show loading state
            const saveBtn = event.target;
            const originalText = saveBtn.textContent;
            saveBtn.textContent = 'Saving...';
            saveBtn.disabled = true;

            // Send to server
            const formData = new FormData();
            formData.append('content', notesContent);

            fetch('notes_save.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message with link
                    const viewUrl = data.viewUrl;
                    const fullUrl = window.location.origin + window.location.pathname.replace('index.php', '') + viewUrl;

                    if (confirm('Notes saved successfully! Click OK to view your saved note in a new tab.')) {
                        window.open(viewUrl, '_blank');
                    }

                    // Optional: Clear the notes after saving
                    // notesTextarea.value = '';
                    // localStorage.removeItem('bibleStudyNotes');
                } else {
                    alert('Failed to save notes: ' + (data.error || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error saving notes:', error);
                alert('Failed to save notes. Please try again.');
            })
            .finally(() => {
                // Restore button state
                saveBtn.textContent = originalText;
                saveBtn.disabled = false;
            });
        }

        // Notes Panel Drag and Resize Functionality
        const notesPanel = document.getElementById('notesPanel');
        const notesDragHandle = document.getElementById('notesDragHandle');
        const notesTextarea = document.getElementById('notesTextarea');
        const notesResizeHandle = document.querySelector('.notes-resize-handle');

        if (notesPanel && notesDragHandle && notesTextarea) {
            // Load saved notes content
            const savedNotes = localStorage.getItem('bibleStudyNotes');
            if (savedNotes) {
                notesTextarea.value = savedNotes;
            }

            // Save notes on input
            notesTextarea.addEventListener('input', function() {
                localStorage.setItem('bibleStudyNotes', this.value);
            });

            // Load saved position and size
            const savedPosition = JSON.parse(localStorage.getItem('notesPanelPosition') || '{}');
            if (savedPosition.top) notesPanel.style.top = savedPosition.top;
            if (savedPosition.right) notesPanel.style.right = savedPosition.right;
            if (savedPosition.left) notesPanel.style.left = savedPosition.left;
            if (savedPosition.width) notesPanel.style.width = savedPosition.width;
            if (savedPosition.height) notesTextarea.style.height = savedPosition.height;

            // Make panel draggable
            let isDragging = false;
            let currentX;
            let currentY;
            let initialX;
            let initialY;
            let xOffset = 0;
            let yOffset = 0;

            notesDragHandle.addEventListener('mousedown', dragStart);
            document.addEventListener('mousemove', drag);
            document.addEventListener('mouseup', dragEnd);

            function dragStart(e) {
                // Don't drag if clicking on button
                if (e.target.tagName === 'BUTTON') return;

                initialX = e.clientX - xOffset;
                initialY = e.clientY - yOffset;

                if (e.target === notesDragHandle || e.target.closest('#notesDragHandle')) {
                    isDragging = true;
                    notesDragHandle.style.cursor = 'grabbing';
                }
            }

            function drag(e) {
                if (isDragging) {
                    e.preventDefault();

                    currentX = e.clientX - initialX;
                    currentY = e.clientY - initialY;

                    xOffset = currentX;
                    yOffset = currentY;

                    // Remove right positioning when dragging
                    notesPanel.style.right = 'auto';
                    notesPanel.style.left = (notesPanel.offsetLeft + currentX) + 'px';
                    notesPanel.style.top = (notesPanel.offsetTop + currentY) + 'px';

                    initialX = e.clientX;
                    initialY = e.clientY;
                }
            }

            function dragEnd(e) {
                if (isDragging) {
                    initialX = currentX;
                    initialY = currentY;
                    isDragging = false;
                    notesDragHandle.style.cursor = 'grab';

                    // Save position to localStorage
                    savePosition();
                }
            }

            // Make panel resizable
            let isResizing = false;
            let startWidth;
            let startHeight;
            let startX;
            let startY;

            if (notesResizeHandle) {
                notesResizeHandle.addEventListener('mousedown', resizeStart);
                document.addEventListener('mousemove', resize);
                document.addEventListener('mouseup', resizeEnd);
            }

            function resizeStart(e) {
                isResizing = true;
                startWidth = notesPanel.offsetWidth;
                startHeight = notesTextarea.offsetHeight;
                startX = e.clientX;
                startY = e.clientY;
                e.preventDefault();
            }

            function resize(e) {
                if (isResizing) {
                    const deltaX = startX - e.clientX;
                    const deltaY = e.clientY - startY;

                    const newWidth = Math.max(250, Math.min(800, startWidth + deltaX));
                    const newHeight = Math.max(200, startHeight + deltaY);

                    notesPanel.style.width = newWidth + 'px';
                    notesTextarea.style.height = newHeight + 'px';
                }
            }

            function resizeEnd(e) {
                if (isResizing) {
                    isResizing = false;
                    savePosition();
                }
            }

            function savePosition() {
                const position = {
                    top: notesPanel.style.top,
                    right: notesPanel.style.right,
                    left: notesPanel.style.left,
                    width: notesPanel.style.width,
                    height: notesTextarea.style.height
                };
                localStorage.setItem('notesPanelPosition', JSON.stringify(position));
            }
        }
    </script>
</body>
</html>
