<?php
// notes_list.php
// Display all saved Bible study notes

$notesDir = __DIR__ . '/notes/';
$notes = [];

if (is_dir($notesDir)) {
    // Get all .txt files
    $files = glob($notesDir . '*.txt');

    foreach ($files as $file) {
        $noteId = basename($file, '.txt');

        // Skip tracking files (hits and human_ips files)
        if (strpos($noteId, '.hits') !== false || strpos($noteId, '.human_ips') !== false) {
            continue;
        }

        $metaFile = $notesDir . $noteId . '.meta';

        // Read metadata if exists
        if (file_exists($metaFile)) {
            $metadata = json_decode(file_get_contents($metaFile), true);
        } else {
            // Fallback if no metadata
            $metadata = [
                'id' => $noteId,
                'created' => filemtime($file),
                'ip' => 'unknown',
                'lines' => 0,
                'size' => filesize($file)
            ];
        }

        // Read first 250 lines for preview
        $content = file_get_contents($file);
        $lines = explode("\n", $content);
        $preview = implode("\n", array_slice($lines, 0, 250));

        // Truncate if exactly 250 lines and more exist
        if (count($lines) > 250) {
            $preview .= "\n...";
        }

        // Load hit tracking data
        $noteHitsFile = $notesDir . $noteId . '.hits.txt';
        $noteHumanIpsFile = $notesDir . $noteId . '.human_ips.txt';

        $humanHits = 0;
        $uniqueHumans = 0;

        if (file_exists($noteHitsFile)) {
            $humanHits = (int)file_get_contents($noteHitsFile);
        }

        if (file_exists($noteHumanIpsFile)) {
            $humanIpLog = file_get_contents($noteHumanIpsFile);
            $humanIps = array_filter(explode("\n", $humanIpLog));
            $uniqueHumans = count($humanIps);
        }

        $notes[] = [
            'id' => $noteId,
            'created' => $metadata['created'],
            'preview' => $preview,
            'totalLines' => count($lines),
            'size' => $metadata['size'],
            'humanHits' => $humanHits,
            'uniqueHumans' => $uniqueHumans
        ];
    }

    // Sort by created time, newest first
    usort($notes, function($a, $b) {
        return $b['created'] - $a['created'];
    });
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Saved Bible Study Notes - Bib 4.0</title>
    <meta name="description" content="View saved Bible study notes shared by users of Bib 4.0 by Amfile.org">

    <?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 -->
    <meta property="og:type" content="website">
    <meta property="og:url" content="<?php echo htmlspecialchars($currentUrl); ?>">
    <meta property="og:title" content="Saved Bible Study Notes - Bib 4.0">
    <meta property="og:description" content="View saved Bible study notes shared by users of Bib 4.0 by Amfile.org">
    <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="Saved Bible Study Notes - Bib 4.0">
    <meta property="twitter:description" content="View saved Bible study notes shared by users of Bib 4.0 by Amfile.org">
    <meta property="twitter:image" content="<?php echo htmlspecialchars($ogImageUrl); ?>">

    <link rel="stylesheet" href="styles.css">
    <style>
        .notes-list-container {
            max-width: 1200px;
            margin: 1rem auto;
            padding: 0 0.5rem;
        }

        .note-card {
            background-color: var(--os2-gray);
            border: 2px solid var(--os2-dark-gray);
            box-shadow:
                inset 2px 2px 0 rgba(255,255,255,0.7),
                inset -2px -2px 0 rgba(0,0,0,0.5),
                2px 2px 8px rgba(0, 0, 0, 0.3);
            margin-bottom: 1rem;
            padding: 1rem;
            cursor: pointer;
            transition: transform 0.2s ease;
        }

        .note-card:hover {
            transform: translateY(-2px);
            box-shadow:
                inset 2px 2px 0 rgba(255,255,255,0.7),
                inset -2px -2px 0 rgba(0,0,0,0.5),
                4px 4px 12px rgba(0, 0, 0, 0.4);
        }

        .note-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.5rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid var(--os2-dark-gray);
        }

        .note-meta {
            font-size: 0.9rem;
            color: var(--os2-purple);
            font-weight: bold;
        }

        .note-stats {
            font-size: 0.85rem;
            color: var(--os2-dark-gray);
        }

        .note-preview {
            white-space: pre-wrap;
            word-wrap: break-word;
            background-color: var(--os2-white);
            padding: 0.8rem;
            border: 2px solid var(--os2-dark-gray);
            box-shadow: inset 1px 1px 3px rgba(0,0,0,0.2);
            font-family: 'System', 'Arial', monospace;
            font-size: 0.95rem;
            line-height: 1.4;
            max-height: 400px;
            overflow-y: auto;
        }

        .back-link {
            display: inline-block;
            margin: 1rem 0.5rem;
            padding: 0.6rem 1.2rem;
            background: linear-gradient(180deg, var(--os2-light-gray) 0%, var(--os2-button) 50%, var(--os2-dark-gray) 100%);
            color: var(--os2-black);
            text-decoration: none;
            border: 2px solid;
            border-color: var(--os2-white) var(--os2-dark-gray) var(--os2-dark-gray) var(--os2-white);
            box-shadow:
                inset 1px 1px 0 rgba(255,255,255,0.8),
                inset -1px -1px 0 rgba(0,0,0,0.4),
                2px 2px 4px rgba(0,0,0,0.3);
            font-weight: bold;
            transition: all 0.1s ease;
        }

        .back-link:hover {
            background: linear-gradient(180deg, var(--os2-white) 0%, var(--os2-light-gray) 50%, var(--os2-button) 100%);
        }

        .back-link:active {
            border-color: var(--os2-dark-gray) var(--os2-white) var(--os2-white) var(--os2-dark-gray);
            box-shadow:
                inset -1px -1px 0 rgba(255,255,255,0.8),
                inset 1px 1px 2px rgba(0,0,0,0.4);
            transform: translate(1px, 1px);
        }

        .empty-state {
            text-align: center;
            padding: 3rem 1rem;
            color: var(--os2-purple);
        }
    </style>
</head>
<body>
    <h1>Saved Bible Study Notes - <a href="index.php" class="header-link">Bib 4.0</a></h1>

    <div style="margin: 1rem 0.5rem;">
        <a href="index.php" class="back-link">← Back to Bib</a>
        <a href="changelog.php" class="back-link" style="background: #666;">📋 Changelog</a>
    </div>

    <div class="notes-list-container">
        <?php if (empty($notes)): ?>
            <div class="empty-state">
                <h2>No notes saved yet</h2>
                <p>Be the first to save a Bible study note!</p>
            </div>
        <?php else: ?>
            <h2 style="margin-bottom: 1rem;">All Saved Notes (<?php echo count($notes); ?>)</h2>

            <?php foreach ($notes as $note): ?>
                <div class="note-card" onclick="window.location.href='notes_view.php?id=<?php echo htmlspecialchars($note['id']); ?>'">
                    <div class="note-header">
                        <div class="note-meta">
                            Saved: <?php echo date('F j, Y, g:i a', $note['created']); ?>
                        </div>
                        <div class="note-stats">
                            <?php echo $note['totalLines']; ?> lines | <?php echo number_format($note['size']); ?> bytes |
                            <?php echo number_format($note['humanHits']); ?> views |
                            <?php echo number_format($note['uniqueHumans']); ?> unique visitors
                        </div>
                    </div>
                    <div class="note-preview"><?php echo htmlspecialchars($note['preview']); ?></div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <script>
        // Prevent default click on note cards and navigate
        document.querySelectorAll('.note-card').forEach(card => {
            card.addEventListener('click', function(e) {
                e.preventDefault();
                window.location.href = this.getAttribute('onclick').match(/'([^']+)'/)[1];
            });
        });
    </script>
</body>
</html>
