<?php
use App\Helpers\ContentCleaner;
include __DIR__ . '/layout/header.php';
$cleanContent = ContentCleaner::clean($article->content);

// Remove leading paragraph if it only contains the article title (avoids h1 + content duplicate)
$cleanContent = preg_replace('/^\s*<p[^>]*>\s*' . preg_quote($article->title, '/') . '\s*<\/p>\s*/i', '', $cleanContent);

// Separate images from text content for two-column layout
$textContent  = '';
$imageContent = '';
$hasImages    = false;

if (!empty(trim($cleanContent))) {
    // Use DOMDocument to extract figure.img-wrap elements
    $dom = new DOMDocument('1.0', 'UTF-8');
    // Suppress warnings from malformed HTML
    libxml_use_internal_errors(true);
    $dom->loadHTML('<?xml encoding="UTF-8"><div id="__wrap__">' . $cleanContent . '</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    libxml_clear_errors();

    $xpath   = new DOMXPath($dom);

    // Extract inline download links to populate the main download box at the bottom
    $dlBtns = $xpath->query('//a[contains(@class,"dl-btn")]');
    if ($dlBtns->length > 0) {
        if (empty($article->download_url)) {
            $article->download_url = $dlBtns->item(0)->getAttribute('href');
        }
        
        $mainUrl = $article->download_url;
        
        // Remove any inline button that has the same url as the main download box
        foreach ($dlBtns as $btn) {
            if ($btn->getAttribute('href') === $mainUrl) {
                $btn->parentNode->removeChild($btn);
            }
        }
    }

    // Remove stray "Download" or "İndir" texts that were next to the button
    $downloadTexts = $xpath->query('//*[self::p or self::span or self::div][translate(normalize-space(.), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")="download" or normalize-space(.)="İndir" or normalize-space(.)="indir" or normalize-space(.)="Download"]');
    foreach ($downloadTexts as $dt) {
        $dt->parentNode->removeChild($dt);
    }

    $figures = $xpath->query('//figure[contains(@class,"img-wrap")]');

    if ($figures->length > 0) {
        $hasImages = true;
        // Collect image HTML
        $imgHtmlParts = [];
        foreach ($figures as $fig) {
            $imgHtmlParts[] = $dom->saveHTML($fig);
            // Remove from original tree
            $fig->parentNode->removeChild($fig);
        }
        $imageContent = implode('', $imgHtmlParts);

        // Rebuild text-only content from the modified DOM
        $wrap = $dom->getElementById('__wrap__');
        $textContent = '';
        if ($wrap) {
            foreach ($wrap->childNodes as $child) {
                $textContent .= $dom->saveHTML($child);
            }
        }
        $textContent = trim($textContent);
    } else {
        $textContent = $cleanContent;
    }
} else {
    $textContent = $cleanContent;
}
?>

<article class="detail-page">

    <nav class="detail-breadcrumb">
        <a href="<?php echo $baseUrl; ?>/">Ana Sayfa</a>
        <?php if ($article->getCategory()): ?>
        <span class="sep">›</span>
        <a href="<?php echo $baseUrl; ?>/<?php echo $article->getCategory()->slug; ?>"><?php echo htmlspecialchars($article->getCategory()->name); ?></a>
        <?php endif; ?>
        <span class="sep">›</span>
        <span><?php echo htmlspecialchars($article->title); ?></span>
    </nav>

    <div class="detail-card">

        <header class="detail-header">
            <h1 class="detail-title"><?php echo htmlspecialchars($article->title); ?></h1>
            <div class="detail-meta">
                <?php if ($article->getBrand()): ?>
                <span class="detail-tag brand-tag">
                    <a href="<?php echo $baseUrl; ?>/<?php echo $article->getBrand()->slug; ?>"><?php echo htmlspecialchars($article->getBrand()->name); ?></a>
                </span>
                <?php endif; ?>
                <span class="detail-date"><?php echo date('d M Y', strtotime($article->created_at)); ?></span>
                <span class="detail-views"><?php echo number_format($article->view_count); ?> okunma</span>
            </div>
        </header>

        <?php if ($hasImages): ?>
        <div class="detail-body detail-split">
            <div class="detail-text-col">
                <?php echo $textContent; ?>
            </div>
            <div class="detail-images-col">
                <?php echo $imageContent; ?>
            </div>
        </div>
        <?php else: ?>
        <div class="detail-body">
            <?php echo $textContent; ?>
        </div>
        <?php endif; ?>

        <?php if ($article->download_url): ?>
        <div class="detail-download">
            <div class="dd-icon"><i class="fa fa-download"></i></div>
            <div class="dd-info">
                <strong>Sıfırlama / Reset Programı</strong>
                <span>Orijinal yazılımı güvenle indirin</span>
                <?php if ($article->file_size && $article->file_size !== 'Bilinmiyor'): ?>
                <small><?php echo htmlspecialchars($article->file_size); ?></small>
                <?php endif; ?>
            </div>
            <a href="<?php echo htmlspecialchars($article->download_url); ?>" class="dd-btn" target="_blank" rel="noopener">İndir</a>
        </div>
        <?php endif; ?>

        <?php if ($article->getCategory()): ?>
        <div class="detail-footer">
            <a href="<?php echo $baseUrl; ?>/<?php echo $article->getCategory()->slug; ?>" class="df-link">← Diğer <?php echo htmlspecialchars($article->getCategory()->name); ?> Çözümleri</a>
        </div>
        <?php endif; ?>

    </div>

</article>

<?php include __DIR__ . '/layout/footer.php'; ?>
