<?php
// notes_view.php
// View a single saved Bible study note (read-only)

$noteId = isset($_GET['id']) ? $_GET['id'] : '';
$notesDir = __DIR__ . '/notes/';
$noteFile = $notesDir . $noteId . '.txt';
$metaFile = $notesDir . $noteId . '.meta';

// Handle download request (don't track hits for downloads)
if (isset($_GET['download']) && $_GET['download'] === '1' && file_exists($noteFile)) {
    header('Content-Type: text/plain');
    header('Content-Disposition: attachment; filename="biblestudy_' . $noteId . '.txt"');
    readfile($noteFile);
    exit;
}

// Bot detection function (same as in index.php)
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 (same as in index.php)
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';
}

$noteExists = false;
$noteContent = '';
$metadata = [];

if ($noteId && file_exists($noteFile)) {
    $noteExists = true;
    $noteContent = file_get_contents($noteFile);

    // Load metadata
    if (file_exists($metaFile)) {
        $metadata = json_decode(file_get_contents($metaFile), true);
    } else {
        $metadata = [
            'id' => $noteId,
            'created' => filemtime($noteFile),
            'lines' => substr_count($noteContent, "\n") + 1,
            'size' => strlen($noteContent)
        ];
    }

    // Track hits for this note (only for actual note views, not downloads)
    $noteHitsFile = $notesDir . $noteId . '.hits.txt';
    $noteHumanIpsFile = $notesDir . $noteId . '.human_ips.txt';

    // Initialize hit tracking files if they don't exist
    if (!file_exists($noteHitsFile)) {
        file_put_contents($noteHitsFile, '0');
    }
    if (!file_exists($noteHumanIpsFile)) {
        file_put_contents($noteHumanIpsFile, '');
    }

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

    // Increment human hit counter if visitor is human
    if ($isHuman) {
        $humanHits = (int)file_get_contents($noteHitsFile);
        $humanHits++;
        file_put_contents($noteHitsFile, $humanHits);

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

        if (!in_array($visitorIP, $humanIps)) {
            file_put_contents($noteHumanIpsFile, $visitorIP . "\n", FILE_APPEND);
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $noteExists ? 'Bible Study Note - ' . date('M j, Y', $metadata['created']) : 'Note Not Found'; ?> - Bib 4.0</title>
    <meta name="description" content="<?php echo $noteExists ? 'View Bible study note saved on ' . date('F j, Y', $metadata['created']) : 'Bible study note not found'; ?>">

    <?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="article">
    <meta property="og:url" content="<?php echo htmlspecialchars($currentUrl); ?>">
    <meta property="og:title" content="Bible Study Note - Bib 4.0">
    <meta property="og:description" content="<?php echo $noteExists ? 'Saved on ' . date('F j, Y', $metadata['created']) . ' | ' . $metadata['lines'] . ' lines' : 'Bible study note'; ?>">
    <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="Bible Study Note - Bib 4.0">
    <meta property="twitter:description" content="<?php echo $noteExists ? 'Saved on ' . date('F j, Y', $metadata['created']) . ' | ' . $metadata['lines'] . ' lines' : 'Bible study note'; ?>">
    <meta property="twitter:image" content="<?php echo htmlspecialchars($ogImageUrl); ?>">

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

        .note-header-bar {
            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);
            padding: 1rem;
            margin-bottom: 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .note-meta-info {
            flex: 1;
        }

        .note-meta-title {
            font-size: 1.2rem;
            font-weight: bold;
            color: var(--os2-purple);
            margin-bottom: 0.5rem;
        }

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

        .note-actions {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }

        .note-content-box {
            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);
            padding: 1rem;
        }

        .note-content {
            white-space: pre-wrap;
            word-wrap: break-word;
            background-color: var(--os2-white);
            padding: 1rem;
            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: 1rem;
            line-height: 1.6;
            min-height: 400px;
            max-height: 80vh;
            overflow-y: auto;
        }

        .action-btn {
            display: inline-block;
            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;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.1s ease;
            white-space: nowrap;
        }

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

        .action-btn: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);
        }

        .error-message {
            background-color: var(--os2-gray);
            border: 2px solid var(--os2-dark-gray);
            padding: 2rem;
            text-align: center;
            color: var(--os2-purple);
            margin: 2rem auto;
            max-width: 600px;
        }

        @media (max-width: 768px) {
            .note-header-bar {
                flex-direction: column;
                align-items: stretch;
            }

            .note-actions {
                width: 100%;
            }

            .action-btn {
                flex: 1;
                text-align: center;
            }
        }
    </style>
</head>
<body>
    <h1>Bible Study Note - <a href="index.php" class="header-link">Bib 4.0</a></h1>

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

    <div class="note-container">
        <?php if ($noteExists): ?>
            <div class="note-header-bar">
                <div class="note-meta-info">
                    <div class="note-meta-title">
                        Saved: <?php echo date('F j, Y, g:i a', $metadata['created']); ?>
                    </div>
                    <div class="note-meta-stats">
                        <?php echo number_format($metadata['lines']); ?> lines |
                        <?php echo number_format($metadata['size']); ?> bytes
                    </div>
                </div>
                <div class="note-actions">
                    <a href="?id=<?php echo htmlspecialchars($noteId); ?>&download=1" class="action-btn">Download as TXT</a>
                </div>
            </div>

            <div class="note-content-box">
                <div class="note-content"><?php echo htmlspecialchars($noteContent); ?></div>
            </div>
        <?php else: ?>
            <div class="error-message">
                <h2>Note Not Found</h2>
                <p>The requested note does not exist or has been removed.</p>
                <p style="margin-top: 1rem;">
                    <a href="notes_list.php" class="action-btn">View All Notes</a>
                </p>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>
