<?php
/**
 * IBVTE Admin - Manage Custom Dynamic Pages (Add, Edit, Delete with Sub-menu Groups)
 */

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

// Require admin access
Auth()->requireRole(['super_admin', 'admin']);

$db = DB();
$user = Auth()->getUser();

// Auto-initialize table and default pages if they don't exist
function initCustomPagesTable($db) {
    // Create custom_pages table if it doesn't exist
    $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,
        `menu_group` VARCHAR(50) DEFAULT 'none',
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    
    // Create custom_page_pdfs table if it doesn't exist
    $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;");
    
    // Add menu_group column if table already existed but didn't have it
    try {
        $db->query("SELECT menu_group FROM custom_pages LIMIT 1");
    } catch (Exception $e) {
        $db->query("ALTER TABLE custom_pages ADD COLUMN menu_group VARCHAR(50) DEFAULT 'none'");
    }

    // Add show_in_sidebar column if not exists
    try {
        $db->query("SELECT show_in_sidebar FROM custom_pages LIMIT 1");
    } catch (Exception $e) {
        $db->query("ALTER TABLE custom_pages ADD COLUMN show_in_sidebar TINYINT(1) DEFAULT 0");
    }

    // Add sidebar_color column if not exists
    try {
        $db->query("SELECT sidebar_color FROM custom_pages LIMIT 1");
    } catch (Exception $e) {
        $db->query("ALTER TABLE custom_pages ADD COLUMN sidebar_color VARCHAR(20) DEFAULT '#2196f3'");
    }

    // Add sidebar_icon column if not exists
    try {
        $db->query("SELECT sidebar_icon FROM custom_pages LIMIT 1");
    } catch (Exception $e) {
        $db->query("ALTER TABLE custom_pages ADD COLUMN sidebar_icon VARCHAR(50) DEFAULT 'fas fa-link'");
    }

    // Add sidebar_order column if not exists
    try {
        $db->query("SELECT sidebar_order FROM custom_pages LIMIT 1");
    } catch (Exception $e) {
        $db->query("ALTER TABLE custom_pages ADD COLUMN sidebar_order INT DEFAULT 0");
    }
    
    // Seed default pages
    $defaultPages = [
        'exam-circular' => ['title' => 'Exam Circular', 'group' => 'examination'],
        'exam-timetable' => ['title' => 'Exam Time Table', 'group' => 'examination'],
        'exam-services' => ['title' => 'Exam Related Services', 'group' => 'examination'],
        'exam-bye-laws' => ['title' => 'IBVTE Examination BYE-Laws', 'group' => 'constitution'],
        'affiliation-bye-laws' => ['title' => 'IBVTE Affiliation BYE-Laws', 'group' => 'constitution'],
        'rules-regulations' => ['title' => 'IBVTE Rules & Regulations', 'group' => 'constitution'],
        'paripatra' => ['title' => 'परिपत्र', 'group' => 'circular'],
        'kaaryakaaree' => ['title' => 'कार्यकारिणी एवं कार्यवृत्त', 'group' => 'circular'],
        'student-downloads' => ['title' => 'Student Downloads', 'group' => 'none'],
        'general' => ['title' => 'General', 'group' => 'home_boxes'],
        'main-exam' => ['title' => 'Main Exam', 'group' => 'home_boxes'],
        'affiliation' => ['title' => 'Affiliation', 'group' => 'home_boxes'],
        'prastav' => ['title' => 'Prastav', 'group' => 'home_boxes'],
        'enrollment' => ['title' => 'Enrollment', 'group' => 'home_boxes'],
        'registration' => ['title' => 'Registration', 'group' => 'home_boxes'],
        'lgs' => ['title' => 'LGS', 'group' => 'home_boxes'],
        'verify' => ['title' => 'Verify', 'group' => 'home_boxes'],
        'brochure' => ['title' => 'Brochure', 'group' => 'home_boxes']
    ];
    
    foreach ($defaultPages as $slug => $data) {
        $exists = $db->fetchOne("SELECT id FROM custom_pages WHERE slug = :slug", ['slug' => $slug]);
        if (!$exists) {
            $db->insert('custom_pages', [
                'slug' => $slug,
                'title' => $data['title'],
                'content' => '<p>Welcome to the ' . htmlspecialchars($data['title']) . ' page. Content is under preparation by the administration.</p>',
                'only_pdf' => 0,
                'pdf_path' => '',
                'menu_group' => $data['group']
            ]);
        } else {
            // Ensure proper default menu groups are assigned
            $existing = $db->fetchOne("SELECT menu_group FROM custom_pages WHERE slug = :slug", ['slug' => $slug]);
            if (empty($existing['menu_group']) || $existing['menu_group'] === 'none' && $data['group'] !== 'none') {
                $db->update('custom_pages', ['menu_group' => $data['group']], ['slug' => $slug]);
            }
        }
    }
}

initCustomPagesTable($db);

$errors = [];
$action = $_GET['action'] ?? 'list';
$editSlug = $_GET['slug'] ?? '';
$pageData = null;

// Handle Delete Action
if ($action === 'delete' && $editSlug) {
    $existing = $db->fetchOne("SELECT * FROM custom_pages WHERE slug = :slug", ['slug' => $editSlug]);
    if ($existing) {
        // Delete PDF file if exists
        if ($existing['pdf_path'] && file_exists(__DIR__ . '/../' . $existing['pdf_path'])) {
            @unlink(__DIR__ . '/../' . $existing['pdf_path']);
        }
        
        // Delete attached multiple PDFs
        $attached = $db->fetchAll("SELECT * FROM custom_page_pdfs WHERE page_slug = :slug", ['slug' => $editSlug]);
        foreach ($attached as $att) {
            if ($att['pdf_path'] && file_exists(__DIR__ . '/../' . $att['pdf_path'])) {
                @unlink(__DIR__ . '/../' . $att['pdf_path']);
            }
        }
        $db->query("DELETE FROM custom_page_pdfs WHERE page_slug = :slug", ['slug' => $editSlug]);
        
        $db->query("DELETE FROM custom_pages WHERE slug = :slug", ['slug' => $editSlug]);
        redirectWithMessage('manage-pages.php', 'Page "' . htmlspecialchars($existing['title']) . '" deleted successfully!', 'success');
    } else {
        redirectWithMessage('manage-pages.php', 'Page not found!', 'danger');
    }
}

// Fetch Page Data for Edit
if ($action === 'edit' && $editSlug) {
    $pageData = $db->fetchOne("SELECT * FROM custom_pages WHERE slug = :slug", ['slug' => $editSlug]);
    if (!$pageData) {
        redirectWithMessage('manage-pages.php', 'Page not found!', 'danger');
    }
    $attachedPdfs = $db->fetchAll("SELECT * FROM custom_page_pdfs WHERE page_slug = :slug ORDER BY id ASC", ['slug' => $editSlug]);
} else {
    $attachedPdfs = [];
}

// Handle Add/Edit POST Requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    $menu_group = $_POST['menu_group'] ?? 'none';
    $content = $_POST['content'] ?? '';
    $only_pdf = isset($_POST['only_pdf']) ? 1 : 0;
    
    if (empty($title)) {
        $errors[] = 'Page Title is required.';
    }
    
    // Slug generation and sanitization
    if (empty($slug)) {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));
    } else {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $slug)));
    }
    
    // Handle Add Mode logic
    if ($action === 'add') {
        $existing = $db->fetchOne("SELECT id FROM custom_pages WHERE slug = :slug", ['slug' => $slug]);
        if ($existing) {
            $errors[] = 'A page with this URL slug already exists. Please choose a different title or slug.';
        }
        
        $pdf_path = '';
        
        // Handle PDF upload
        if (empty($errors) && isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['pdf_file'];
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            
            if ($ext !== 'pdf') {
                $errors[] = 'Only PDF documents are allowed.';
            } else {
                $uploadDir = __DIR__ . '/../assets/uploads/documents/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $fileName = $slug . '_' . time() . '.pdf';
                $destPath = $uploadDir . $fileName;
                
                if (move_uploaded_file($file['tmp_name'], $destPath)) {
                    $pdf_path = 'assets/uploads/documents/' . $fileName;
                } else {
                    $errors[] = 'Failed to save uploaded PDF file.';
                }
            }
        }
        
        if ($only_pdf && empty($pdf_path)) {
            $errors[] = 'You must upload a PDF document if "Only PDF" view is selected.';
        }
        
        if (empty($errors)) {
            $db->insert('custom_pages', [
                'slug' => $slug,
                'title' => $title,
                'content' => $content,
                'only_pdf' => $only_pdf,
                'pdf_path' => $pdf_path,
                'menu_group' => $menu_group,
                'show_in_sidebar' => isset($_POST['show_in_sidebar']) ? 1 : 0,
                'sidebar_color' => $_POST['sidebar_color'] ?? '#2196f3',
                'sidebar_icon' => $_POST['sidebar_icon'] ?? 'fas fa-link',
                'sidebar_order' => intval($_POST['sidebar_order'] ?? 0)
            ]);
            
            // Handle Multiple PDFs
            $multiTitles = $_POST['multi_titles'] ?? [];
            if (isset($_FILES['multi_files'])) {
                $files = $_FILES['multi_files'];
                for ($i = 0; $i < count($files['name']); $i++) {
                    if ($files['error'][$i] === UPLOAD_ERR_OK && !empty($multiTitles[$i])) {
                        $mTitle = trim($multiTitles[$i]);
                        $ext = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));
                        if ($ext === 'pdf') {
                            $uploadDir = __DIR__ . '/../assets/uploads/documents/';
                            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                            $fileName = $slug . '_multi_' . time() . '_' . bin2hex(random_bytes(4)) . '.pdf';
                            if (move_uploaded_file($files['tmp_name'][$i], $uploadDir . $fileName)) {
                                $db->insert('custom_page_pdfs', [
                                    'page_slug' => $slug,
                                    'title' => $mTitle,
                                    'pdf_path' => 'assets/uploads/documents/' . $fileName
                                ]);
                            }
                        }
                    }
                }
            }
            
            redirectWithMessage('manage-pages.php', 'New page created and added to the menu successfully!', 'success');
        }
    }
    
    // Handle Edit Mode logic
    if ($action === 'edit' && $editSlug) {
        $existing = $db->fetchOne("SELECT * FROM custom_pages WHERE slug = :slug", ['slug' => $editSlug]);
        if (!$existing) {
            $errors[] = 'Invalid page selected.';
        }
        
        $pdf_path = $existing ? $existing['pdf_path'] : '';
        
        // Handle PDF upload
        if (empty($errors) && isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['pdf_file'];
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            
            if ($ext !== 'pdf') {
                $errors[] = 'Only PDF documents are allowed.';
            } else {
                $uploadDir = __DIR__ . '/../assets/uploads/documents/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $fileName = $slug . '_' . time() . '.pdf';
                $destPath = $uploadDir . $fileName;
                
                if (move_uploaded_file($file['tmp_name'], $destPath)) {
                    // Delete old PDF file if it existed
                    if ($pdf_path && file_exists(__DIR__ . '/../' . $pdf_path)) {
                        @unlink(__DIR__ . '/../' . $pdf_path);
                    }
                    $pdf_path = 'assets/uploads/documents/' . $fileName;
                } else {
                    $errors[] = 'Failed to save uploaded PDF file.';
                }
            }
        }
        
        if ($only_pdf && empty($pdf_path)) {
            $errors[] = 'You must upload a PDF document if "Only PDF" view is selected.';
        }
        
        if (empty($errors)) {
            $db->update('custom_pages', [
                'title' => $title,
                'content' => $content,
                'only_pdf' => $only_pdf,
                'pdf_path' => $pdf_path,
                'menu_group' => $menu_group,
                'show_in_sidebar' => isset($_POST['show_in_sidebar']) ? 1 : 0,
                'sidebar_color' => $_POST['sidebar_color'] ?? '#2196f3',
                'sidebar_icon' => $_POST['sidebar_icon'] ?? 'fas fa-link',
                'sidebar_order' => intval($_POST['sidebar_order'] ?? 0)
            ], ['slug' => $editSlug]);
            
            // Handle Deleting Multiple PDFs
            $deletePdfIds = $_POST['delete_pdf_ids'] ?? [];
            foreach ($deletePdfIds as $delId) {
                $delId = intval($delId);
                $pdfRow = $db->fetchOne("SELECT * FROM custom_page_pdfs WHERE id = :id AND page_slug = :slug", ['id' => $delId, 'slug' => $editSlug]);
                if ($pdfRow) {
                    if ($pdfRow['pdf_path'] && file_exists(__DIR__ . '/../' . $pdfRow['pdf_path'])) {
                        @unlink(__DIR__ . '/../' . $pdfRow['pdf_path']);
                    }
                    $db->query("DELETE FROM custom_page_pdfs WHERE id = :id", ['id' => $delId]);
                }
            }
            
            // Handle Adding/Uploading New Multiple PDFs
            $multiTitles = $_POST['multi_titles'] ?? [];
            if (isset($_FILES['multi_files'])) {
                $files = $_FILES['multi_files'];
                for ($i = 0; $i < count($files['name']); $i++) {
                    if ($files['error'][$i] === UPLOAD_ERR_OK && !empty($multiTitles[$i])) {
                        $mTitle = trim($multiTitles[$i]);
                        $ext = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));
                        if ($ext === 'pdf') {
                            $uploadDir = __DIR__ . '/../assets/uploads/documents/';
                            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                            $fileName = $editSlug . '_multi_' . time() . '_' . bin2hex(random_bytes(4)) . '.pdf';
                            if (move_uploaded_file($files['tmp_name'][$i], $uploadDir . $fileName)) {
                                $db->insert('custom_page_pdfs', [
                                    'page_slug' => $editSlug,
                                    'title' => $mTitle,
                                    'pdf_path' => 'assets/uploads/documents/' . $fileName
                                ]);
                            }
                        }
                    }
                }
            }
            
            redirectWithMessage('manage-pages.php', 'Page content and menu settings updated successfully!', 'success');
        }
    }
}

$allPages = $db->fetchAll("SELECT * FROM custom_pages ORDER BY menu_group ASC, title ASC");
$flash = getFlashMessage();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Dynamic Pages - <?= APP_SHORT_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/admin-style.css" rel="stylesheet">
    
    <?php if ($action === 'edit' || $action === 'add'): ?>
        <!-- Summernote WYSIWYG Editor Dependencies -->
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel="stylesheet">
        <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.js"></script>
    <?php endif; ?>
    <style>
        .hover-shadow:hover {
            box-shadow: 0 .5rem 1rem rgba(0,0,0,.08)!important;
            transition: all 0.3s ease;
        }
        .page-badge {
            font-size: 0.75rem;
            padding: 5px 10px;
            border-radius: 30px;
            font-weight: 600;
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/admin_header.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <?php include __DIR__ . '/../includes/admin_sidebar.php'; ?>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                
                <?php if (($action === 'edit' && $pageData) || $action === 'add'): ?>
                    <!-- Add / Edit Page Mode Form -->
                    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
                        <h1 class="h2">
                            <i class="<?= $action === 'add' ? 'fas fa-plus-circle' : 'fas fa-edit' ?> me-2 text-primary"></i>
                            <?= $action === 'add' ? 'Create New Dynamic Page' : 'Edit Page: ' . htmlspecialchars($pageData['title']) ?>
                        </h1>
                        <a href="manage-pages.php" class="btn btn-sm btn-outline-secondary rounded-pill px-3">
                            <i class="fas fa-arrow-left me-1"></i>Back to List
                        </a>
                    </div>
                    
                    <?php if (!empty($errors)): ?>
                        <div class="alert alert-danger alert-dismissible fade show shadow-sm">
                            <h5 class="alert-heading fw-bold mb-2"><i class="fas fa-exclamation-triangle me-2"></i>Validation Failed</h5>
                            <ul class="mb-0">
                                <?php foreach ($errors as $err): ?>
                                    <li><?= htmlspecialchars($err) ?></li>
                                <?php endforeach; ?>
                            </ul>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <div class="card border-0 shadow-sm hover-shadow">
                        <div class="card-body p-4">
                            <form action="manage-pages.php?action=<?= $action ?><?= $action === 'edit' ? '&slug=' . urlencode($pageData['slug']) : '' ?>" method="POST" enctype="multipart/form-data">
                                <?php if ($action === 'edit'): ?>
                                    <input type="hidden" name="slug" value="<?= htmlspecialchars($pageData['slug']) ?>">
                                <?php endif; ?>
                                
                                <div class="row g-3 mb-4">
                                    <div class="col-md-6">
                                        <label for="title" class="form-label fw-bold text-secondary">Page Title (पेज का नाम / शीर्षक) <span class="text-danger">*</span></label>
                                        <input type="text" name="title" id="title" class="form-control form-control-lg border-2" placeholder="e.g. Exam Guidelines" value="<?= htmlspecialchars($pageData['title'] ?? '') ?>" required>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="slug" class="form-label fw-bold text-secondary">URL Slug (यूआरएल पहचानकर्ता)</label>
                                        <div class="input-group input-group-lg">
                                            <span class="input-group-text bg-light text-muted small">page.php?slug=</span>
                                            <input type="text" name="slug" id="slug" class="form-control border-2" placeholder="exam-guidelines" value="<?= htmlspecialchars($pageData['slug'] ?? '') ?>" <?= $action === 'edit' ? 'readonly' : '' ?>>
                                        </div>
                                        <div class="form-text">यूआरएल अनुकूल बनाने के लिए (अक्षरों, संख्याओं और हाइफ़न का उपयोग करें)। खाली छोड़ने पर नाम से अपने आप बन जाएगा।</div>
                                    </div>
                                </div>

                                <!-- Dynamic Submenu Selector -->
                                <div class="card border border-primary bg-light bg-opacity-10 mb-4 shadow-xs">
                                    <div class="card-body p-3">
                                        <h5 class="card-title text-primary fw-bold mb-2">
                                            <i class="fas fa-network-wired me-2"></i>Choose Parent Sub-Menu (यह पेज किस सब-मेन्यू में जुड़ेगा?)
                                        </h5>
                                        <div class="row align-items-center">
                                            <div class="col-md-7">
                                                <select class="form-select form-select-lg border-primary border-2 fw-semibold text-dark" name="menu_group" id="menu_group" required>
                                                    <option value="none" <?= ($pageData['menu_group'] ?? '') === 'none' ? 'selected' : '' ?>>None / Independent Page (स्वतंत्र पेज - किसी मेन्यू के अंदर नहीं)</option>
                                                    <option value="examination" <?= ($pageData['menu_group'] ?? '') === 'examination' ? 'selected' : '' ?>>Examination (परीक्षा dropdown menu के अंदर)</option>
                                                    <option value="constitution" <?= ($pageData['menu_group'] ?? '') === 'constitution' ? 'selected' : '' ?>>IBVTE Constitution (संविधान dropdown menu के अंदर)</option>
                                                    <option value="circular" <?= ($pageData['menu_group'] ?? '') === 'circular' ? 'selected' : '' ?>>शासनादेश एवं परिपत्र (परिपत्र dropdown menu के अंदर)</option>
                                                    <option value="home_boxes" <?= ($pageData['menu_group'] ?? '') === 'home_boxes' ? 'selected' : '' ?>>Homepage Quick Link Boxes (होमपेज क्विक लिंक बॉक्स)</option>
                                                </select>
                                            </div>
                                            <div class="col-md-5 mt-2 mt-md-0">
                                                <div class="small text-muted">
                                                    <i class="fas fa-info-circle text-primary me-1"></i>
                                                    यहाँ समूह चुनने से यह पेज ऑटोमैटिकली मुख्य हेडर मेन्यू के संबंधित सब-मेन्यू ड्रॉपडाउन में जुड़ जाएगा।
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Sidebar Link Configuration -->
                                <div class="card border border-success bg-light bg-opacity-10 mb-4 shadow-xs">
                                    <div class="card-body p-3">
                                        <h5 class="card-title text-success fw-bold mb-2">
                                            <i class="fas fa-bars me-2"></i>Homepage Sidebar Link (होमपेज रंगीन साइडबार लिंक)
                                        </h5>
                                        <div class="form-check form-switch mb-3">
                                            <input class="form-check-input" type="checkbox" role="switch" id="show_in_sidebar" name="show_in_sidebar" value="1" <?= ($pageData['show_in_sidebar'] ?? 0) ? 'checked' : '' ?>>
                                            <label class="form-check-label fw-bold" for="show_in_sidebar">Show in sitewide colorful sidebar (इस पेज को रंगीन साइडबार में दिखाएं)</label>
                                            <div class="form-text">यदि सक्रिय किया जाता है, तो यह पेज होमपेज और अन्य पेजों के बाईं ओर दिखने वाले मुख्य रंगीन क्विक-लिंक्स साइडबार में दिखेगा।</div>
                                        </div>

                                        <div class="row g-3" id="sidebar-details-wrapper" style="<?= ($pageData['show_in_sidebar'] ?? 0) ? '' : 'display: none;' ?>">
                                            <div class="col-md-4">
                                                <label for="sidebar_color" class="form-label fw-bold">Sidebar Button Color (बटन का रंग)</label>
                                                <div class="d-flex align-items-center gap-2">
                                                    <input type="color" name="sidebar_color" id="sidebar_color" class="form-control form-control-color border-2" style="width: 50px; height: 38px;" value="<?= htmlspecialchars($pageData['sidebar_color'] ?? '#2196f3') ?>">
                                                    <input type="text" id="sidebar_color_text" class="form-control" placeholder="#2196f3" value="<?= htmlspecialchars($pageData['sidebar_color'] ?? '#2196f3') ?>" oninput="document.getElementById('sidebar_color').value = this.value">
                                                </div>
                                                <div class="form-text">साइडबार बटन की पृष्ठभूमि का रंग।</div>
                                            </div>
                                            <div class="col-md-4">
                                                <label for="sidebar_icon" class="form-label fw-bold">FontAwesome Icon Class (आइकॉन)</label>
                                                <input type="text" name="sidebar_icon" id="sidebar_icon" class="form-control" placeholder="e.g. fas fa-marker" value="<?= htmlspecialchars($pageData['sidebar_icon'] ?? 'fas fa-link') ?>">
                                                <div class="form-text">जैसे: <code>fas fa-marker</code>, <code>fas fa-book</code>, <code>fas fa-poll</code>.</div>
                                            </div>
                                            <div class="col-md-4">
                                                <label for="sidebar_order" class="form-label fw-bold">Display Order (क्रम संख्या)</label>
                                                <input type="number" name="sidebar_order" id="sidebar_order" class="form-control" placeholder="0" value="<?= intval($pageData['sidebar_order'] ?? 0) ?>">
                                                <div class="form-text">कम नंबर वाले बटन साइडबार में ऊपर दिखाई देंगे।</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="card border border-warning bg-light bg-opacity-10 mb-4 shadow-xs">
                                    <div class="card-body p-3">
                                        <h5 class="card-title text-warning fw-bold mb-2"><i class="fas fa-file-pdf me-2"></i>PDF Attachment Option (केवल पीडीएफ विकल्प)</h5>
                                        <div class="form-check form-switch mb-3">
                                            <input class="form-check-input" type="checkbox" role="switch" id="only_pdf" name="only_pdf" value="1" <?= ($pageData['only_pdf'] ?? 0) ? 'checked' : '' ?>>
                                            <label class="form-check-label fw-bold" for="only_pdf">Only PDF (अगर टिक किया तो सीधे पीडीएफ खुलेगी)</label>
                                            <div class="form-text">यदि टिक किया गया है, तो इस पेज को खोलने पर सीधे अपलोड की गई पीडीएफ़ फ़ाइल ही पूरी स्क्रीन पर दिखाई देगी।</div>
                                        </div>
                                        
                                        <div class="row align-items-center">
                                            <div class="col-md-6">
                                                <label for="pdf_file" class="form-label fw-bold">Upload PDF Document</label>
                                                <input type="file" name="pdf_file" id="pdf_file" class="form-control" accept=".pdf">
                                                <div class="form-text text-muted">Choose a .pdf document to display. Max recommended size 15MB.</div>
                                            </div>
                                            <div class="col-md-6">
                                                <?php if (!empty($pageData['pdf_path'])): ?>
                                                    <div class="p-2 border border-danger border-opacity-25 rounded bg-white mt-3 mt-md-0 d-flex align-items-center justify-content-between">
                                                        <span class="small text-muted text-truncate me-2"><i class="fas fa-file-pdf text-danger me-2"></i><?= basename($pageData['pdf_path']) ?></span>
                                                        <a href="../<?= htmlspecialchars($pageData['pdf_path']) ?>" target="_blank" class="btn btn-sm btn-outline-danger py-1 px-2"><i class="fas fa-eye me-1"></i>View PDF</a>
                                                    </div>
                                                <?php else: ?>
                                                    <span class="text-muted small d-block mt-3 mt-md-0"><i class="fas fa-info-circle me-1"></i>No PDF file currently uploaded.</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Multiple PDF Attachments Section -->
                                <div class="card border border-info bg-light bg-opacity-10 mb-4 shadow-xs">
                                    <div class="card-body p-3">
                                        <h5 class="card-title text-info fw-bold mb-2">
                                            <i class="fas fa-copy me-2"></i>Multiple PDF Attachments (मल्टीपल पीडीएफ विकल्प)
                                        </h5>
                                        <div class="form-text text-muted mb-3">यदि आप इस पेज पर एक से अधिक पीडीएफ़ लिंक दिखाना चाहते हैं, तो यहाँ जोड़ें। मल्टीपल पीडीएफ जोड़ने पर "केवल पीडीएफ (Only PDF)" वाला विकल्प अपने आप बंद हो जाएगा।</div>

                                        <!-- Already attached multiple PDFs -->
                                        <?php if (!empty($attachedPdfs)): ?>
                                            <div class="mb-3">
                                                <label class="form-label fw-bold">Current Attached PDFs:</label>
                                                <div class="row g-2" id="existing-pdfs-list">
                                                    <?php foreach ($attachedPdfs as $ap): ?>
                                                        <div class="col-md-6 id-pdf-container-<?= $ap['id'] ?>">
                                                            <div class="p-2 border border-info border-opacity-25 rounded bg-white d-flex align-items-center justify-content-between">
                                                                <span class="small text-muted text-truncate me-2">
                                                                    <i class="fas fa-file-pdf text-danger me-2"></i>
                                                                    <strong><?= htmlspecialchars($ap['title']) ?></strong> (<?= basename($ap['pdf_path']) ?>)
                                                                </span>
                                                                <div>
                                                                    <a href="../<?= htmlspecialchars($ap['pdf_path']) ?>" target="_blank" class="btn btn-sm btn-outline-info py-0 px-2 me-1"><i class="fas fa-eye"></i></a>
                                                                    <button type="button" class="btn btn-sm btn-outline-danger py-0 px-2 remove-existing-pdf" data-id="<?= $ap['id'] ?>"><i class="fas fa-trash"></i></button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>

                                        <!-- Dynamic rows for adding new PDFs -->
                                        <div id="multiple-pdfs-wrapper">
                                            <!-- Dynamic rows appended here -->
                                        </div>

                                        <button type="button" class="btn btn-info text-white btn-sm mt-2 fw-bold" id="add-more-pdf-btn">
                                            <i class="fas fa-plus me-1"></i>Add PDF Row (नया पीडीएफ रो जोड़ें)
                                        </button>
                                        
                                        <div class="alert alert-warning py-2 mt-3 mb-0 small" id="only-pdf-warning" style="display:none;">
                                            <i class="fas fa-exclamation-circle me-1"></i> मल्टीपल पीडीएफ जोड़ने के कारण <strong>"Only PDF (केवल पीडीएफ)"</strong> और सिंगल पीडीएफ़ अपलोड का विकल्प अक्षम कर दिया गया है।
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mb-4" id="editor-container">
                                    <label for="content" class="form-label fw-bold text-secondary">Page HTML Content (पेज की सामग्री - MS Word जैसा एडिटर)</label>
                                    <textarea name="content" id="content"><?= htmlspecialchars($pageData['content'] ?? '') ?></textarea>
                                    <div class="form-text mt-2 text-muted">उपरोक्त एडिटर में आप माइक्रोसॉफ्ट वर्ड की तरह ही बोल्ड, इटैलिक, फ़ॉन्ट आकार, रंग, टेबल, लिंक, चित्र जोड़कर संपूर्ण पेज तैयार कर सकते हैं।</div>
                                </div>
                                
                                <div class="d-flex justify-content-between border-top pt-4">
                                    <a href="manage-pages.php" class="btn btn-outline-secondary rounded-pill px-4">Cancel</a>
                                    <button type="submit" class="btn btn-primary rounded-pill px-5 fw-bold shadow-sm">
                                        <i class="fas fa-save me-2"></i><?= $action === 'add' ? 'Create Dynamic Page' : 'Save & Update Page' ?>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <script>
                        $(document).ready(function() {
                            // Slug Auto Generator from Title (only on Add Page)
                            <?php if ($action === 'add'): ?>
                            $('#title').on('keyup', function() {
                                var title = $(this).val();
                                var slug = title.toLowerCase()
                                    .replace(/[^a-z0-9\s-]/g, '') // remove invalid chars
                                    .replace(/\s+/g, '-')         // collapse whitespace and replace by -
                                    .replace(/-+/g, '-');         // collapse dashes
                                $('#slug').val(slug);
                            });
                            <?php endif; ?>

                            // Initialize Summernote WYSIWYG Editor
                            $('#content').summernote({
                                placeholder: 'Word-like dynamic editing area. Write text, design lists, adjust colors and fonts, insert headings...',
                                tabsize: 2,
                                height: 400,
                                toolbar: [
                                    ['style', ['style']],
                                    ['font', ['bold', 'underline', 'clear', 'italic', 'strikethrough']],
                                    ['fontname', ['fontname']],
                                    ['fontsize', ['fontsize']],
                                    ['color', ['color']],
                                    ['para', ['ul', 'ol', 'paragraph']],
                                    ['table', ['table']],
                                    ['insert', ['link', 'picture', 'video', 'hr']],
                                    ['view', ['fullscreen', 'codeview', 'help']]
                                ]
                            });
                            
                            // Toggle state of Only PDF and Upload PDF based on multiple PDFs
                            function checkPdfStatus() {
                                var existingCount = $('#existing-pdfs-list > div').length;
                                var newCount = $('.multiple-pdf-row').length;
                                var hasMultiple = (existingCount + newCount) > 0;
                                
                                if (hasMultiple) {
                                    $('#only_pdf').prop('checked', false).prop('disabled', true);
                                    $('#pdf_file').val('').prop('disabled', true);
                                    $('#only-pdf-warning').show();
                                } else {
                                    $('#only_pdf').prop('disabled', false);
                                    $('#pdf_file').prop('disabled', false);
                                    $('#only-pdf-warning').hide();
                                }
                                toggleEditor();
                            }

                            // Dynamic display toggle for editor container
                            function toggleEditor() {
                                if ($('#only_pdf').is(':checked')) {
                                    $('#editor-container').addClass('opacity-50');
                                } else {
                                    $('#editor-container').removeClass('opacity-50');
                                }
                            }
                            
                            $('#only_pdf').change(toggleEditor);
                            
                            // Add PDF Row
                            $('#add-more-pdf-btn').on('click', function() {
                                var rowHtml = `
                                    <div class="row g-2 mb-2 align-items-center multiple-pdf-row">
                                        <div class="col-md-5">
                                            <input type="text" name="multi_titles[]" class="form-control" placeholder="PDF Title (e.g. परिपत्र अप्रैल 2026)" required>
                                        </div>
                                        <div class="col-md-6">
                                            <input type="file" name="multi_files[]" class="form-control" accept=".pdf" required>
                                        </div>
                                        <div class="col-auto">
                                            <button type="button" class="btn btn-danger btn-sm remove-new-pdf-row"><i class="fas fa-minus"></i></button>
                                        </div>
                                    </div>
                                `;
                                $('#multiple-pdfs-wrapper').append(rowHtml);
                                checkPdfStatus();
                            });
                            
                            // Remove New PDF Row
                            $(document).on('click', '.remove-new-pdf-row', function() {
                                $(this).closest('.multiple-pdf-row').remove();
                                checkPdfStatus();
                            });
                            
                            // Remove Existing PDF Row (marked for deletion)
                            $(document).on('click', '.remove-existing-pdf', function() {
                                var pdfId = $(this).data('id');
                                if (confirm('क्या आप वाकई इस पीडीएफ को डिलीट करना चाहते हैं? सेव करने पर यह डिलीट हो जायेगा।')) {
                                    // Append hidden input to notify backend to delete this pdf
                                    $('form').append('<input type="hidden" name="delete_pdf_ids[]" value="' + pdfId + '">');
                                    $('.id-pdf-container-' + pdfId).remove();
                                    checkPdfStatus();
                                }
                            });
                            
                            // Sidebar Details Toggle
                            $('#show_in_sidebar').change(function() {
                                if ($(this).is(':checked')) {
                                    $('#sidebar-details-wrapper').slideDown();
                                } else {
                                    $('#sidebar-details-wrapper').slideUp();
                                }
                            });
                            
                            // Sync color picker with text box
                            $('#sidebar_color').on('input', function() {
                                $('#sidebar_color_text').val($(this).val());
                            });
                            
                            // Run initial checks
                            checkPdfStatus();
                        });
                    </script>
                    
                <?php else: ?>
                    <!-- List Mode -->
                    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
                        <h1 class="h2"><i class="fas fa-file-alt me-2 text-primary"></i>Manage Dynamic Pages</h1>
                        <a href="manage-pages.php?action=add" class="btn btn-primary rounded-pill px-4 shadow-sm fw-bold">
                            <i class="fas fa-plus-circle me-1"></i>Add New Page
                        </a>
                    </div>
                    
                    <?php if ($flash): ?>
                        <div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show shadow-sm">
                            <?= $flash['message'] ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <div class="card border-0 shadow-sm hover-shadow">
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-hover align-middle mb-0">
                                    <thead class="table-light">
                                        <tr>
                                            <th class="ps-4">Page Title (पेज का नाम)</th>
                                            <th>Target Slug</th>
                                            <th>Sub-Menu Placement</th>
                                            <th>Mode / Type</th>
                                            <th>Attached PDF Document</th>
                                            <th>Last Updated</th>
                                            <th class="text-end pe-4">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (empty($allPages)): ?>
                                            <tr>
                                                <td colspan="7" class="text-center py-4 text-muted">
                                                    <i class="fas fa-folder-open me-2"></i>No pages initialized yet.
                                                </td>
                                            </tr>
                                        <?php else: ?>
                                            <?php foreach ($allPages as $page): ?>
                                                <tr>
                                                    <td class="ps-4">
                                                        <div class="fw-bold text-dark"><?= htmlspecialchars($page['title']) ?></div>
                                                        <small class="text-muted"><i class="fas fa-link me-1"></i>page.php?slug=<?= htmlspecialchars($page['slug']) ?></small>
                                                    </td>
                                                    <td><code><?= htmlspecialchars($page['slug']) ?></code></td>
                                                    <td>
                                                        <?php
                                                        $group = $page['menu_group'] ?? 'none';
                                                        if ($group === 'examination') {
                                                            echo '<span class="badge bg-primary page-badge"><i class="fas fa-pen-nib me-1"></i>Examination</span>';
                                                        } elseif ($group === 'constitution') {
                                                            echo '<span class="badge bg-purple page-badge" style="background-color: #6f42c1 !important;"><i class="fas fa-gavel me-1"></i>Constitution</span>';
                                                        } elseif ($group === 'circular') {
                                                            echo '<span class="badge bg-warning text-dark page-badge"><i class="fas fa-bullhorn me-1"></i>शासनादेश</span>';
                                                        } elseif ($group === 'home_boxes') {
                                                            echo '<span class="badge bg-info text-dark page-badge"><i class="fas fa-th me-1"></i>Homepage Boxes</span>';
                                                        } else {
                                                            echo '<span class="badge bg-secondary page-badge"><i class="fas fa-unlink me-1"></i>None / Independent</span>';
                                                        }
                                                        ?>
                                                    </td>
                                                    <td>
                                                        <?php if ($page['only_pdf']): ?>
                                                            <span class="badge bg-danger page-badge"><i class="fas fa-file-pdf me-1"></i>Only PDF Mode</span>
                                                        <?php else: ?>
                                                            <span class="badge bg-success page-badge"><i class="fas fa-code me-1"></i>HTML Content</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if ($page['pdf_path']): ?>
                                                            <a href="../<?= htmlspecialchars($page['pdf_path']) ?>" target="_blank" class="link-danger small fw-bold">
                                                                <i class="fas fa-file-pdf me-1"></i><?= basename($page['pdf_path']) ?>
                                                            </a>
                                                        <?php else: ?>
                                                            <span class="text-muted small"><i class="fas fa-ban me-1"></i>No document</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <small class="text-muted"><?= date('d M Y, h:i A', strtotime($page['updated_at'])) ?></small>
                                                    </td>
                                                    <td class="text-end pe-4">
                                                        <div class="btn-group shadow-xs rounded-pill overflow-hidden">
                                                            <a href="../page.php?slug=<?= htmlspecialchars($page['slug']) ?>" target="_blank" class="btn btn-sm btn-outline-info" title="View Live Page">
                                                                <i class="fas fa-eye"></i>
                                                            </a>
                                                            <a href="manage-pages.php?action=edit&slug=<?= urlencode($page['slug']) ?>" class="btn btn-sm btn-primary" title="Edit Content">
                                                                <i class="fas fa-edit"></i>
                                                            </a>
                                                            <a href="manage-pages.php?action=delete&slug=<?= urlencode($page['slug']) ?>" class="btn btn-sm btn-danger" onclick="return confirm('क्या आप वाकई इस पेज को हमेशा के लिए डिलीट करना चाहते हैं?');" title="Delete Page">
                                                                <i class="fas fa-trash"></i>
                                                            </a>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
                
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
