<?php
require 'config.php';
include 'templates/header.php';

// Fetch ads
$adverts = $pdo->query("SELECT * FROM adverts WHERE active=1 ORDER BY id DESC")->fetchAll();

function showAdverts($position, $adverts) {
    $adsForPos = array_filter($adverts, fn($a)=>$a['position']==$position);
    foreach($adsForPos as $ad) {
        $adId = 'advert-'.$ad['id'];

        echo '<div id="'.$adId.'" class="advert" style="background:#fff;border:1px solid #ddd;padding:15px;border-radius:8px;margin:20px 0;position:relative;">';

        echo '<button onclick="closeAd(\''.$adId.'\')" 
              style="position:absolute;top:5px;right:8px;border:none;background:none;font-size:1.2rem;cursor:pointer;">&times;</button>';

        if(!empty($ad['image'])) {
            echo '<img src="'.htmlspecialchars($ad['image']).'" style="width:100%;border-radius:5px;margin-bottom:10px;">';
        }

        echo '<h4 style="margin:0 0 5px;font-weight:600;">'.htmlspecialchars($ad['title']).'</h4>';

        if(!empty($ad['content'])) {
            echo '<p>'.htmlspecialchars($ad['content']).'</p>';
        }

        if(!empty($ad['link'])) {
            echo '<a href="ad-click.php?id='.$ad['id'].'" target="_blank" style="color:#ff3b30;">Learn More</a>';
        }

        echo '</div>';
    }
}

// GET POST
if(isset($_GET['slug'])) {

    $slug = $_GET['slug'];

    $stmt = $pdo->query("SELECT p.*, a.name AS author, c.name AS category
                         FROM posts p
                         LEFT JOIN authors a ON p.author_id=a.id
                         LEFT JOIN categories c ON p.category_id=c.id");

    $posts = $stmt->fetchAll();

    $post = null;
    foreach($posts as $p){
        if(strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $p['title']))) === $slug){
            $post = $p;
            break;
        }
    }

    if($post):

        // increase views
        $stmt = $pdo->prepare("UPDATE posts SET views = views + 1 WHERE id=?");
        $stmt->execute([$post['id']]);
?>

<!-- TOP ADS -->
<div style="max-width:900px;margin:20px auto;">
    <?php showAdverts('top', $adverts); ?>
</div>

<!-- ARTICLE -->
<div style="max-width:900px;margin:20px auto;padding:20px;background:#fff;border-radius:10px;box-shadow:0 4px 12px rgba(0,0,0,0.1);">

    <?php if(!empty($post['featured_image'])): ?>
        <img src="<?=htmlspecialchars($post['featured_image'])?>" 
             style="width:100%;height:400px;object-fit:cover;border-radius:10px;margin-bottom:20px;">
    <?php endif; ?>

    <h1><?=htmlspecialchars($post['title'])?></h1>

    <!-- 🔊 TTS CONTROLS -->
    <div style="margin:15px 0;display:flex;gap:10px;flex-wrap:wrap;">
        <button id="tts-play" style="padding:10px 15px;background:#ff3b30;color:#fff;border:none;border-radius:5px;cursor:pointer;">
            🔊 Listen
        </button>
        <button id="tts-pause" style="padding:10px 15px;">⏸ Pause</button>
        <button id="tts-stop" style="padding:10px 15px;">⏹ Stop</button>
    </div>

    <p style="color:#888;font-size:0.9rem;margin-bottom:20px;">
        Story By <?=htmlspecialchars($post['author'] ?? 'Unknown')?> | 
        <?=htmlspecialchars($post['category'] ?? 'General')?> | 
        <?=date('M d, Y', strtotime($post['created_at']))?> |
        <?=htmlspecialchars($post['views'] + 1)?> Views
    </p>

    <!-- CONTENT -->
    <div id="post-content" style="line-height:1.8;color:#555;">
        <?php
        $content = nl2br($post['content']);
        $parts = explode('<br />', $content);

        foreach($parts as $i => $part){
            echo $part . '<br />';

            if($i == 3){
                showAdverts('incontent', $adverts);
            }

            if($i == 8){
                showAdverts('incontent', $adverts);
            }
        }
        ?>
    </div>

</div>

<!-- BOTTOM ADS -->
<div style="max-width:900px;margin:20px auto;">
    <?php showAdverts('bottom', $adverts); ?>
</div>

<?php
    else:
        echo "<p style='text-align:center;margin:40px;'>Post not found.</p>";
    endif;
}
?>

<!-- JS -->
<script>
function closeAd(id){
    const el = document.getElementById(id);
    if(el) el.style.display='none';
}
</script>

<!-- 🔊 FINAL TTS SCRIPT -->
<script>
(function () {

    let synth = window.speechSynthesis;
    let utterance = null;
    let voices = [];

    function loadVoices() {
        voices = synth.getVoices();
    }

    if (speechSynthesis.onvoiceschanged !== undefined) {
        speechSynthesis.onvoiceschanged = loadVoices;
    }

    loadVoices();

    function getText() {
        const el = document.getElementById("post-content");
        return el ? el.innerText.trim() : "";
    }

    function startTTS() {
        const text = getText();
        if (!text) return;

        synth.cancel();

        utterance = new SpeechSynthesisUtterance(text);
        utterance.lang = "en-US";
        utterance.rate = 1;
        utterance.pitch = 1;

        if (voices.length > 0) {
            let v = voices.find(voice => voice.lang.includes("en"));
            utterance.voice = v || voices[0];
        }

        synth.speak(utterance);
    }

    function pauseTTS() {
        if (synth.speaking && !synth.paused) synth.pause();
    }

    function resumeTTS() {
        if (synth.paused) synth.resume();
    }

    function stopTTS() {
        synth.cancel();
    }

    document.addEventListener("DOMContentLoaded", function () {

        const play = document.getElementById("tts-play");
        const pause = document.getElementById("tts-pause");
        const stop = document.getElementById("tts-stop");

        if (play) {
            play.addEventListener("click", () => {
                if (synth.paused) {
                    resumeTTS();
                } else {
                    startTTS();
                }
            });
        }

        if (pause) pause.addEventListener("click", pauseTTS);
        if (stop) stop.addEventListener("click", stopTTS);

    });

})();
</script>

<?php include 'templates/footer.php'; ?>