<?php
/**
 * IBVTE - Dynamic Custom Page Handler
 */

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/db.php';

$db = DB();

// Self-healing database initialization
try {
    $db->query("SELECT 1 FROM `custom_pages` LIMIT 1");
} catch (Exception $e) {
    // Table doesn't exist, create it dynamically
    $db->query("CREATE TABLE IF NOT EXISTS `custom_pages` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `slug` VARCHAR(100) UNIQUE NOT NULL,
        `title` VARCHAR(255) NOT NULL,
        `content` LONGTEXT NULL,
        `only_pdf` TINYINT(1) DEFAULT 0,
        `pdf_path` VARCHAR(255) NULL,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    
    // Seed default pages
    $defaultPages = [
        'exam-bye-laws' => 'IBVTE Examination BYE-Laws',
        'affiliation-bye-laws' => 'IBVTE Affiliation BYE-Laws',
        'rules-regulations' => 'IBVTE Rules & Regulations',
        'exam-circular' => 'Exam Circular',
        'exam-timetable' => 'Exam Time Table',
        'exam-services' => 'Exam Related Services',
        'paripatra' => 'परिपत्र',
        'kaaryakaaree' => 'कार्यकारिणी एवं कार्यवृत्त',
        'student-downloads' => 'Student Downloads',
        'general' => 'General',
        'main-exam' => 'Main Exam',
        'affiliation' => 'Affiliation',
        'prastav' => 'Prastav',
        'check-result' => 'Check Result',
        'registration' => 'Registration',
        'lgs' => 'LGS',
        'verify' => 'Verify',
        'brochure' => 'Brochure'
    ];
    
    foreach ($defaultPages as $slugKey => $titleVal) {
        $db->insert('custom_pages', [
            'slug' => $slugKey,
            'title' => $titleVal,
            'content' => '<p>Welcome to the ' . htmlspecialchars($titleVal) . ' page. Content is under preparation by the administration.</p>',
            'only_pdf' => 0,
            'pdf_path' => ''
        ]);
    }
}

$slug = $_GET['slug'] ?? '';

if (empty($slug)) {
    header('Location: index.php');
    exit;
}

$pageData = $db->fetchOne("SELECT * FROM custom_pages WHERE slug = :slug", ['slug' => $slug]);

if ($pageData) {
    try {
        $attachedPdfs = $db->fetchAll("SELECT * FROM custom_page_pdfs WHERE page_slug = :slug ORDER BY id ASC", ['slug' => $slug]);
    } catch (Exception $e) {
        $db->query("CREATE TABLE IF NOT EXISTS `custom_page_pdfs` (
            `id` INT AUTO_INCREMENT PRIMARY KEY,
            `page_slug` VARCHAR(100) NOT NULL,
            `title` VARCHAR(255) NOT NULL,
            `pdf_path` VARCHAR(255) NOT NULL,
            `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX (`page_slug`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
        $attachedPdfs = [];
    }
} else {
    $attachedPdfs = [];
}

if (!$pageData) {
    // If page is not initialized, show 404 or redirect
    $pageTitle = 'Page Not Found | IBVTE';
    require_once __DIR__ . '/includes/header.php';
    ?>
    <div class="container py-5 my-5 text-center">
        <div class="py-5 bg-white rounded-3 shadow-sm border border-light">
            <i class="fas fa-exclamation-triangle text-warning fa-4x mb-3 animate-pulse"></i>
            <h2 class="fw-bold text-primary">Page Not Found (पेज नहीं मिला)</h2>
            <p class="text-muted mt-2">The requested dynamic page could not be located on our servers.</p>
            <a href="index.php" class="btn btn-primary rounded-pill px-5 fw-bold mt-4"><i class="fas fa-home me-2"></i>Return Home</a>
        </div>
    </div>
    <?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

// Page details found
$pageTitle = $pageData['title'] . ' | IBVTE - Indian Board of Vocational and Technical Education';
$pageDesc  = 'Official publication and documents of the Indian Board of Vocational and Technical Education (IBVTE), New Delhi: ' . $pageData['title'];
require_once __DIR__ . '/includes/header.php';
?>
<link rel="stylesheet" href="<?php echo $base; ?>assets/css/pages.css">

<!-- Dynamic Page Hero -->
<div class="ibvte-page-hero">
    <div class="container">
        <nav aria-label="breadcrumb" class="ibvte-breadcrumb mb-2">
            <ol class="breadcrumb mb-0 small">
                <li class="breadcrumb-item"><a href="<?php echo $base; ?>index.php">Home</a></li>
                <li class="breadcrumb-item"><a href="#">Official</a></li>
                <li class="breadcrumb-item active"><?= htmlspecialchars($pageData['title']) ?></li>
            </ol>
        </nav>
        <h1><i class="fas fa-file-alt me-2"></i><?= htmlspecialchars($pageData['title']) ?></h1>
        <p>Indian Board of Vocational and Technical Education (New Delhi)</p>
    </div>
</div>

<!-- Main Content Area -->
<section class="ibvte-section bg-light">
    <div class="container">
        <div class="row g-4">
            
            <!-- Dynamic Sidebar -->
            <div class="col-lg-3">
                <div class="ibvte-inner-sidebar sticky-top" style="top:20px;">
                    <div class="bg-white rounded-3 shadow-sm overflow-hidden">
                        <div class="px-3 py-3" style="background:var(--primary-color);">
                            <span class="text-white fw-bold small text-uppercase"><i class="fas fa-bookmark me-2"></i>Quick Navigation</span>
                        </div>
                        <div class="list-group list-group-flush">
                            <?php
                            $siblingPages = [];
                            $currentGroup = $pageData['menu_group'] ?? 'none';
                            if ($currentGroup !== 'none') {
                                $siblingPages = $db->fetchAll("SELECT slug, title FROM custom_pages WHERE menu_group = :group ORDER BY id ASC", ['group' => $currentGroup]);
                            }
                            if (!empty($siblingPages)) {
                                foreach ($siblingPages as $sib) {
                                    $activeClass = ($slug === $sib['slug']) ? 'active' : '';
                                    echo '<a href="page.php?slug=' . urlencode($sib['slug']) . '" class="list-group-item list-group-item-action ' . $activeClass . '">' . htmlspecialchars($sib['title']) . '</a>';
                                }
                            } else {
                                ?>
                                <a href="page.php?slug=exam-bye-laws" class="list-group-item list-group-item-action <?= ($slug === 'exam-bye-laws') ? 'active' : '' ?>">Exam BYE-Laws</a>
                                <a href="page.php?slug=affiliation-bye-laws" class="list-group-item list-group-item-action <?= ($slug === 'affiliation-bye-laws') ? 'active' : '' ?>">Affiliation BYE-Laws</a>
                                <a href="page.php?slug=rules-regulations" class="list-group-item list-group-item-action <?= ($slug === 'rules-regulations') ? 'active' : '' ?>">Rules & Regulations</a>
                                <a href="page.php?slug=exam-circular" class="list-group-item list-group-item-action <?= ($slug === 'exam-circular') ? 'active' : '' ?>">Exam Circular</a>
                                <a href="page.php?slug=exam-timetable" class="list-group-item list-group-item-action <?= ($slug === 'exam-timetable') ? 'active' : '' ?>">Exam Time Table</a>
                                <a href="page.php?slug=exam-services" class="list-group-item list-group-item-action <?= ($slug === 'exam-services') ? 'active' : '' ?>">Exam Services</a>
                                <a href="page.php?slug=paripatra" class="list-group-item list-group-item-action <?= ($slug === 'paripatra') ? 'active' : '' ?>">परिपत्र (Circulars)</a>
                                <a href="page.php?slug=kaaryakaaree" class="list-group-item list-group-item-action <?= ($slug === 'kaaryakaaree') ? 'active' : '' ?>">कार्यकारिणी एवं कार्यवृत्त</a>
                                <a href="page.php?slug=student-downloads" class="list-group-item list-group-item-action <?= ($slug === 'student-downloads') ? 'active' : '' ?>">Student Downloads</a>
                                <?php
                            }
                            ?>
                        </div>
                    </div>
                    
                    <?php if ($pageData['pdf_path']): ?>
                        <!-- Quick Download Box -->
                        <div class="card border-0 shadow-sm mt-4 text-center p-3 bg-white">
                            <div class="card-body">
                                <i class="fas fa-file-pdf text-danger fa-3x mb-3"></i>
                                <h6 class="fw-bold mb-2">Offline Document</h6>
                                <p class="text-muted small mb-3">Download the offline copy of this publication to your local storage.</p>
                                <a href="<?= $base . htmlspecialchars($pageData['pdf_path']) ?>" download class="btn btn-outline-danger btn-sm w-100 fw-bold rounded-pill">
                                    <i class="fas fa-download me-1"></i>Download PDF
                                </a>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Content Card -->
            <div class="col-lg-9">
                <div class="ibvte-section-card bg-white p-4 p-md-5 rounded-3 shadow-sm h-100 border-0" data-aos="fade-up">
                    
                    <?php if ($pageData['only_pdf'] && !empty($pageData['pdf_path'])): ?>
                        <!-- PDF Embedding Mode -->
                        <div class="d-flex justify-content-between align-items-center mb-4 border-bottom pb-2">
                            <h2 class="text-primary fw-bold mb-0" style="font-size:1.35rem;"><i class="fas fa-file-pdf text-danger me-2"></i>Official PDF Document</h2>
                            <a href="<?= $base . htmlspecialchars($pageData['pdf_path']) ?>" target="_blank" class="btn btn-outline-primary btn-sm rounded-pill fw-bold px-3">
                                <i class="fas fa-expand me-1"></i>Open Fullscreen
                            </a>
                        </div>
                        
                        <div class="ratio ratio-4x3 border rounded-3 overflow-hidden shadow-sm bg-light" style="min-height: 650px;">
                            <iframe src="<?= $base . htmlspecialchars($pageData['pdf_path']) ?>#toolbar=1" class="w-100 h-100 ibvte-pdf-viewer" style="border:none;" allowfullscreen>
                                <div class="p-5 text-center">
                                    <p>Your browser does not support embedded PDF files. Please click below to download or view.</p>
                                    <a href="<?= $base . htmlspecialchars($pageData['pdf_path']) ?>" class="btn btn-danger btn-lg"><i class="fas fa-download me-2"></i>Download PDF</a>
                                </div>
                            </iframe>
                        </div>
                        
                    <?php else: ?>
                        <!-- Rich Text HTML Content Mode -->
                        <h2 class="text-primary fw-bold mb-4" style="font-size:1.5rem;"><i class="fas fa-landmark me-2"></i><?= htmlspecialchars($pageData['title']) ?></h2>
                        
                        <div class="ibvte-dynamic-rich-content pe-md-2" style="font-size:15px; color:#222222; line-height:1.8;">
                            <?= $pageData['content'] ?>
                        </div>
                        
                        <?php if (!empty($attachedPdfs)): ?>
                            <!-- Multiple PDF Downloads Section -->
                            <div class="mt-5">
                                <h4 class="text-primary fw-bold mb-3 border-bottom pb-2" style="font-size:1.25rem;">
                                    <i class="fas fa-file-pdf text-danger me-2"></i>संलग्न दस्तावेज / Attached Documents
                                </h4>
                                <div class="list-group shadow-xs rounded-3 overflow-hidden">
                                    <?php foreach ($attachedPdfs as $pdfRow): ?>
                                        <div class="list-group-item d-flex flex-column flex-md-row justify-content-between align-items-md-center p-3 border-light-subtle bg-white" style="transition: background-color 0.2s ease;">
                                            <div class="d-flex align-items-center gap-3">
                                                <div class="bg-danger bg-opacity-10 text-danger rounded-circle p-2 d-flex align-items-center justify-content-center" style="width:40px; height:40px; flex-shrink:0;">
                                                    <i class="fas fa-file-pdf fa-lg"></i>
                                                </div>
                                                <div>
                                                    <h6 class="fw-bold mb-1 text-dark" style="font-size: 0.95rem; line-height: 1.4;"><?= htmlspecialchars($pdfRow['title']) ?></h6>
                                                    <small class="text-muted"><i class="fas fa-calendar-alt me-1"></i>Uploaded on: <?= date('d M Y, h:i A', strtotime($pdfRow['created_at'])) ?></small>
                                                </div>
                                            </div>
                                            <div class="d-flex gap-2 mt-2 mt-md-0">
                                                <a href="<?= $base . htmlspecialchars($pdfRow['pdf_path']) ?>" target="_blank" class="btn btn-sm btn-outline-primary px-3 rounded-pill fw-bold">
                                                    <i class="fas fa-eye me-1"></i>View
                                                </a>
                                                <a href="<?= $base . htmlspecialchars($pdfRow['pdf_path']) ?>" download class="btn btn-sm btn-danger px-3 rounded-pill fw-bold text-white">
                                                    <i class="fas fa-download me-1"></i>Download
                                                </a>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($pageData['pdf_path']): ?>
                            <!-- Supplemental PDF download link at the bottom of the article -->
                            <div class="mt-5 p-3 rounded-3 bg-light border d-flex flex-column flex-md-row align-items-center justify-content-between gap-3">
                                <div class="d-flex align-items-center gap-3">
                                    <i class="fas fa-file-pdf text-danger fa-2x"></i>
                                    <div>
                                        <h6 class="fw-bold mb-0">Official Document Available</h6>
                                        <small class="text-muted">You can also download the official authorized PDF document for this page.</small>
                                    </div>
                                </div>
                                <a href="<?= $base . htmlspecialchars($pageData['pdf_path']) ?>" target="_blank" class="btn btn-danger btn-sm fw-bold px-4 rounded-pill">
                                    <i class="fas fa-file-download me-1"></i>Download Official PDF
                                </a>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                </div>
            </div>
            
        </div>
    </div>
</section>

<style>
    /* Styling overrides for the Summernote output content inside public pages */
    .ibvte-dynamic-rich-content p {
        text-align: justify !important;
        margin-bottom: 1.5rem;
    }
    .ibvte-dynamic-rich-content h1, 
    .ibvte-dynamic-rich-content h2, 
    .ibvte-dynamic-rich-content h3, 
    .ibvte-dynamic-rich-content h4, 
    .ibvte-dynamic-rich-content h5, 
    .ibvte-dynamic-rich-content h6 {
        color: var(--primary-color) !important;
        font-weight: 700 !important;
        margin-top: 1.8rem;
        margin-bottom: 1rem;
    }
    .ibvte-dynamic-rich-content ul, 
    .ibvte-dynamic-rich-content ol {
        margin-bottom: 1.5rem;
        padding-left: 2rem;
    }
    .ibvte-dynamic-rich-content li {
        margin-bottom: 0.5rem;
    }
    .ibvte-dynamic-rich-content img {
        max-width: 100% !important;
        height: auto !important;
        border-radius: 8px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.08);
        margin: 15px 0;
    }
    .ibvte-dynamic-rich-content table {
        width: 100% !important;
        margin: 20px 0;
        border-collapse: collapse;
    }
    .ibvte-dynamic-rich-content table th, 
    .ibvte-dynamic-rich-content table td {
        border: 1px solid #dee2e6;
        padding: 10px 15px;
    }
    .ibvte-dynamic-rich-content table th {
        background-color: #f8f9fa;
        font-weight: bold;
    }
</style>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
