<?php
/**
 * Smart Page Management - Redirect Fix (Pro Version)
 */
require_once 'header.php';

$success = '';
$error = '';

// ফুটারের ডিফল্ট পেজগুলোর লিস্ট
$default_pages = [
    'about-us'          => 'About Us',
    'contact-us'        => 'Contact Us',
    'faq'               => 'FAQ',
    'privacy-policy'    => 'Privacy Policy',
    'refund-policy'     => 'Refund Policy',
    'terms-conditions'  => 'Terms & Conditions'
];

// ১. পেজ সেভ বা আপডেট লজিক
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_page'])) {
    $slug    = $_POST['slug'];
    $title   = $_POST['title'];
    $content = $_POST['content'];

    if (empty($slug) || empty($title) || empty($content)) {
        $error = "Please fill all fields.";
    } else {
        try {
            $stmt = $pdo->prepare("INSERT INTO pages (title, slug, content) VALUES (?, ?, ?) 
                                   ON DUPLICATE KEY UPDATE title=VALUES(title), content=VALUES(content)");
            if($stmt->execute([$title, $slug, $content])) {
                // সাকসেস মেসেজ সেশনে রাখা যাতে রিডাইরেক্টের পর পাওয়া যায়
                $_SESSION['msg_success'] = "Page '$title' updated successfully!";
                // রিডাইরেক্ট লজিক: সেভ হওয়ার পর আবার ওই পেজেই নিয়ে যাবে
                echo "<script>window.location.href='manage-pages.php?edit=$slug';</script>";
                exit;
            }
        } catch (PDOException $e) {
            $error = "Database Error: " . $e->getMessage();
        }
    }
}

// সেশন থেকে মেসেজ তুলে আনা
if(isset($_SESSION['msg_success'])) {
    $success = $_SESSION['msg_success'];
    unset($_SESSION['msg_success']);
}

// ২. বর্তমান পেজগুলোর ডাটা তুলে আনা
$existing_pages = [];
$stmt = $pdo->query("SELECT * FROM pages");
while($row = $stmt->fetch()) {
    $existing_pages[$row['slug']] = $row;
}
?>

<style>
    .editor-container { display: grid; grid-template-columns: 320px 1fr; gap: 20px; align-items: start; }
    .page-card { background: #fff; border-radius: 12px; border: 1px solid var(--border-color); padding: 20px; }
    
    .footer-page-list { display: flex; flex-direction: column; gap: 8px; }
    .footer-item { 
        padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; cursor: pointer; transition: 0.2s;
        display: flex; justify-content: space-between; align-items: center; background: #f9fafb; text-decoration: none;
    }
    .footer-item:hover { border-color: var(--primary-orange); background: #fff; }
    .footer-item.active { border-color: var(--primary-orange); background: var(--primary-light); border-left: 4px solid var(--primary-orange); }
    
    .status-dot { width: 8px; height: 8px; border-radius: 50%; }
    .dot-live { background: #10b981; }
    .dot-off { background: #d1d5db; }

    .page-editor { min-height: 450px; width: 100%; padding: 15px; border: 1px solid var(--border-color); border-radius: 8px; font-family: 'Courier New', monospace; font-size: 14px; resize: vertical; box-sizing: border-box; }
    
    @media (max-width: 992px) { .editor-container { grid-template-columns: 1fr; } }
</style>

<h1 class="page-title">Manage Pages</h1>

<?php if($success): ?> <div class="alert-box alert-success">✓ <?php echo $success; ?></div> <?php endif; ?>
<?php if($error): ?> <div class="alert-box alert-danger">⚠ <?php echo $error; ?></div> <?php endif; ?>

<div class="editor-container">
    
    <div class="page-card">
        <div class="footer-page-list">
            <?php foreach($default_pages as $slug => $name): ?>
                <?php $is_live = isset($existing_pages[$slug]); ?>
                <a href="?edit=<?php echo $slug; ?>" class="footer-item <?php echo (isset($_GET['edit']) && $_GET['edit'] == $slug) ? 'active' : ''; ?>">
                    <div style="font-weight: 700; font-size: 0.85rem; color: var(--text-dark);"><?php echo $name; ?></div>
                    <div class="status-dot <?php echo $is_live ? 'dot-live' : 'dot-off'; ?>"></div>
                </a>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="page-card">
        <?php 
            $edit_slug = $_GET['edit'] ?? '';
            $current_title = isset($existing_pages[$edit_slug]) ? $existing_pages[$edit_slug]['title'] : ($default_pages[$edit_slug] ?? '');
            $current_content = isset($existing_pages[$edit_slug]) ? $existing_pages[$edit_slug]['content'] : '';
        ?>

        <?php if($edit_slug): ?>
            <form action="" method="POST" id="pageForm">
                <input type="hidden" name="slug" value="<?php echo htmlspecialchars($edit_slug); ?>">
                
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h3 style="margin: 0; font-size: 1.1rem;">Editing: <span style="color: var(--primary-orange);"><?php echo $current_title; ?></span></h3>
                    <button type="submit" name="save_page" class="btn-admin" style="padding: 10px 30px;">Save & Update</button>
                </div>

                <div class="form-group" style="margin-bottom: 15px;">
                    <label class="form-label">Display Title</label>
                    <input type="text" name="title" class="form-control" value="<?php echo htmlspecialchars($current_title); ?>" required>
                </div>

                <div class="form-group">
                    <label class="form-label">HTML Content</label>
                    <textarea name="content" class="page-editor" required><?php echo htmlspecialchars($current_content); ?></textarea>
                </div>
            </form>
        <?php else: ?>
            <div style="text-align: center; padding: 100px 20px; color: var(--text-muted);">
                <h3>Select a page from the list to start editing.</h3>
            </div>
        <?php endif; ?>
    </div>

</div>

<?php echo '</div></div></body></html>'; ?>