<?php
// Sirf installation ke liye ye line uncomment karein
// header("Location: install.php"); 
// exit;

// Original Logic
if (!file_exists('config.php') || filesize('config.php') == 0) {
    header("Location: install.php");
    exit;
}
require_once 'config.php';
session_start(); // Naya: Messages ke liye

$message_html = ''; // User ko dikhane ke liye

// --- 1. Contact Us Form Handling ---
if (isset($_POST['submit_contact_form'])) {
    $name = clean_input($_POST['name']);
    $email = clean_input($_POST['email']);
    $phone = clean_input($_POST['phone']); // Naya: Phone
    $subject = clean_input($_POST['subject']);
    $form_message = clean_input($_POST['message']);
    
    if (!empty($name) && !empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($form_message)) {
        try {
            $sql = "INSERT INTO messages (name, email, phone, subject, message, is_read, created_at) VALUES (?, ?, ?, ?, ?, 0, NOW())";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$name, $email, $phone, $subject, $form_message]);
            
            $_SESSION['form_message'] = ['type' => 'success', 'text' => 'Your message has been sent successfully! We will get back to you soon.'];
        } catch (PDOException $e) {
            $_SESSION['form_message'] = ['type' => 'error', 'text' => 'There was a database error. Please try again.'];
        }
    } else {
        $_SESSION['form_message'] = ['type' => 'error', 'text' => 'Please fill in all required fields with valid information.'];
    }
    header("Location: " . $_SERVER['REQUEST_URI']);
    exit;
}

// --- 2. Comment Form Handling ---
if (isset($_POST['submit_comment'])) {
    $name = clean_input($_POST['name']);
    $email = clean_input($_POST['email']);
    $comment_text = clean_input($_POST['comment']);
    $post_slug = clean_input($_POST['post_slug']);
    $post_type = clean_input($_POST['post_type']);
    
    if (!empty($name) && !empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($comment_text) && !empty($post_slug) && !empty($post_type)) {
        try {
            // is_approved ko '1' (auto-approve) kar diya gaya hai
            $sql = "INSERT INTO comments (post_slug, post_type, name, email, comment, is_approved, created_at) VALUES (?, ?, ?, ?, ?, 1, NOW())";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$post_slug, $post_type, $name, $email, $comment_text]);
            
            $_SESSION['form_message'] = ['type' => 'success', 'text' => 'Your comment has been posted successfully!'];
        } catch (PDOException $e) {
            $_SESSION['form_message'] = ['type' => 'error', 'text' => 'There was a database error submitting your comment.'];
        }
    } else {
        $_SESSION['form_message'] = ['type' => 'error', 'text' => 'Please fill in all required fields to submit a comment.'];
    }
    header("Location: " . $_SERVER['REQUEST_URI']);
    exit;
}

// --- 3. Display Session Message (if any) ---
if (isset($_SESSION['form_message'])) {
    $msg = $_SESSION['form_message'];
    $message_html = '<div class="form-message ' . htmlspecialchars($msg['type']) . '">' . htmlspecialchars($msg['text']) . '</div>';
    unset($_SESSION['form_message']);
}
// --- END OF FORM HANDLING ---


// --- 1. URL Routing Logic ---
$request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// Folder where the script is installed
$base_path = '/free-seo-tools';

// Remove the installation folder
if (strpos($request_uri, $base_path) === 0) {
    $request_uri = substr($request_uri, strlen($base_path));
}

// Remove index.php if present
$request_uri = preg_replace('#^/index\.php#', '/', $request_uri);

// Final slug
$slug = trim($request_uri, '/');
$category_slug = null;
$tool_data = null;
$page_data = null;
$category_data = null;
$blog_post_slug = null;
$blog_post_data = null;

if (empty($slug) || $slug === 'index.php') {
    $action = 'home';
}
else if ($slug === 'blog') {
    $action = 'blog_index';
}
else if (strpos($slug, 'blog/') === 0) {
    $blog_post_slug = substr($slug, strlen('blog/'));
    $stmt = $pdo->prepare("SELECT * FROM blog_posts WHERE slug = ? AND is_active = 1");
    $stmt->execute([$blog_post_slug]);
    $blog_post_data = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($blog_post_data) {
        $action = 'blog_post';
    } else {
        $action = '404';
    }
}
else if (strpos($slug, 'category/') === 0) {
    $category_slug = substr($slug, strlen('category/'));
    $stmt = $pdo->prepare("SELECT * FROM categories WHERE slug = ? AND is_active = 1");
    $stmt->execute([$category_slug]);
    $category_data = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($category_data) {
        $action = 'category';
    } else {
        $action = '404';
    }
}
else {
    $stmt = $pdo->prepare("SELECT * FROM tools WHERE slug = ? AND is_active = 1");
    $stmt->execute([$slug]);
    $tool_data = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($tool_data) {
        $action = 'tool';
        
        // 🔽 NAYA: Tool Analytics 🔽
        try {
            $sql_update_view = "UPDATE tools SET view_count = view_count + 1 WHERE id = ?";
            $pdo->prepare($sql_update_view)->execute([$tool_data['id']]);
        } catch (PDOException $e) { /* Do nothing */ }
        
    }
    else {
        $stmt = $pdo->prepare("SELECT * FROM pages WHERE slug = ? AND is_active = 1");
        $stmt->execute([$slug]);
        $page_data = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($page_data) {
            $action = 'page';
        } else {
            $action = '404';
        }
    }
}


// --- 2. Data Fetching and SEO Setup ---
$tools = [];
$categories = [];
$blog_posts = [];

if ($action === 'home' || $action === 'category') {
     try {
         $cat_stmt = $pdo->query("SELECT id, name, slug FROM categories WHERE is_active = 1 ORDER BY name ASC");
         $categories = $cat_stmt->fetchAll(PDO::FETCH_ASSOC);
     } catch (PDOException $e) {
         $categories = [];
     }
}

if ($action === 'home') {
    try {
        // 🔽 NAYA: Category Wise Logic 🔽
        $stmt_tools = $pdo->query("SELECT t.tool_name, t.slug, t.short_description, t.icon_class, 
                                      c.slug as category_slug, c.name as category_name
                               FROM tools t
                               JOIN categories c ON t.category_id = c.id
                               WHERE t.is_active = 1 AND c.is_active = 1
                               ORDER BY c.name ASC, t.tool_name ASC");
        $tools_with_cat = $stmt_tools->fetchAll(PDO::FETCH_ASSOC);

        $stmt_no_cat = $pdo->query("SELECT tool_name, slug, short_description, icon_class, 
                                        NULL as category_slug, 'Other Tools' as category_name
                                 FROM tools
                                 WHERE is_active = 1 AND (category_id IS NULL OR category_id NOT IN (SELECT id FROM categories WHERE is_active = 1))
                                 ORDER BY tool_name ASC");
        $tools_no_cat = $stmt_no_cat->fetchAll(PDO::FETCH_ASSOC);
        
        $tools = array_merge($tools_with_cat, $tools_no_cat);
        
    } catch (PDOException $e) {
        $tools = [];
    }
    $page_seo = [
        'title' => get_setting('home_seo_title') ?: get_setting('site_name') . ' - Online Tools',
        'description' => get_setting('home_seo_description'),
        'keywords' => get_setting('home_seo_keywords')
    ];
}
elseif ($action === 'category' && $category_data) {
     try {
         $stmt = $pdo->prepare("SELECT tool_name, slug, short_description, icon_class
                                FROM tools
                                WHERE is_active = 1 AND category_id = ?
                                ORDER BY tool_name ASC");
         $stmt->execute([$category_data['id']]);
         $tools = $stmt->fetchAll(PDO::FETCH_ASSOC);
     } catch (PDOException $e) {
         $tools = [];
     }
    $page_seo = [
        'title' => secure_input($category_data['name']) . ' Tools | ' . get_setting('site_name'),
        'description' => secure_input($category_data['description']) ?: 'Find the best ' . secure_input($category_data['name']) . ' tools on ' . get_setting('site_name') . '.',
        'keywords' => strtolower(secure_input($category_data['name'])) . ', online tools, ' . get_setting('site_name')
    ];
}
elseif ($action === 'blog_index') {
    try {
        $stmt = $pdo->query("SELECT title, slug, thumbnail_url, LEFT(content, 150) as excerpt, created_at 
                              FROM blog_posts
                              WHERE is_active = 1 ORDER BY created_at DESC");
        $blog_posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $blog_posts = [];
    }
    $page_seo = [
        'title' => 'Blog | ' . get_setting('site_name'),
        'description' => 'Read our latest articles, tutorials, and updates about PDF & image tools and productivity.',
        'keywords' => 'blog, articles, tutorials, pdf tips, image tips, ' . get_setting('site_name')
    ];
}
elseif ($action === 'blog_post' && $blog_post_data) {
    $page_seo = [
        'title' => secure_input($blog_post_data['seo_title'] ?: $blog_post_data['title'] . ' | ' . get_setting('site_name')),
        'description' => secure_input($blog_post_data['seo_description']),
        'keywords' => secure_input($blog_post_data['seo_keywords'])
    ];
}
elseif ($action === 'tool' && $tool_data) {
    $page_seo = [
        'title' => secure_input($tool_data['seo_title'] ?: $tool_data['tool_name'] . ' | ' . get_setting('site_name')),
        'description' => secure_input($tool_data['seo_description'] ?: $tool_data['short_description']),
        'keywords' => secure_input($tool_data['seo_keywords'])
    ];
} elseif ($action === 'page' && $page_data) {
    $page_seo = [
        'title' => secure_input($page_data['seo_title'] ?: $page_data['title'] . ' | ' . get_setting('site_name')),
        'description' => secure_input($page_data['seo_description']),
        'keywords' => secure_input($page_data['seo_keywords'])
    ];
} else { 
    http_response_code(404);
    $page_seo = [
        'title' => '404 Not Found | ' . get_setting('site_name'),
        'description' => 'The page you requested could not be found.'
    ];
     $action = '404';
}


// --- 3. HTML Rendering ---

$page_title = $page_seo['title'] ?? get_setting('site_name'); 
$meta_description = $page_seo['description'] ?? '';
$meta_keywords = $page_seo['keywords'] ?? '';

include 'header.php';

if ($action !== 'tool') {
    echo '<main class="container main-content-area">';
} else {
    echo '<main class="main-content-area">';
}

// Naya: Session Message
if ($action === 'page' || $action === 'tool' || $action === 'blog_post') {
    echo '<div class="container">' . $message_html . '</div>';
}

switch ($action) {
    case 'home':
        ?>
        <style>
            /* 🔽 NAYA: Background color aur category-wise heading ke liye CSS 🔽 */
            body {
                background-color: #f0fff0;
            }
            .homepage-content { padding-top: 10px; text-align: center; animation: fadeInUp 0.8s ease-out forwards; }
            .site-title { font-size: 2.5em; color: #2c2c2c; margin-bottom: 5px; }
            .site-tagline { font-size: 1.1em; color: #666; margin-bottom: 20px; }
            .search-bar { display: flex; max-width: 600px; margin: 20px auto; border: 1px solid var(--primary-color); border-radius: 50px; overflow: hidden; background: white; box-shadow: 0 5px 10px rgba(76, 175, 80, 0.1); }
            .search-bar input { flex-grow: 1; border: none; padding: 15px 25px; font-size: 1em; outline: none; }
            .search-bar button { background: var(--primary-color); color: white; border: none; padding: 15px 25px; cursor: pointer; transition: background-color 0.3s; }
            .search-bar button:hover { background: var(--secondary-color); }
            .separator { border: 0; border-top: 1px solid #eee; margin: 30px 0; }
            .category-section { margin-bottom: 30px; text-align: center; }
            .category-section h2 { margin-bottom: 15px; font-size: 1.8em; color: #333; }
            .category-pills { display: flex; flex-wrap: wrap; justify-content: center; gap: 10px; }
            .category-pills a {
                display: inline-block;
                padding: 6px 15px;
                border: 1px solid var(--primary-color);
                color: var(--primary-color);
                border-radius: 20px;
                text-decoration: none;
                font-weight: 500;
                transition: all 0.3s ease;
                background-color: white;
                font-size: 0.9em;
            }
            .category-pills a:hover {
                background-color: var(--primary-color);
                color: white;
                box-shadow: 0 3px 8px rgba(76, 175, 80, 0.3);
            }
            .category-pills a:nth-child(n+6) {
                display: none;
            }
            .category-pills.show-all a {
                display: inline-block;
            }
            .btn-more-cats {
                background-color: var(--secondary-color);
                color: white;
                border: none;
                border-radius: 20px;
                padding: 6px 15px;
                font-size: 0.9em;
                font-weight: 500;
                cursor: pointer;
                margin-top: 15px;
                transition: all 0.3s ease;
            }
            .btn-more-cats:hover {
                background-color: var(--primary-color);
                box-shadow: 0 3px 8px rgba(76, 175, 80, 0.3);
            }
            
            .tool-category-heading {
                grid-column: 1 / -1;
                text-align: left;
                font-size: 1.6em;
                color: #333;
                margin-top: 25px;
                margin-bottom: 15px;
                border-bottom: 2px solid var(--primary-color);
                padding-bottom: 8px;
                animation: fadeInUp 0.5s ease-out forwards;
            }
            .tool-category-heading:first-of-type {
                margin-top: 0;
            }
        </style>

        <div class="homepage-content">
            <h1 class="site-title"><?php echo secure_input(get_setting('site_name')); ?></h1>
            <p class="site-tagline"><?php echo secure_input(get_setting('site_tagline')); ?></p>

            <div class="search-bar">
                <input type="text" placeholder="Search for tools..." class="search-input" id="toolSearchInput">
                <button type="button" aria-label="Search"><i class="fas fa-search"></i></button>
            </div>

            <?php if (!empty($categories)): ?>
            <section class="category-section" id="category-section">
                 <h2>Browse by Category</h2>
                 <div class="category-pills" id="categoryPills">
                     <?php foreach ($categories as $category): ?>
                         <a href="/category/<?php echo secure_input($category['slug']); ?>">
                             <?php echo secure_input($category['name']); ?>
                         </a>
                     <?php endforeach; ?>
                 </div>
                 <?php if (count($categories) > 5): ?>
                    <button type="button" class="btn-more-cats" id="showMoreCategories">
                        Show More <i class="fas fa-angle-down"></i>
                    </button>
                 <?php endif; ?>
            </section>
             <hr class="separator">
            <?php endif; ?>

            <section class="tool-grid-section">
                 <div class="tool-grid" id="toolGrid">
                    <?php if (!empty($tools)): ?>
                        <?php 
                        // 🔽 NAYA: Category wise loop 🔽
                        $current_category = '';
                        foreach ($tools as $tool):
                            if ($tool['category_name'] !== $current_category):
                                $current_category = $tool['category_name'];
                                echo '<h2 class="tool-category-heading">' . secure_input($current_category) . '</h2>';
                            endif;
                        ?>
                            <div class="tool-card" data-name="<?php echo strtolower(secure_input($tool['tool_name'])); ?>" data-category="<?php echo secure_input($tool['category_slug'] ?? ''); ?>">
                                <a href="/<?php echo secure_input($tool['slug']); ?>">
                                    <div class="tool-icon-container">
                                        <div class="tool-icon"><i class="<?php echo secure_input($tool['icon_class']); ?>"></i></div>
                                    </div>
                                    <h3><?php echo secure_input($tool['tool_name']); ?></h3>
                                    <p class="tool-short-desc"><?php echo secure_input($tool['short_description']); ?></p>
                                </a>
                            </div>
                        <?php endforeach; ?>
                     <?php else: ?>
                        <p style="grid-column: 1 / -1; text-align: center; color: #777;">No active tools found. Please add tools via the admin panel.</p>
                     <?php endif; ?>
                     <p id="noResults" style="grid-column: 1 / -1; text-align: center; color: #777; display: none;">No tools match your search.</p>
                </div>
            </section>
        </div>

         <script>
             const searchInput = document.getElementById('toolSearchInput');
             const toolGrid = document.getElementById('toolGrid');
             const toolCards = toolGrid.querySelectorAll('.tool-card');
             const categoryHeadings = toolGrid.querySelectorAll('.tool-category-heading'); // 🔽 NAYA 🔽
             const noResultsMsg = document.getElementById('noResults');

             searchInput.addEventListener('input', function() {
                 const searchTerm = searchInput.value.toLowerCase().trim();
                 let totalFound = false;

                 toolCards.forEach(card => {
                     const toolName = card.dataset.name;
                     const matches = toolName.includes(searchTerm);
                     card.style.display = matches ? 'flex' : 'none';
                     if (matches) {
                         totalFound = true;
                     }
                 });
                 
                 // 🔽 NAYA: Category headings ko hide/show karna 🔽
                 categoryHeadings.forEach(heading => {
                     let nextElement = heading.nextElementSibling;
                     let foundInThisCategory = false;
                     while (nextElement && !nextElement.classList.contains('tool-category-heading')) {
                         if (nextElement.classList.contains('tool-card') && nextElement.style.display !== 'none') {
                             foundInThisCategory = true;
                             break;
                         }
                         nextElement = nextElement.nextElementSibling;
                     }
                     heading.style.display = foundInThisCategory ? 'block' : 'none';
                 });

                 noResultsMsg.style.display = totalFound ? 'none' : 'block';
             });

            const showMoreBtn = document.getElementById('showMoreCategories');
             const categoryPillsContainer = document.getElementById('categoryPills');
             if (showMoreBtn && categoryPillsContainer) {
                 showMoreBtn.addEventListener('click', function() {
                     categoryPillsContainer.classList.add('show-all');
                     this.style.display = 'none';
                 });
             }
         </script>
        <?php
        break;

     case 'category':
        ?>
        <style>
             .category-page-header { text-align: center; margin-bottom: 25px; padding-top: 20px; animation: fadeInUp 0.8s ease-out forwards; }
             .category-page-header h1 { font-size: 2em; color: var(--primary-color); margin-bottom: 8px; }
             .category-page-header p { font-size: 1em; color: #555; max-width: 700px; margin: 0 auto; }
             .back-to-categories { 
                display: inline-block; margin-top: 20px; color: var(--secondary-color); text-decoration: none; font-weight: 600;
                transition: transform 0.3s ease, color 0.3s ease;
            }
             .back-to-categories:hover { text-decoration: underline; transform: translateX(-5px); color: var(--primary-color); }
        </style>
         <div class="category-page-header">
             <h1><?php echo secure_input($category_data['name']); ?> Tools</h1>
             <?php if (!empty($category_data['description'])): ?>
                 <p><?php echo secure_input($category_data['description']); ?></p>
             <?php endif; ?>
         </div>

         <div class="tool-grid">
             <?php if (!empty($tools)): ?>
                 <?php foreach ($tools as $tool): ?>
                     <div class="tool-card">
                         <a href="/<?php echo secure_input($tool['slug']); ?>">
                             <div class="tool-icon-container">
                                 <div class="tool-icon"><i class="<?php echo secure_input($tool['icon_class']); ?>"></i></div>
                             </div>
                             <h3><?php echo secure_input($tool['tool_name']); ?></h3>
                             <p class="tool-short-desc"><?php echo secure_input($tool['short_description']); ?></p>
                         </a>
                     </div>
                 <?php endforeach; ?>
             <?php else: ?>
                 <p style="grid-column: 1 / -1; text-align: center; color: #777; padding: 40px 0;">No tools found in the '<?php echo secure_input($category_data['name']); ?>' category yet.</p>
             <?php endif; ?>
         </div>
         <div style="text-align: center;">
             <a href="/#category-section" class="back-to-categories"><i class="fas fa-arrow-left"></i> Back to All Categories</a>
         </div>
        <?php
        break;

    case 'tool':
         ?>
         <style>
             .tool-page-container { padding: 20px 0; animation: fadeInUp 0.8s ease-out forwards; }
             .tool-page-container h1 { text-align: center; color: var(--primary-color); margin-bottom: 20px; font-size: 2em;}
             .ad-slot-container { margin: 15px auto; text-align: center; max-width: 900px; }
             .tool-function-area { background: white; padding: 25px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.05); margin-bottom: 20px; }
         </style>
         <div class="tool-page-container">
             <h1><?php echo secure_input($tool_data['tool_name']); ?></h1>

             <?php if (!empty(get_setting('ad_tool_top'))): ?>
             <div class="ad-slot-container ad-tool-top">
                 <?php echo get_setting('ad_tool_top'); ?>
             </div>
             <?php endif; ?>
             
             <div class="tool-function-area">
                 <?php echo $tool_data['tool_code']; ?>
             </div>

             <?php if (!empty(get_setting('ad_tool_bottom'))): ?>
             <div class="ad-slot-container ad-tool-bottom">
                 <?php echo get_setting('ad_tool_bottom'); ?>
             </div>
             <?php endif; ?>

             <div class="container">
                <?php
                $share_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $share_title = rawurlencode($page_seo['title']);
                ?>
                <section class="social-share-section">
                    <h3>Share this Tool!</h3>
                    <div class="social-share-buttons">
                        <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($share_url); ?>" target="_blank" class="share-btn facebook"><i class="fab fa-facebook-f"></i> Facebook</a>
                        <a href="https://twitter.com/intent/tweet?url=<?php echo urlencode($share_url); ?>&text=<?php echo $share_title; ?>" target="_blank" class="share-btn twitter"><i class="fab fa-twitter"></i> Twitter</a>
                        <a href="https://api.whatsapp.com/send?text=<?php echo $share_title; ?> <?php echo urlencode($share_url); ?>" target="_blank" class="share-btn whatsapp"><i class="fab fa-whatsapp"></i> WhatsApp</a>
                        <a href="https://t.me/share/url?url=<?php echo urlencode($share_url); ?>&text=<?php echo $share_title; ?>" target="_blank" class="share-btn telegram"><i class="fab fa-telegram-plane"></i> Telegram</a>
                        <a href="https://www.linkedin.com/shareArticle?mini=true&url=<?php echo urlencode($share_url); ?>&title=<?php echo $share_title; ?>" target="_blank" class="share-btn linkedin"><i class="fab fa-linkedin-in"></i> LinkedIn</a>
                    </div>
                </section>

                <?php
                $related_tools = [];
                if (!empty($tool_data['category_id'])) {
                    $stmt_related = $pdo->prepare("SELECT tool_name, slug, short_description, icon_class 
                                                   FROM tools 
                                                   WHERE category_id = ? AND id != ? AND is_active = 1 
                                                   LIMIT 4");
                    $stmt_related->execute([$tool_data['category_id'], $tool_data['id']]);
                    $related_tools = $stmt_related->fetchAll(PDO::FETCH_ASSOC);
                }
                ?>
                <?php if (!empty($related_tools)): ?>
                <section class="related-section">
                    <h2>Related Tools</h2>
                    <div class="tool-grid">
                        <?php foreach ($related_tools as $tool): ?>
                            <div class="tool-card">
                                <a href="/<?php echo secure_input($tool['slug']); ?>">
                                    <div class="tool-icon-container">
                                        <div class="tool-icon"><i class="<?php echo secure_input($tool['icon_class']); ?>"></i></div>
                                    </div>
                                    <h3><?php echo secure_input($tool['tool_name']); ?></h3>
                                    <p class="tool-short-desc"><?php echo secure_input($tool['short_description']); ?></p>
                                </a>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </section>
                <?php endif; ?>

                <?php
                $stmt_comments = $pdo->prepare("SELECT name, comment, created_at FROM comments 
                                                WHERE post_slug = ? AND post_type = 'tool' AND is_approved = 1 
                                                ORDER BY created_at DESC");
                $stmt_comments->execute([$tool_data['slug']]);
                $comments = $stmt_comments->fetchAll(PDO::FETCH_ASSOC);
                ?>
                <section class="comments-section">
                    <h2>Comments (<?php echo count($comments); ?>)</h2>
                    <ul class="comment-list">
                        <?php if (empty($comments)): ?>
                            <li class="no-comments">Be the first to leave a comment!</li>
                        <?php else: ?>
                            <?php foreach ($comments as $comment): ?>
                                <li class="comment-item">
                                    <div class="comment-meta">
                                        <?php echo secure_input($comment['name']); ?>
                                        <span class="comment-date"><?php echo date('F j, Y \a\t g:i a', strtotime($comment['created_at'])); ?></span>
                                    </div>
                                    <p class="comment-body"><?php echo nl2br(secure_input($comment['comment'])); ?></p>
                                </li>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </ul>

                    <div class="comment-form">
                        <h3>Leave a Comment</h3>
                        <form action="" method="POST">
                            <input type="hidden" name="post_slug" value="<?php echo secure_input($tool_data['slug']); ?>">
                            <input type="hidden" name="post_type" value="tool">
                            <div class="form-group">
                                <label for="name">Name</label>
                                <input type="text" name="name" id="name" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Email (will not be published)</label>
                                <input type="email" name="email" id="email" required>
                            </div>
                            <div class="form-group">
                                <label for="comment">Comment</label>
                                <textarea name="comment" id="comment" rows="5" required></textarea>
                            </div>
                            <button type="submit" name="submit_comment" class="btn-submit">Post Comment</button>
                        </form>
                    </div>
                </section>
             </div>
             </div>
         <?php
        break;


    case 'page':
         ?>
         <style>
             .static-page-container { padding: 30px 0; animation: fadeInUp 0.8s ease-out forwards; }
             .static-page-container h1 { color: #2c2c2c; text-align: center; margin-bottom: 20px; font-size: 2em;}
             .page-content { background: white; padding: 30px; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.05); line-height: 1.7; }
             .page-content h2 { color: var(--primary-color); margin-top: 20px; margin-bottom: 10px; font-size: 1.5em; border-bottom: 1px solid #eee; padding-bottom: 8px;}
             .page-content h3 { color: #333; margin-top: 15px; margin-bottom: 8px; font-size: 1.2em;}
             .page-content p { margin-bottom: 10px; color: #555;}
             .page-content ul, .page-content ol { margin-left: 25px; margin-bottom: 10px; color: #555;}
             .page-content li { margin-bottom: 6px; }
             .page-content a { color: var(--secondary-color); text-decoration: none; }
             .page-content a:hover { text-decoration: underline; }
             .page-content code { background-color: #f0f0f0; padding: 2px 5px; border-radius: 4px; font-family: monospace; }
             .page-content strong { font-weight: 600; }
             .page-content em { font-style: italic; }
         </style>
         <div class="static-page-container">
             <h1><?php echo secure_input($page_data['title']); ?></h1>
             <div class="page-content">
                 <?php echo $page_data['content']; ?>
             </div>
         </div>
         <?php
        break;

    case 'blog_index':
        ?>
        <div class="blog-header">
            <h1>Our Blog</h1>
            <p>Latest articles, tips, and updates.</p>
        </div>
        
        <div class="blog-grid">
            <?php if (!empty($blog_posts)): ?>
                <?php foreach ($blog_posts as $post): ?>
                    <article class="blog-card">
                        <a href="/blog/<?php echo secure_input($post['slug']); ?>" class="blog-thumbnail-wrapper">
                            <img src="<?php echo secure_input($post['thumbnail_url'] ?: '/assets/placeholder.jpg'); ?>" alt="<?php echo secure_input($post['title']); ?>" class="blog-thumbnail">
                        </a>
                        <div class="blog-content">
                            <h2><a href="/blog/<?php echo secure_input($post['slug']); ?>"><?php echo secure_input($post['title']); ?></a></h2>
                            <p class="blog-excerpt"><?php echo secure_input(strip_tags($post['excerpt'])); ?>...</p>
                            <span class="blog-meta">Published on: <?php echo date('F j, Y', strtotime($post['created_at'])); ?></span>
                            <a href="/blog/<?php echo secure_input($post['slug']); ?>" class="blog-read-more">Read More &rarr;</a>
                        </div>
                    </article>
                <?php endforeach; ?>
            <?php else: ?>
                <p style="grid-column: 1 / -1; text-align: center; color: #777; padding: 50px 0;">No blog posts found yet. Please check back later!</p>
            <?php endif; ?>
        </div>
        <?php
        break;

    case 'blog_post':
        ?>
        <style>
            .blog-post-container {
                max-width: 800px;
                margin: 0 auto;
                background: white;
                padding: 30px 40px;
                border-radius: 12px;
                box-shadow: var(--shadow-subtle);
                animation: fadeInUp 0.8s ease-out forwards;
            }
            .blog-post-header h1 {
                font-size: 2.2em;
                color: var(--text-color);
                margin-bottom: 10px;
            }
            .blog-post-meta {
                font-size: 0.9em;
                color: #777;
                margin-bottom: 20px;
                border-bottom: 1px solid #eee;
                padding-bottom: 15px;
            }
            .blog-post-thumbnail {
                width: 100%;
                height: auto;
                max-height: 400px;
                object-fit: cover;
                border-radius: 8px;
                margin-bottom: 25px;
            }
            .blog-post-content {
                line-height: 1.7;
            }
            .blog-post-content h2 { color: var(--primary-color); margin-top: 30px; margin-bottom: 10px; border-bottom: 1px solid #eee; padding-bottom: 5px; }
            .blog-post-content h3 { color: #333; margin-top: 20px; margin-bottom: 10px; }
            .blog-post-content p { margin-bottom: 15px; color: #555; }
            .blog-post-content ul, .blog-post-content ol { margin-left: 25px; margin-bottom: 15px; }
            .blog-post-content a { color: var(--secondary-color); }
            .blog-post-content a:hover { text-decoration: underline; }
            .blog-post-content code { background: #f4f4f4; padding: 2px 5px; border-radius: 4px; }
            .blog-post-content blockquote {
                border-left: 4px solid var(--primary-color);
                margin: 15px 0 15px 20px;
                padding-left: 15px;
                font-style: italic;
                color: #666;
            }
            .back-to-blog {
                display: inline-block;
                margin-top: 30px;
                color: var(--secondary-color);
                font-weight: 600;
                text-decoration: none;
            }
            .back-to-blog:hover { text-decoration: underline; }
        </style>
        <article class="blog-post-container">
            <header class="blog-post-header">
                <h1><?php echo secure_input($blog_post_data['title']); ?></h1>
                <p class="blog-post-meta">
                    Published on <?php echo date('F j, Y', strtotime($blog_post_data['created_at'])); ?>
                </p>
            </header>

            <?php if (!empty($blog_post_data['thumbnail_url'])): ?>
                <img src="<?php echo secure_input($blog_post_data['thumbnail_url']); ?>" alt="<?php echo secure_input($blog_post_data['title']); ?>" class="blog-post-thumbnail">
            <?php endif; ?>

            <div class="blog-post-content">
                <?php echo $blog_post_data['content']; ?>
            </div>
            
            <?php
            $share_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $share_title = rawurlencode($page_seo['title']);
            ?>
            <section class="social-share-section">
                <h3>Share this Post!</h3>
                <div class="social-share-buttons">
                    <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($share_url); ?>" target="_blank" class="share-btn facebook"><i class="fab fa-facebook-f"></i> Facebook</a>
                    <a href="https://twitter.com/intent/tweet?url=<?php echo urlencode($share_url); ?>&text=<?php echo $share_title; ?>" target="_blank" class="share-btn twitter"><i class="fab fa-twitter"></i> Twitter</a>
                    <a href="https://api.whatsapp.com/send?text=<?php echo $share_title; ?> <?php echo urlencode($share_url); ?>" target="_blank" class="share-btn whatsapp"><i class="fab fa-whatsapp"></i> WhatsApp</a>
                    <a href="https://t.me/share/url?url=<?php echo urlencode($share_url); ?>&text=<?php echo $share_title; ?>" target="_blank" class="share-btn telegram"><i class="fab fa-telegram-plane"></i> Telegram</a>
                    <a href="https://www.linkedin.com/shareArticle?mini=true&url=<?php echo urlencode($share_url); ?>&title=<?php echo $share_title; ?>" target="_blank" class="share-btn linkedin"><i class="fab fa-linkedin-in"></i> LinkedIn</a>
                </div>
            </section>

            <?php
            $stmt_related = $pdo->prepare("SELECT title, slug, thumbnail_url, LEFT(content, 150) as excerpt, created_at 
                                           FROM blog_posts 
                                           WHERE id != ? AND is_active = 1 
                                           ORDER BY created_at DESC
                                           LIMIT 3");
            $stmt_related->execute([$blog_post_data['id']]);
            $related_posts = $stmt_related->fetchAll(PDO::FETCH_ASSOC);
            ?>
            <?php if (!empty($related_posts)): ?>
            <section class="related-section">
                <h2>Recent Posts</h2>
                <div class="blog-grid">
                    <?php foreach ($related_posts as $post): ?>
                        <article class="blog-card">
                            <a href="/blog/<?php echo secure_input($post['slug']); ?>" class="blog-thumbnail-wrapper">
                                <img src="<?php echo secure_input($post['thumbnail_url'] ?: '/assets/placeholder.jpg'); ?>" alt="<?php echo secure_input($post['title']); ?>" class="blog-thumbnail">
                            </a>
                            <div class="blog-content">
                                <h2><a href="/blog/<?php echo secure_input($post['slug']); ?>"><?php echo secure_input($post['title']); ?></a></h2>
                                <p class="blog-excerpt"><?php echo secure_input(strip_tags($post['excerpt'])); ?>...</p>
                                <a href="/blog/<?php echo secure_input($post['slug']); ?>" class="blog-read-more">Read More &rarr;</a>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
            </section>
            <?php endif; ?>

            <?php
            $stmt_comments = $pdo->prepare("SELECT name, comment, created_at FROM comments 
                                            WHERE post_slug = ? AND post_type = 'blog' AND is_approved = 1 
                                            ORDER BY created_at DESC");
            $stmt_comments->execute([$blog_post_data['slug']]);
            $comments = $stmt_comments->fetchAll(PDO::FETCH_ASSOC);
            ?>
            <section class="comments-section">
                <h2>Comments (<?php echo count($comments); ?>)</h2>
                <ul class="comment-list">
                    <?php if (empty($comments)): ?>
                        <li class="no-comments">Be the first to leave a comment!</li>
                    <?php else: ?>
                        <?php foreach ($comments as $comment): ?>
                            <li class="comment-item">
                                <div class="comment-meta">
                                    <?php echo secure_input($comment['name']); ?>
                                    <span class="comment-date"><?php echo date('F j, Y \a\t g:i a', strtotime($comment['created_at'])); ?></span>
                                </div>
                                <p class="comment-body"><?php echo nl2br(secure_input($comment['comment'])); ?></p>
                            </li>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </ul>

                <div class="comment-form">
                    <h3>Leave a Comment</h3>
                    <form action="" method="POST">
                        <input type="hidden" name="post_slug" value="<?php echo secure_input($blog_post_data['slug']); ?>">
                        <input type="hidden" name="post_type" value="blog">
                        <div class="form-group">
                            <label for="name">Name</label>
                            <input type="text" name="name" id="name" required>
                        </div>
                        <div class="form-group">
                            <label for="email">Email (will not be published)</label>
                            <input type="email" name="email" id="email" required>
                        </div>
                        <div class="form-group">
                            <label for="comment">Comment</label>
                            <textarea name="comment" id="comment" rows="5" required></textarea>
                        </div>
                        <button type="submit" name="submit_comment" class="btn-submit">Post Comment</button>
                    </form>
                </div>
            </section>
            <a href="/blog" class="back-to-blog"><i class="fas fa-arrow-left"></i> Back to Blog</a>
        </article>
        <?php
        break;

    case '404':
    default:
        ?>
         <style>
             .not-found-container { text-align: center; padding: 60px 20px; animation: fadeInUp 0.8s ease-out forwards; }
             .not-found-container h1 { font-size: 5em; color: #e74c3c; margin-bottom: 5px; font-weight: 800;}
             .not-found-container h2 { font-size: 1.8em; color: #333; margin-bottom: 10px;}
             .not-found-container p { font-size: 1em; color: #666; margin-bottom: 20px;}
             .not-found-container .btn-home {
                 display: inline-block;
                 padding: 10px 20px;
                 background-color: var(--primary-color);
                 color: white;
                 text-decoration: none;
                 border-radius: 5px;
                 font-weight: 600;
                 transition: background-color 0.3s;
             }
             .not-found-container .btn-home:hover { background-color: var(--secondary-color); }
         </style>
         <div class="not-found-container">
             <h1>404</h1>
             <h2>Oops! Page Not Found</h2>
             <p>Sorry, the page you are looking for doesn't exist or has been moved.</p>
             <a href="/" class="btn-home"><i class="fas fa-home"></i> Go to Homepage</a>
         </div>
        <?php
        break;
}

echo '</main>';

// 🔽 NAYA 🔽: Country Code Library JS
if ($action === 'page' && isset($page_data['slug']) && $page_data['slug'] === 'contact-us'):
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/intlTelInput.min.js"></script>
<script>
    var input = document.querySelector("#phone");
    if (input) {
        var iti = window.intlTelInput(input, {
            initialCountry: "us", // India default
            separateDialCode: true,
            utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js",
        });
        
        var form = input.closest("form");
        form.addEventListener("submit", function() {
            input.value = iti.getNumber();
        });
    }
</script>
<?php
endif;

include 'footer.php';
?>
