<?php
include 'includes/db.php';

if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $stmt = $conn->prepare("SELECT * FROM blogs WHERE id = ?");
    $stmt->bind_param("i", $id);
} elseif (isset($_GET['title'])) {
    $title = urldecode($_GET['title']);
    $stmt = $conn->prepare("SELECT * FROM blogs WHERE title = ?");
    $stmt->bind_param("s", $title);
} else {
    header("Location: /bm/blog.php");
    exit;
}

$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 0) {
    include 'includes/header.php';
    echo "
    <link rel='stylesheet' href='/bm/assets/css/blog.css'>
    <div class='bm-blog-wrapper' style='padding: 80px 20px; text-align: center;'>
        <div style='max-width: 600px; margin: 0 auto; background: #fff; padding: 40px; border-radius: 12px; box-shadow: var(--bm-shadow-md);'>
            <i class='fas fa-exclamation-circle' style='font-size: 50px; color: var(--bm-blue-primary); margin-bottom: 20px;'></i>
            <h2 style='color: var(--bm-blue-dark); margin-bottom: 10px;'>Article Not Found</h2>
            <p style='color: var(--bm-text-muted); margin-bottom: 24px;'>The blog post you requested could not be found or may have been removed.</p>
            <a href='/bm/blog.php' class='btn-read-more' style='display: inline-flex; border: 2px solid var(--bm-blue-primary); padding: 10px 24px; border-radius: 50px;'>
                <i class='fas fa-arrow-left me-2'></i> Return to Blogs
            </a>
        </div>
    </div>";
    include 'includes/footer.php';
    exit;
}

$blog = $result->fetch_assoc();
$stmt->close();

// Parse Content & Decode JSON
$content_raw = $blog['content'];
$json_data = json_decode($content_raw, true);

// Resolve Featured Image
$featured_img = !empty($blog['image_url']) ? $blog['image_url'] : '';
if (empty($featured_img) && $json_data && isset($json_data['blocks'])) {
    foreach ($json_data['blocks'] as $b) {
        if ($b['type'] === 'image' && !empty($b['data']['file']['url'])) {
            $featured_img = $b['data']['file']['url'];
            break;
        } elseif ($b['type'] === 'gallery' && !empty($b['data']['urls'][0])) {
            $featured_img = $b['data']['urls'][0];
            break;
        }
    }
}
if (!empty($featured_img)) {
    if (strpos($featured_img, '/') !== 0 && strpos($featured_img, 'http') !== 0) {
        $featured_img = '/bm/' . $featured_img;
    }
}

// Calculate reading time
$plain_text = '';
if ($json_data && isset($json_data['blocks'])) {
    foreach ($json_data['blocks'] as $b) {
        if (isset($b['data']['text'])) $plain_text .= strip_tags($b['data']['text']) . ' ';
    }
} else {
    $plain_text = strip_tags($content_raw);
}
$words = str_word_count(strip_tags($plain_text));
$read_mins = max(2, ceil($words / 180));

// Process Content & Build Table of Contents
$toc_items = [];
$processed_content_html = '';

if ($json_data && isset($json_data['blocks'])) {
    $heading_counter = 0;
    foreach ($json_data['blocks'] as $block) {
        $alignStyle = '';
        if (isset($block['tunes']['alignment']['alignment'])) {
            $align = $block['tunes']['alignment']['alignment'];
            if ($align === 'center') $alignStyle = 'text-align: center;';
            elseif ($align === 'right') $alignStyle = 'text-align: right;';
            elseif ($align === 'left') $alignStyle = 'text-align: left;';
        }

        switch ($block['type']) {
            case 'header':
                $heading_counter++;
                $level = $block['data']['level'] ?? 2;
                $htext = $block['data']['text'] ?? '';
                $clean_text = strip_tags($htext);
                $anchor_id = 'section-' . $heading_counter . '-' . preg_replace('/[^a-zA-Z0-9_-]/', '-', strtolower(substr($clean_text, 0, 30)));
                $anchor_id = trim($anchor_id, '-');
                
                if ($level <= 3) {
                    $toc_items[] = [
                        'id' => $anchor_id,
                        'text' => $clean_text,
                        'level' => $level
                    ];
                }
                
                $processed_content_html .= "<h{$level} id='{$anchor_id}' style='{$alignStyle}'>" . $htext . "</h{$level}>\n";
                break;

            case 'paragraph':
                $ptext = $block['data']['text'] ?? '';
                $processed_content_html .= "<p style='{$alignStyle}'>" . $ptext . "</p>\n";
                break;

            case 'list':
                $tag = ($block['data']['style'] ?? 'unordered') === 'ordered' ? 'ol' : 'ul';
                $processed_content_html .= "<{$tag} style='{$alignStyle}'>";
                $renderNestedList = function($items) use (&$renderNestedList) {
                    $out = '';
                    foreach ($items as $item) {
                        if (is_array($item)) {
                            $c = isset($item['content']) ? $item['content'] : '';
                            $out .= "<li>" . $c;
                            if (!empty($item['items']) && is_array($item['items'])) {
                                $out .= "<ul>" . $renderNestedList($item['items']) . "</ul>";
                            }
                            $out .= "</li>";
                        } else {
                            $out .= "<li>{$item}</li>";
                        }
                    }
                    return $out;
                };
                $processed_content_html .= $renderNestedList($block['data']['items'] ?? []);
                $processed_content_html .= "</{$tag}>\n";
                break;

            case 'image':
                $url = $block['data']['file']['url'] ?? '';
                $caption = $block['data']['caption'] ?? '';
                $withBorder = !empty($block['data']['withBorder']) ? 'border: 1px solid var(--bm-border-color);' : '';
                $processed_content_html .= "<figure>";
                $processed_content_html .= "<img src='{$url}' style='max-width:100%;border-radius:var(--bm-radius-md);{$withBorder}' alt='" . htmlspecialchars($caption) . "'>";
                if ($caption) $processed_content_html .= "<figcaption style='{$alignStyle}'>" . htmlspecialchars($caption) . "</figcaption>";
                $processed_content_html .= "</figure>\n";
                break;

            case 'quote':
                $qtext = $block['data']['text'] ?? '';
                $qcap = $block['data']['caption'] ?? '';
                $processed_content_html .= "<blockquote style='{$alignStyle}'>";
                $processed_content_html .= "<p style='margin-bottom:0;'>{$qtext}</p>";
                if ($qcap) {
                    $processed_content_html .= "<footer style='font-size:14px;font-weight:600;margin-top:8px;color:var(--bm-blue-primary);'>— {$qcap}</footer>";
                }
                $processed_content_html .= "</blockquote>\n";
                break;

            case 'table':
                if (!empty($block['data']['content']) && is_array($block['data']['content'])) {
                    $processed_content_html .= "<div style='overflow-x:auto; margin: 1.8em 0;'><table>";
                    foreach ($block['data']['content'] as $rowIdx => $row) {
                        $processed_content_html .= "<tr>";
                        $tag2 = ($rowIdx === 0 && !empty($block['data']['withHeadings'])) ? 'th' : 'td';
                        foreach ($row as $cell) {
                            $processed_content_html .= "<{$tag2}>" . htmlspecialchars_decode(strip_tags($cell, '<b><i><a><strong><em>')) . "</{$tag2}>";
                        }
                        $processed_content_html .= "</tr>";
                    }
                    $processed_content_html .= "</table></div>\n";
                }
                break;

            case 'code':
                $code_text = htmlspecialchars($block['data']['code'] ?? '');
                $processed_content_html .= "<pre><code>{$code_text}</code></pre>\n";
                break;

            case 'preformatted':
                $pre_text = htmlspecialchars($block['data']['text'] ?? '');
                $processed_content_html .= "<pre>{$pre_text}</pre>\n";
                break;

            case 'details':
                $summary = htmlspecialchars($block['data']['summary'] ?? 'Click to Read More');
                $dcontent = $block['data']['content'] ?? '';
                $processed_content_html .= "<details><summary>{$summary}</summary><p style='margin-top:12px;margin-bottom:0;'>{$dcontent}</p></details>\n";
                break;

            case 'pullquote':
                $pq_text = $block['data']['text'] ?? '';
                $pq_cit = $block['data']['citation'] ?? '';
                $processed_content_html .= "<div style='padding:22px 26px; border-left:4px solid var(--bm-blue-primary); border-right:4px solid var(--bm-blue-primary); background:var(--bm-blue-tint); text-align:center; margin:32px 0; border-radius:var(--bm-radius-md);'>";
                $processed_content_html .= "<h3 style='font-style:italic; color:var(--bm-blue-dark); margin:0 0 8px; font-size:1.25rem;'>“{$pq_text}”</h3>";
                if ($pq_cit) $processed_content_html .= "<p style='text-transform:uppercase;font-size:12px;font-weight:700;color:var(--bm-blue-primary);margin:0;'>{$pq_cit}</p>";
                $processed_content_html .= "</div>\n";
                break;

            case 'verse':
                $vtext = htmlspecialchars($block['data']['text'] ?? '');
                $processed_content_html .= "<pre style='font-family:Georgia,serif;background:var(--bm-blue-tint);color:var(--bm-blue-dark);padding:18px 24px;border-radius:var(--bm-radius-md);border-left:3px solid var(--bm-blue-primary);'>{$vtext}</pre>\n";
                break;

            case 'button':
                $burl = htmlspecialchars($block['data']['url'] ?? '#');
                $btext = htmlspecialchars($block['data']['text'] ?? 'Learn More');
                $processed_content_html .= "<div style='text-align:center;margin:26px 0;{$alignStyle}'><a href='{$burl}' class='btn-cta-white' style='background:var(--bm-blue-primary);color:#fff;display:inline-block;'>{$btext} <i class='fas fa-arrow-right ms-2'></i></a></div>\n";
                break;

            case 'delimiter':
                $processed_content_html .= "<div class='ce-delimiter'>* * *</div>\n";
                break;

            case 'separator':
                $processed_content_html .= "<hr style='width:80px;margin:32px auto;border:none;border-top:3px solid var(--bm-blue-primary);border-radius:3px;'>\n";
                break;

            case 'spacer':
                $height = (int)($block['data']['height'] ?? 30);
                $processed_content_html .= "<div style='height:{$height}px;'></div>\n";
                break;

            case 'raw':
                $processed_content_html .= ($block['data']['html'] ?? '') . "\n";
                break;

            case 'embed-youtube':
                if (!empty($block['data']['url'])) {
                    preg_match('/(?:v=|youtu\.be\/)([a-zA-Z0-9_-]+)/', $block['data']['url'], $m);
                    if (!empty($m[1])) {
                        $processed_content_html .= "<div style='position:relative;padding-bottom:56.25%;height:0;overflow:hidden;margin:26px 0;border-radius:var(--bm-radius-md);box-shadow:var(--bm-shadow-md);'>";
                        $processed_content_html .= "<iframe src='https://www.youtube.com/embed/{$m[1]}' style='position:absolute;top:0;left:0;width:100%;height:100%;' frameborder='0' allowfullscreen></iframe>";
                        $processed_content_html .= "</div>\n";
                    }
                }
                break;

            case 'embed-vimeo':
                if (!empty($block['data']['url'])) {
                    preg_match('/vimeo\.com\/([0-9]+)/', $block['data']['url'], $m);
                    if (!empty($m[1])) {
                        $processed_content_html .= "<div style='position:relative;padding-bottom:56.25%;height:0;overflow:hidden;margin:26px 0;border-radius:var(--bm-radius-md);box-shadow:var(--bm-shadow-md);'>";
                        $processed_content_html .= "<iframe src='https://player.vimeo.com/video/{$m[1]}' style='position:absolute;top:0;left:0;width:100%;height:100%;' frameborder='0' allowfullscreen></iframe>";
                        $processed_content_html .= "</div>\n";
                    }
                }
                break;

            case 'gallery':
                if (!empty($block['data']['urls'])) {
                    $processed_content_html .= "<div style='display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:14px;margin:24px 0;'>";
                    foreach ($block['data']['urls'] as $gurl) {
                        $processed_content_html .= "<img src='" . htmlspecialchars($gurl) . "' style='width:100%;height:180px;object-fit:cover;border-radius:var(--bm-radius-md);box-shadow:var(--bm-shadow-sm);'>";
                    }
                    $processed_content_html .= "</div>\n";
                }
                break;

            case 'video':
                if (!empty($block['data']['url'])) {
                    $processed_content_html .= "<div style='margin:26px 0;'><video controls style='width:100%;border-radius:var(--bm-radius-md);box-shadow:var(--bm-shadow-md);' src='" . htmlspecialchars($block['data']['url']) . "'></video></div>\n";
                }
                break;

            default:
                if (!empty($block['data']['text'])) {
                    $processed_content_html .= "<p>" . $block['data']['text'] . "</p>\n";
                }
                break;
        }
    }
} else {
    // If regular HTML string: extract H2/H3 for TOC and inject IDs
    $html = $content_raw;
    $heading_counter = 0;
    $processed_content_html = preg_replace_callback('/<h([23])([^>]*)>(.*?)<\/h\1>/i', function($matches) use (&$toc_items, &$heading_counter) {
        $heading_counter++;
        $level = (int)$matches[1];
        $attributes = $matches[2];
        $inner_content = $matches[3];
        $clean_title = strip_tags($inner_content);
        $anchor_id = 'section-' . $heading_counter . '-' . preg_replace('/[^a-zA-Z0-9_-]/', '-', strtolower(substr($clean_title, 0, 30)));
        $anchor_id = trim($anchor_id, '-');

        $toc_items[] = [
            'id' => $anchor_id,
            'text' => $clean_title,
            'level' => $level
        ];

        return "<h{$level} id='{$anchor_id}'{$attributes}>{$inner_content}</h{$level}>";
    }, $html);
}

// Fetch Related Articles
$related_posts = [];
try {
    $stmt_rel = $conn->prepare("SELECT id, title, image_url, created_at, content FROM blogs WHERE (status = 'published' OR status IS NULL) AND deleted_at IS NULL AND id != ? ORDER BY id DESC LIMIT 4");
    $stmt_rel->bind_param("i", $blog['id']);
    $stmt_rel->execute();
    $res_rel = $stmt_rel->get_result();
    while ($r = $res_rel->fetch_assoc()) {
        $related_posts[] = $r;
    }
    $stmt_rel->close();
} catch (Exception $e) {}

$current_page_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
?>

<?php include 'includes/header.php'; ?>

<!-- Link Dedicated Blog Stylesheet -->
<link rel="stylesheet" href="/bm/assets/css/blog.css">

<div class="bm-single-post-wrapper">

    <!-- 1. BREADCRUMB NAVIGATION -->
    <nav class="bm-breadcrumb-nav" aria-label="breadcrumb">
        <div class="container">
            <ul class="bm-breadcrumb-list">
                <li><a href="/bm/"><i class="fas fa-home me-1"></i> Home</a></li>
                <li class="bm-breadcrumb-sep"><i class="fas fa-chevron-right"></i></li>
                <li><a href="/bm/blog.php">Blogs</a></li>
                <li class="bm-breadcrumb-sep"><i class="fas fa-chevron-right"></i></li>
                <li><span class="bm-breadcrumb-current"><?php echo htmlspecialchars(mb_substr($blog['title'], 0, 45)) . (mb_strlen($blog['title']) > 45 ? '...' : ''); ?></span></li>
            </ul>
        </div>
    </nav>

    <!-- 2. MAIN TWO-COLUMN LAYOUT (LAKSHYA STYLE) -->
    <div class="bm-single-post-layout">

        <!-- ======== LEFT: ARTICLE CONTENT ======== -->
        <main>
            <article class="bm-article-card">

                <!-- Post Title & Meta Header -->
                <div class="blogSingle">
                    <h1 class="heading"><?php echo htmlspecialchars($blog['title']); ?></h1>
                    
                    <div class="iconWrap">
                        <p class="iconBox">
                            <i class="far fa-calendar-check"></i>
                            <span>Last Updated On - <strong><?php echo date('d M Y', strtotime($blog['created_at'])); ?></strong></span>
                        </p>
                        <p class="iconBox">
                            <i class="fas fa-user-shield"></i>
                            <span>By <strong>Balimeen Team</strong></span>
                        </p>
                        <p class="iconBox">
                            <i class="far fa-clock"></i>
                            <span><?php echo $read_mins; ?> min read</span>
                        </p>
                    </div>
                </div>

                <!-- Featured Image -->
                <?php if (!empty($featured_img)): ?>
                <div class="singleBlogImg">
                    <img src="<?php echo htmlspecialchars($featured_img); ?>" 
                         alt="<?php echo htmlspecialchars($blog['title']); ?>"
                         loading="eager"
                         onerror="this.parentElement.style.display='none'">
                </div>
                <?php endif; ?>

                <!-- Table of Contents (Signature Lakshya Feature) -->
                <?php if (!empty($toc_items) && count($toc_items) >= 2): ?>
                <div class="toc-wrapper">
                    <div class="toc-title">
                        <i class="fas fa-list-ol"></i> Table of Contents
                    </div>
                    <ul class="toc-list">
                        <?php foreach ($toc_items as $titem): ?>
                        <li style="<?php echo $titem['level'] == 3 ? 'padding-left: 18px; font-size: 13.5px;' : ''; ?>">
                            <a href="#<?php echo htmlspecialchars($titem['id']); ?>">
                                <?php echo htmlspecialchars($titem['text']); ?>
                            </a>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>

                <!-- Article Body Content -->
                <div class="webContent singleBlogContent">
                    <?php echo $processed_content_html; ?>
                </div>

                <!-- Back to blogs link -->
                <a href="/bm/blog.php" class="article-back-link">
                    <i class="fas fa-arrow-left"></i> Back to All Articles
                </a>

                <!-- Related Articles Section (Lakshya Style) -->
                <?php if (!empty($related_posts)): ?>
                <div class="relatedBlogSection">
                    <h4>Related Articles</h4>
                    <div class="related-posts-grid">
                        <?php foreach ($related_posts as $rp): 
                            $rSlug = urlencode($rp['title']);
                            $rUrl = '/bm/blog_post/' . $rSlug;
                            $rImg = !empty($rp['image_url']) ? $rp['image_url'] : '/bm/our servies image/Our Services/Construction_of_Building.jpeg';
                            if (strpos($rImg, '/') !== 0 && strpos($rImg, 'http') !== 0) $rImg = '/bm/' . $rImg;
                        ?>
                        <a href="<?php echo $rUrl; ?>" class="related-blog-card">
                            <div class="related-blog-img">
                                <img src="<?php echo htmlspecialchars($rImg); ?>" 
                                     alt="<?php echo htmlspecialchars($rp['title']); ?>" 
                                     loading="lazy"
                                     onerror="this.src='/bm/our servies image/Our Services/Construction_of_Building.jpeg'">
                            </div>
                            <div class="related-blog-info">
                                <div class="related-blog-title"><?php echo htmlspecialchars($rp['title']); ?></div>
                                <div class="related-blog-date"><i class="far fa-calendar-alt me-1"></i> <?php echo date('d M Y', strtotime($rp['created_at'])); ?></div>
                            </div>
                        </a>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

            </article>
        </main>

    </div><!-- /.bm-single-post-layout -->

</div><!-- /.bm-single-post-wrapper -->

<script>
function copyCurrentUrl() {
    navigator.clipboard.writeText(window.location.href).then(function() {
        alert('Link copied to clipboard!');
    }).catch(function() {
        const input = document.createElement('input');
        input.value = window.location.href;
        document.body.appendChild(input);
        input.select();
        document.execCommand('copy');
        document.body.removeChild(input);
        alert('Link copied to clipboard!');
    });
}
</script>

<?php include 'includes/footer.php'; ?>
