<?php
// Admin dashboard - protected page
session_start();

// Check if user is logged in as admin
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    header('Location: admin_login.php');
    exit;
}


$username = $_SESSION['username'] ?? 'Admin';

// Data files and upload paths
$dataDir = __DIR__ . '/data';
if (!is_dir($dataDir)) @mkdir($dataDir, 0755, true);
$configFile = $dataDir . '/site_config.json';
$pagesFile = $dataDir . '/pages.json';
$categoriesFile = $dataDir . '/categories.json';
$uploadDir = __DIR__ . '/uploads';
if (!is_dir($uploadDir)) @mkdir($uploadDir, 0755, true);
// Ensure pages folder exists for created page files
$pagesDir = __DIR__ . '/pages';
if (!is_dir($pagesDir)) @mkdir($pagesDir, 0755, true);


// Load current config
$siteConfig = ['title' => "Esa's Fashion", 'logo' => ''];
if (file_exists($configFile)) {
    $c = @json_decode(file_get_contents($configFile), true);
    if (is_array($c)) $siteConfig = array_merge($siteConfig, $c);
}

// Load categories
$categories = [];
if (file_exists($categoriesFile)) {
    $cats = @json_decode(file_get_contents($categoriesFile), true);
    if (is_array($cats)) $categories = $cats;
}

// Load pages
$pages = [];
if (file_exists($pagesFile)) {
    $p = @json_decode(file_get_contents($pagesFile), true);
    if (is_array($p)) $pages = $p;
}

$flash = '';

// Initialize action variable to prevent undefined warnings
$action = '';

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_title') {
        $newTitle = trim($_POST['site_title'] ?? '');
        if ($newTitle !== '') {
            $siteConfig['title'] = $newTitle;
            file_put_contents($configFile, json_encode($siteConfig, JSON_PRETTY_PRINT));
            $flash = 'Site title updated.';
        } else {
            $flash = 'Please provide a tittle.';
        }
    }

    if ($action === 'upload_logo' && !empty($_FILES['site_logo']) && $_FILES['site_logo']['error'] === UPLOAD_ERR_OK) {
        $tmp = $_FILES['site_logo']['tmp_name'];
        $name = basename($_FILES['site_logo']['name']);
        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        $allowed = ['png','jpg','jpeg','gif','svg'];
        if (!in_array($ext, $allowed)) {
            $flash = 'Logo must be an image (png,jpg,gif,svg).';
        } else {
            $target = $uploadDir . '/site_logo.' . $ext;
            if (move_uploaded_file($tmp, $target)) {
                // store relative path (no leading slash, no escaped slashes)
                $siteConfig['logo'] = 'uploads/site_logo.' . $ext;
                file_put_contents($configFile, json_encode($siteConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
                $flash = 'Logo uploaded successfully.';
            } else {
                $flash = 'Failed to move uploaded file.';
            }
        }
    }

    // Category management
    if ($action === 'add_category') {
        $name = trim($_POST['category_name'] ?? '');
        $slug = trim($_POST['category_slug'] ?? '');
        $desc = trim($_POST['category_desc'] ?? '');
        if ($name === '' || $slug === '') {
            $flash = 'Category name and slug are required.';
        } else {
            $slug = preg_replace('/[^a-z0-9\-]+/i', ' -', strtolower($slug));
            $exists = false;
            foreach ($categories as $cat) { if (($cat['slug'] ?? '') === $slug) { $exists = true; break; } }
            if ($exists) {
                $flash = 'A category with that slug already exists.';
            } else {
                $id = 1;
                foreach ($categories as $cat) { if ($cat['id'] >= $id) $id = $cat['id'] + 1; }
                $categories[] = ['id' => $id, 'name' => $name, 'slug' => $slug, 'description' => $desc];
                file_put_contents($categoriesFile, json_encode($categories, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
                $flash = 'Category added successfully.';
            }
        }
    }

    if ($action === 'edit_category') {
        $id = (int)($_POST['category_id'] ?? 0);
        $name = trim($_POST['category_name'] ?? '');
        $slug = trim($_POST['category_slug'] ?? '');
        $desc = trim($_POST['category_desc'] ?? '');
        if ($name === '' || $slug === '' || $id === 0) {
            $flash = 'All fields are required.';
        } else {
            $slug = preg_replace('/[^a-z0-9\-]+/i', '-', strtolower($slug));
            $found = false;
            foreach ($categories as $k => $cat) {
                if ($cat['id'] === $id) {
                    $categories[$k] = ['id' => $id, 'name' => $name, 'slug' => $slug, 'description' => $desc];
                    $found = true;
                    break;
                }
            }
            if ($found) {
                file_put_contents($categoriesFile, json_encode($categories, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
                $flash = 'Category updated successfully.';
            } else {
                $flash = 'Category not found.';
            }
        }
    }

    if ($action === 'delete_category') {
        $id = (int)($_POST['category_id'] ?? 0);
        if ($id !== 0) {
            $categories = array_values(array_filter($categories, function($cat) use ($id){ return $cat['id'] !== $id; }));
            file_put_contents($categoriesFile, json_encode($categories, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
            $flash = 'Category deleted successfully.';
        }
    }

    if ($action === 'add_page') {
        $title = trim($_POST['page_title'] ?? '');
        $slug = trim($_POST['page_slug'] ?? '');
        $category = trim($_POST['page_category'] ?? '');
        $html_content = $_POST['page_html'] ?? '';
        if ($title === '' || $slug === '') {
            $flash = 'Page title and slug are required.';
        } else {
            // normalize slug
            $slug = preg_replace('/[^a-z0-9\-]+/i', '-', strtolower($slug));
            // prevent duplicates
            $exists = false;
            foreach ($pages as $pg) { if (isset($pg['slug']) && $pg['slug'] === $slug) { $exists = true; break; } }
            if ($exists) {
                $flash = 'A page with that slug already exists.';
            } else {
                $pageData = ['title' => $title, 'slug' => $slug, 'created' => date('c'), 'html' => $html_content];
                if (!empty($category)) {
                    $pageData['category'] = $category;
                }
                $pages[] = $pageData;
                file_put_contents($pagesFile, json_encode($pages, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

                // Create a simple page file under /pages/<slug>.php that uses the dynamic loader
                $pageFile = $pagesDir . '/' . $slug . '.php';
                $pageContent = "<?php\n// Load page dynamically from page-loader\nrequire_once __DIR__ . '/../page-loader.php';\n";
                @file_put_contents($pageFile, $pageContent);

                $flash = 'Page added successfully.';
            }
        }
    }

    if ($action === 'save_page_content') {
        $slug = trim($_POST['slug'] ?? '');
        $html_content = $_POST['page_html'] ?? '';
        if ($slug !== '') {
            $pageKey = null;
            foreach ($pages as $k => $pg) {
                if (($pg['slug'] ?? '') === $slug) { $pageKey = $k; break; }
            }
            if ($pageKey !== null) {
                $pages[$pageKey]['html'] = $html_content;
                file_put_contents($pagesFile, json_encode($pages, JSON_PRETTY_PRINT));
                
                // Update the page file to use dynamic loader (no need to regenerate HTML)
                $pageFile = $pagesDir . '/' . $slug . '.php';
                $pageContent = "<?php\n// Load page dynamically from page-loader\nrequire_once __DIR__ . '/../page-loader.php';\n";
                @file_put_contents($pageFile, $pageContent);
                
                $flash = 'Page content updated successfully.';
            } else
            
            {
                $flash = 'Page not found.';
            }
        }
    }


    if ($action === 'edit_page') {
        $oldSlug = trim($_POST['old_slug'] ?? '');
        $newTitle = trim($_POST['page_title'] ?? '');
        $newSlug = trim($_POST['page_slug'] ?? '');
        if ($oldSlug !== '' && $newTitle !== '' && $newSlug !== '') {
            $newSlug = preg_replace('/[^a-z0-9\-]+/i', '-', strtolower($newSlug));
            $pageKey = null;
            foreach ($pages as $k => $pg) {
                if (($pg['slug'] ?? '') === $oldSlug) { $pageKey = $k; break; }
            }
            if ($pageKey !== null) {
                // If slug changed, rename the file
                if ($newSlug !== $oldSlug) {
                    $oldFile = $pagesDir . '/' . $oldSlug . '.php';
                    $newFile = $pagesDir . '/' . $newSlug . '.php';
                    if (file_exists($oldFile)) @rename($oldFile, $newFile);
                }
                $pages[$pageKey]['title'] = $newTitle;
                $pages[$pageKey]['slug'] = $newSlug;
                file_put_contents($pagesFile, json_encode($pages, JSON_PRETTY_PRINT));
                $flash = 'Page updated.';
            } else {
                $flash = 'Page not found.';
            }
        } else {
            $flash = 'Please provide all fields.';
        }
    }

    if ($action === 'delete_page') {
        $slug = trim($_POST['slug'] ?? '');
        if ($slug !== '') {
            $pages = array_values(array_filter($pages, function($pg) use ($slug){ return ($pg['slug'] ?? '') !== $slug; }));
            file_put_contents($pagesFile, json_encode($pages, JSON_PRETTY_PRINT));
            // Remove generated page file if it exists
            $gen = $pagesDir . '/' . $slug . '.php';
            if (file_exists($gen)) @unlink($gen);
            $flash = 'Page removed.';
        }
    }
    // reload config/pages after changes
    if (file_exists($configFile)) {
        $c = @json_decode(file_get_contents($configFile), true);
        if (is_array($c)) $siteConfig = array_merge($siteConfig, $c);
    }
    if (file_exists($categoriesFile)) {
        $cats = @json_decode(file_get_contents($categoriesFile), true);
        if (is_array($cats)) $categories = $cats; else $categories = [];
    }
    if (file_exists($pagesFile)) {
        $p = @json_decode(file_get_contents($pagesFile), true);
        if (is_array($p)) $pages = $p; else $pages = [];
    }
}
/* slider */


if ($action === 'update_slider') {
    $sliderFile = $dataDir . '/slider.json';
    $slider = file_exists($sliderFile) ? json_decode(file_get_contents($sliderFile), true) : [];

    // Update hero text
    $slider['hero'] = [
        'title' => $_POST['hero_title'] ?? '',
        'subtitle' => $_POST['hero_subtitle'] ?? '',
        'button_text' => $_POST['hero_button_text'] ?? '',
        'button_link' => $_POST['hero_button_link'] ?? ''
    ];

    // Handle image upload
    if (!empty($_FILES['slider_image']['name']) && $_FILES['slider_image']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['slider_image']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg','jpeg','png','gif'];
        if (in_array($ext, $allowed)) {
            $target = $uploadDir . '/' . uniqid('slide_') . '.' . $ext;
            if (move_uploaded_file($_FILES['slider_image']['tmp_name'], $target)) {
                $slider['slides'][] = ['image' => 'uploads/' . basename($target), 'alt' => 'Slide'];
            }
        }
    }

    file_put_contents($sliderFile, json_encode($slider, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    $flash = 'Slider updated successfully.';
}

if ($action === 'delete_slide') {
    $sliderFile = $dataDir . '/slider.json';
    $slider = file_exists($sliderFile) ? json_decode(file_get_contents($sliderFile), true) : [];

    $index = (int)($_POST['slide_index'] ?? -1);
    if (isset($slider['slides'][$index])) {
        // Optionally delete the actual image file too:
        $imgPath = __DIR__ . '/' . $slider['slides'][$index]['image'];
        if (file_exists($imgPath)) {
            @unlink($imgPath);
        }

        // Remove from array
        array_splice($slider['slides'], $index, 1);

        file_put_contents($sliderFile, json_encode($slider, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        $flash = 'Slide deleted successfully.';
    } else {
        $flash = 'Slide not found.';
    }
}




?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    <link rel="stylesheet" href="styles.css">
        <style>
        /* Admin page adjustments - ensure footer is full-width and does not overlap sidebar */
        body.with-admin-sidebar .site-footer { position: relative; z-index: 2; }
        /* Style footer links to look like text but remain clickable */
        .site-footer a { color: var(--text); text-decoration: none; font-weight:600; }
        .site-footer a:hover { text-decoration: underline; }
        /* Sidebar link styles to match site theme */
        #adminSidebar { background: #fff; border-right: 1px solid #f0f0f0; }
        #adminSidebar a { color: #F07E2Dff; text-decoration: none; display:block; padding:8px 10px; border-radius:4px; }
        #adminSidebar a:hover { background: rgba(102,126,234,0.06); color:#333; }
        #adminSidebar .side-link { font-weight:600; }
        #adminSidebar .side-sub a { font-weight:400; color:#666; padding-left:6px; }


        /* Collapsed state for sidebar (used on small screens) */
        #adminSidebar.collapsed { transform: translateX(-100%); transition: transform 220ms ease; }
        #adminSidebar { transition: transform 220ms ease; }

        /* Main content offset on wide screens to avoid overlap. Also support a desktop-collapsed state that reduces the sidebar to a slim rail. */
        @media (min-width: 900px) {
            body.with-admin-sidebar #adminSidebar { position:fixed; left:0; top:0; bottom:0; width:260px; }
            body.with-admin-sidebar #adminMain { margin-left: 260px; padding-left: 24px; transition: margin-left 200ms ease; }
            body.with-admin-sidebar .site-footer { margin-left: 260px; transition: margin-left 200ms ease; }

            /* Desktop collapsed (stored in localStorage) */
            body.with-admin-sidebar.sidebar-collapsed #adminSidebar { width:64px; }
            body.with-admin-sidebar.sidebar-collapsed #adminMain { margin-left:64px; }
            body.with-admin-sidebar.sidebar-collapsed .site-footer { margin-left:64px; }
            /* optionally hide labels inside the slim sidebar - keep icons visible if you add them later */
            body.with-admin-sidebar.sidebar-collapsed #adminSidebar nav ul li a { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
        }

        /* On smaller screens the sidebar overlays content and is hidden by default */
        @media (max-width: 899px) {
            #adminSidebar { position:fixed; left:0; top:0; bottom:0; width:260px; z-index:1100; }
            #adminSidebar.collapsed { transform: translateX(-100%); }
            #adminMain { margin-left:0; padding:12px; }
            .admin-toggle-btn { display:inline-block; }
        }

        /* Show toggle on all screen sizes so admins can collapse the sidebar on desktop too */
        .admin-toggle-btn { display:inline-block ;  margin-left:8px; }
        </style>
</head>
<body class="with-admin-sidebar">
<?php include __DIR__ . '/header.php'; ?>

<!-- Sidebar outside flex container so footer can be full-width -->
<aside id="adminSidebar" style="width:260px; background:#fff; padding:12px; box-shadow:0 2px 8px rgba(0,0,0,0.04); position:fixed; top:0; left:0; bottom:0; overflow:auto; z-index:1000;">
        <div style="display:flex; align-items:center; gap:10px; padding:8px;">
            <div style="width:44px;height:44px; border-radius:6px; overflow:hidden; background:#f4f4f4; display:flex;align-items:center;justify-content:center;">
                <?php if (!empty($siteConfig['logo'])): 
                    $logoPath = $siteConfig['logo'];
                ?>
                    <img src="<?php echo htmlspecialchars($logoPath); ?>?v=<?php echo time(); ?>" alt="logo" style="max-width:100%; max-height:100%; display:block;">
                <?php else: ?>
                    <span style="font-weight:700;color:#666;">E</span>
                <?php endif; ?>
            </div>
            <div>
                <div style="font-weight:700; font-size:15px;"><?php echo htmlspecialchars($siteConfig['title'] ?? 'Esa\'s Fashion'); ?></div>
                <div style="font-size:12px; color:#666;">Signed in as <?php echo htmlspecialchars($username); ?></div>
            </div>
        </div>

        <nav style="margin-top:12px;">
            <ul style="list-style:none; padding:0; margin:0;">
                <li style="margin-bottom:6px;"><a href="#" class="side-link" onclick="openModal('siteTitleModal'); return false;" data-target="title">Site Settings</a></li>
                <li style="margin-bottom:6px;"><a href="#" class="side-link" onclick="openModal('logoModal'); return false;" data-target="logo">Logo</a></li>
                <li style="margin-bottom:6px;"><a href="#" class="side-link" onclick="openModal('sliderModal'); return false;" data-target="slider">Slider</a></li>
                <li style="margin-bottom:6px;"><a href="#" class="side-link" onclick="openModal('categoriesModal'); return false;" data-target="categories">Categories</a></li>
                <li style="margin-bottom:6px;"><a href="#" class="side-link" data-target="pages">Pages ▾</a>
                    <ul class="side-sub" data-parent="pages" style="display:none; list-style:none; padding-left:12px; margin-top:6px;">
                        <li><a href="#" onclick="openModal('managePageModal'); return false;">Manage Pages</a></li>
                        <li><a href="#" onclick="openModal('addPageModal'); return false;">Add Page</a></li>
                    </ul>
                </li>
                <li style="margin-bottom:6px;"><a href="admin_products.php" class="side-link" data-target="products">Products</a></li>
                <li style="margin-bottom:6px;"><a href="admin_manage_users.php" class="side-link" data-target="users">Users</a></li>
                <li style="margin-bottom:6px;"><a href="admin_orders.php" class="side-link" data-target="orders">Orders</a></li>
            </ul>
        </nav>
        <div style="margin-top:12px; font-size:13px;"><a href="index.php" style="text-decoration:none;">View store</a> · <a href="logout_admin.php">Logout</a></div>
</aside>

<!-- Main content section -->


<main class="container" style="margin-top: 24px; margin-bottom: 24px; display:block;">
    <section id="adminMain" style="margin-left:260px; padding-left:24px;">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px;">
            <div>
                <h1 style="font-size:22px; margin:0 0 4px 0;">Admin Dashboard</h1>
                <div style="color:#666; font-size:13px;">Manage site content, pages, products and settings</div>
            </div>
            <div>
                <button class="admin-toggle-btn btn" onclick="toggleSidebar()" title="Toggle sidebar" style="background:#fff;border:1px solid #e6e6e6;padding:6px 10px;border-radius:6px;margin-right:8px;">☰</button>
                <a href="logout_admin.php" class="btn" style="text-decoration:none; background:#a5a3a3; color:#fff; padding:8px 12px; border-radius:6px;">Logout</a>
            </div>
        </div>

        <?php if (!empty($flash)): ?>
            <div style="background:#eef8ee; color:#085; padding:10px 12px; border-radius:6px; margin-bottom:12px;"><?php echo htmlspecialchars($flash); ?></div>
        <?php endif; ?>


        <!-- Main panels -->
        <div id="main-general" style="background:#fff; padding:18px; border-radius:8px; box-shadow:0 2px 8px rgba(0,0,0,0.04); margin-bottom:16px;">
            <h2 style="margin-top:0;">Site Title</h2>
            <form method="post" style="display:flex; gap:8px; align-items:center; flex-wrap:wrap;">
                <input type="hidden" name="action" value="update_title">
                <input type="text" name="site_title" value="<?php echo htmlspecialchars($siteConfig['title']); ?>" style="padding:10px; border:1px solid #e6e6e6; border-radius:6px; flex:1; min-width:200px;">
                <button class="btn" type="submit">Save Title</button>
            </form>
        </div>
        <!---slider--->
        <div id="main-slider" style="background:#fff; padding:18px; border-radius:8px; box-shadow:0 2px 8px rgba(0,0,0,0.04); margin-bottom:16px;">
    <h2>Homepage Slider</h2>
    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="action" value="update_slider">
        
        <label>Hero Title:</label>
        <input type="text" name="hero_title" value="<?php echo htmlspecialchars($slider['hero']['title'] ?? ''); ?>" style="width:100%; padding:8px;"><br>
        
        <label>Hero Subtitle:</label>
        <input type="text" name="hero_subtitle" value="<?php echo htmlspecialchars($slider['hero']['subtitle'] ?? ''); ?>" style="width:100%; padding:8px;"><br>
        
        <label>Button Text:</label>
        <input type="text" name="hero_button_text" value="<?php echo htmlspecialchars($slider['hero']['button_text'] ?? ''); ?>" style="width:100%; padding:8px;"><br>
        
        <label>Button Link:</label>
        <input type="text" name="hero_button_link" value="<?php echo htmlspecialchars($slider['hero']['button_link'] ?? ''); ?>" style="width:100%; padding:8px;"><br>
        
        <label>Upload New Slide Image:</label>
        <input type="file" name="slider_image" accept="image/*"><br>
        
        <button type="submit" class="btn">Save Slider</button>
    </form>
</div>
<!---slider above --->

<!---delete slider--->
<div id="main-slider" style="background:#fff; padding:18px; border-radius:8px; margin-bottom:16px;">
    <h2>Homepage Slider</h2>

    <h3>Existing Slides</h3>
    <?php if (!empty($slider['slides'])): ?>
        <ul style="list-style:none; padding:0;">
            <?php foreach ($slider['slides'] as $i => $s): ?>
                <li style="margin-bottom:10px; display:flex; align-items:center; gap:10px;">
                    <img src="<?php echo htmlspecialchars($s['image']); ?>" alt="" style="width:120px; height:auto;">
                    <form method="post" style="display:inline;">
                        <input type="hidden" name="action" value="delete_slide">
                        <input type="hidden" name="slide_index" value="<?php echo $i; ?>">
                        <button type="submit" style="background:#f2dede; color:#a00; padding:6px 12px; border-radius:6px; border:1px solid #a00;">Delete</button>
                    </form>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php else: ?>
        <p>No slides yet.</p>
    <?php endif; ?>
</div>


<!---slider above --->
        <div id="main-appearance" style="background:#fff; padding:18px; border-radius:8px; box-shadow:0 2px 8px rgba(0,0,0,0.04); margin-bottom:16px;">
            <h2 style="margin-top:0;">Logo</h2>
            <div style="display:flex; gap:16px; align-items:center;">
                <div style="width:120px; height:80px; border:1px solid #eee; display:flex; align-items:center; justify-content:center;">
                    <?php if (!empty($siteConfig['logo'])): 
                        $logoPath = $siteConfig['logo'];
                    ?>
                        <img src="<?php echo htmlspecialchars($logoPath); ?>?v=<?php echo filemtime(__DIR__ . '/' . $logoPath); ?>" alt="logo" style="max-width:100%; max-height:100%;">
                    <?php else: ?>
                        <span style="color:#999;">No logo</span>
                    <?php endif; ?>
                </div>
                <form method="post" enctype="multipart/form-data" style="display:flex; gap:8px; align-items:center;">
                    <input type="hidden" name="action" value="upload_logo">
                    <input type="file" name="site_logo" accept="image/*">
                    <button class="btn" type="submit">Upload Logo</button>
                </form>
            </div>
        </div>

        <div id="main-categories" style="background:#fff; padding:18px; border-radius:8px; box-shadow:0 2px 8px rgba(0,0,0,0.04); margin-bottom:16px;">
            <h2 style="margin-top:0;">Categories</h2>
            <p style="color:#666; margin-top:6px;">Manage product categories for your store.</p>

            <h3 style="margin-bottom:6px;">Existing Categories</h3>
            <?php if (empty($categories)): ?>
                <div class="muted">No categories yet.</div>
            <?php else: ?>
                <ul style="padding-left:16px; list-style:none;">
                    <?php foreach ($categories as $cat): ?>
                        <li style="margin-bottom:8px; display:flex; align-items:center; gap:10px;">
                            <div style="flex:1;"><strong><?php echo htmlspecialchars($cat['name']); ?></strong> — <small style="color:#666;"><?php echo htmlspecialchars($cat['slug']); ?></small><br><span style="font-size:12px; color:#999;"><?php echo htmlspecialchars($cat['description']); ?></span></div>
                            <button type="button" onclick="editCategoryForm('<?php echo htmlspecialchars($cat['id']); ?>', '<?php echo htmlspecialchars($cat['name']); ?>', '<?php echo htmlspecialchars($cat['slug']); ?>', '<?php echo htmlspecialchars($cat['description']); ?>')" style="background:#667eea; color:#fff; padding:6px 12px; border-radius:6px; border:none; cursor:pointer; font-size:13px; font-weight:600;">Edit</button>
                            <form method="post" style="display:inline; margin:0; padding:0;">
                                <input type="hidden" name="action" value="delete_category">
                                <input type="hidden" name="category_id" value="<?php echo htmlspecialchars($cat['id']); ?>">
                                <button type="submit" style="background:#f2dede; color:#a00; padding:6px 12px; border-radius:6px; border:1px solid #a00; cursor:pointer; font-size:13px; font-weight:600;">Delete</button>
                            </form>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>

            <h3 style="margin-top:12px;">Add Category</h3>
            <form method="post" style="display:flex; gap:8px; flex-wrap:wrap; align-items:flex-start; flex-direction:column;">
                <input type="hidden" name="action" value="add_category">
                <div style="display:flex; gap:8px; width:100%; flex-wrap:wrap;">
                    <input type="text" name="category_name" placeholder="Category name" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px; flex:1; min-width:220px;">
                    <input type="text" name="category_slug" placeholder="category-slug" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px; min-width:160px;">
                </div>
                <input type="text" name="category_desc" placeholder="Category description (optional)" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px; width:100%;">
                <button class="btn" type="submit">Add Category</button>
            </form>

            <h3 style="margin-top:16px; display:none;" id="editCategoryTitle">Edit Category</h3>
            <form method="post" id="editCategoryForm" style="display:none; gap:8px; flex-wrap:wrap; align-items:flex-start; flex-direction:column;">
                <input type="hidden" name="action" value="edit_category">
                <input type="hidden" name="category_id" id="editCategoryId">
                <div style="display:flex; gap:8px; width:100%; flex-wrap:wrap;">
                    <input type="text" name="category_name" id="editCategoryName" placeholder="Category name" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px; flex:1; min-width:220px;">
                    <input type="text" name="category_slug" id="editCategorySlug" placeholder="category-slug" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px; min-width:160px;">
                </div>
                <input type="text" name="category_desc" id="editCategoryDesc" placeholder="Category description (optional)" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px; width:100%;">
                <div style="display:flex; gap:8px;">
                    <button class="btn" type="submit" style="background:#667eea;">Save Changes</button>
                    <button type="button" onclick="cancelEditCategory()" style="background:#999; color:#fff; padding:8px 16px; border-radius:6px; border:none; cursor:pointer; font-weight:600;">Cancel</button>
                </div>
            </form>
        </div>

        <div id="main-pages" style="background:#fff; padding:18px; border-radius:8px; box-shadow:0 2px 8px rgba(0,0,0,0.04);">
            <h2 style="margin-top:0;">Pages</h2>
            <p style="color:#666; margin-top:6px;">Add simple static pages to the site. These pages will be listed here and saved to a JSON file for now.</p>

            <h3 style="margin-bottom:6px;">Existing Pages</h3>
            <?php if (empty($pages)): ?>
                <div class="muted">No pages yet.</div>
            <?php else: ?>
                <ul style="padding-left:16px; list-style:none;">
                    <?php foreach ($pages as $pg): ?>
                        <li style="margin-bottom:8px; display:flex; align-items:center; gap:10px;">
                            <div style="flex:1;"><strong><?php echo htmlspecialchars($pg['title']); ?></strong> — <small style="color:#666;"><?php echo htmlspecialchars($pg['slug']); ?></small></div>
                            <button type="button" onclick="editPageHtmlForm('<?php echo htmlspecialchars($pg['slug']); ?>', '<?php echo htmlspecialchars($pg['title']); ?>', `<?php echo htmlspecialchars($pg['html'] ?? ''); ?>`)" style="background:#4a90e2; color:#fff; padding:6px 12px; border-radius:6px; border:none; cursor:pointer; font-size:13px; font-weight:600;">Edit HTML</button>
                            <button type="button" onclick="editPageForm('<?php echo htmlspecialchars($pg['slug']); ?>', '<?php echo htmlspecialchars($pg['title']); ?>')" style="background:#667eea; color:#fff; padding:6px 12px; border-radius:6px; border:none; cursor:pointer; font-size:13px; font-weight:600;">Edit</button>
                            <form method="post" style="display:inline; margin:0; padding:0;">
                                <input type="hidden" name="action" value="delete_page">
                                <input type="hidden" name="slug" value="<?php echo htmlspecialchars($pg['slug']); ?>">
                                <button type="submit" style="background:#f2dede; color:#a00; padding:6px 12px; border-radius:6px; border:1px solid #a00; cursor:pointer; font-size:13px; font-weight:600;">Delete</button>
                            </form>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>

            <h3 style="margin-top:12px;">Add Page</h3>
            <form method="post" style="display:flex; gap:8px; flex-wrap:wrap; align-items:flex-start; flex-direction:column;">
                <input type="hidden" name="action" value="add_page">
                <div style="display:flex; gap:8px; width:100%; flex-wrap:wrap;">
                    <input type="text" name="page_title" placeholder="Page title" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px; flex:1; min-width:220px;">
                    <input type="text" name="page_slug" placeholder="page-slug" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px; min-width:160px;">
                </div>
                <select name="page_category" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px; width:100%; font-size:14px;">
                    <option value="">Select Category (optional)</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo htmlspecialchars($cat['slug']); ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                    <?php endforeach; ?>
                </select>
                <label style="display:block; font-weight:600; margin-bottom:6px;">Page HTML Content</label>
                <textarea name="page_html" placeholder="Enter HTML content for the page..." style="padding:12px; border:1px solid #e6e6e6; border-radius:6px; width:100%; height:200px; font-family:monospace; font-size:13px;"></textarea>
                <button class="btn" type="submit">Add Page</button>
            </form>

            <h3 style="margin-top:16px; display:none;" id="editPageTitle">Edit Page</h3>
            <form method="post" id="editPageForm" style="display:none; gap:8px; flex-wrap:wrap; align-items:center; flex-direction:column;">
                <input type="hidden" name="action" value="edit_page">
                <input type="hidden" name="old_slug" id="oldSlug">
                <div style="display:flex; gap:8px; width:100%;">
                    <input type="text" name="page_title" id="editPageTitleInput" placeholder="Page title" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px; flex:1; min-width:220px;">
                    <input type="text" name="page_slug" id="editPageSlugInput" placeholder="page-slug" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px; min-width:160px;">
                </div>
                <div style="display:flex; gap:8px;">
                    <button class="btn" type="submit" style="background:#667eea;">Save Changes</button>
                    <button type="button" onclick="cancelEditPage()" style="background:#999; color:#fff; padding:8px 16px; border-radius:6px; border:none; cursor:pointer; font-weight:600;">Cancel</button>
                </div>
            </form>

            <h3 style="margin-top:16px; display:none;" id="editHtmlPageTitle">Edit Page HTML</h3>
            <form method="post" id="editHtmlPageForm" style="display:none; gap:8px; flex-wrap:wrap; align-items:flex-start; flex-direction:column;">
                <input type="hidden" name="action" value="save_page_content">
                <input type="hidden" name="slug" id="htmlPageSlug">
                <label style="display:block; font-weight:600; margin-bottom:6px;">HTML Content for <span id="htmlPageTitleDisplay"></span></label>
                <textarea name="page_html" id="editHtmlPageContent" placeholder="Enter HTML content for the page..." style="padding:12px; border:1px solid #e6e6e6; border-radius:6px; width:100%; height:300px; font-family:monospace; font-size:13px;"></textarea>
                <div style="display:flex; gap:8px;">
                    <button class="btn" type="submit" style="background:#4a90e2;">Save HTML</button>
                    <button type="button" onclick="cancelEditHtmlPage()" style="background:#999; color:#fff; padding:8px 16px; border-radius:6px; border:none; cursor:pointer; font-weight:600;">Cancel</button>
                </div>
            </form>
        </div>
    </section>

<script>
function editPageHtmlForm(slug, title, htmlContent) {
    document.getElementById('editHtmlPageTitle').style.display = 'block';
    document.getElementById('editHtmlPageForm').style.display = 'flex';
    document.getElementById('htmlPageSlug').value = slug;
    document.getElementById('htmlPageTitleDisplay').innerText = title;
    document.getElementById('editHtmlPageContent').value = htmlContent;
    document.getElementById('editHtmlPageForm').scrollIntoView({ behavior: 'smooth' });
}

function cancelEditHtmlPage() {
    document.getElementById('editHtmlPageTitle').style.display = 'none';
    document.getElementById('editHtmlPageForm').style.display = 'none';
    document.getElementById('editHtmlPageForm').reset();
}

function editPageForm(slug, title) {
    document.getElementById('editPageTitle').style.display = 'block';
    document.getElementById('editPageForm').style.display = 'flex';
    document.getElementById('oldSlug').value = slug;
    document.getElementById('editPageTitleInput').value = title;
    document.getElementById('editPageSlugInput').value = slug;
    document.getElementById('editPageForm').scrollIntoView({ behavior: 'smooth' });
}

function cancelEditPage() {
    document.getElementById('editPageTitle').style.display = 'none';
    document.getElementById('editPageForm').style.display = 'none';
    document.getElementById('editPageForm').reset();
}

function editCategoryForm(id, name, slug, desc) {
    document.getElementById('editCategoryTitle').style.display = 'block';
    document.getElementById('editCategoryForm').style.display = 'flex';
    document.getElementById('editCategoryId').value = id;
    document.getElementById('editCategoryName').value = name;
    document.getElementById('editCategorySlug').value = slug;
    document.getElementById('editCategoryDesc').value = desc;
    document.getElementById('editCategoryForm').scrollIntoView({ behavior: 'smooth' });
}

function cancelEditCategory() {
    document.getElementById('editCategoryTitle').style.display = 'none';
    document.getElementById('editCategoryForm').style.display = 'none';
    document.getElementById('editCategoryForm').reset();
}

function applySidebarState(collapsed) {
    var body = document.body;
    var sidebar = document.getElementById('adminSidebar');
    if (collapsed) {
        body.classList.add('sidebar-collapsed');
        if (sidebar) sidebar.classList.add('collapsed');
    } else {
        body.classList.remove('sidebar-collapsed');
        if (sidebar) sidebar.classList.remove('collapsed');
    }
}

function toggleSidebar() {
    var currently = document.body.classList.contains('sidebar-collapsed');
    applySidebarState(!currently);
    try { localStorage.setItem('adminSidebarCollapsed', (!currently) ? '1' : '0'); } catch(e) {}
}

document.addEventListener('DOMContentLoaded', function(){
    // Apply stored sidebar collapsed state (desktop persistent)
    try {
        var saved = localStorage.getItem('adminSidebarCollapsed');
        if (saved === '1') applySidebarState(true);
    } catch(e) {}

    // Sidebar dropdown toggles
    document.querySelectorAll('.side-link').forEach(function(el){
        el.addEventListener('click', function(e){
            e.preventDefault();
            var t = el.getAttribute('data-target');
            var sub = document.querySelector('.side-sub[data-parent="' + t + '"]');
            if (!sub) return;
            sub.style.display = (sub.style.display === 'block') ? 'none' : 'block';
        });
    });

    // Close sidebar on outside click for small screens
    document.addEventListener('click', function(e){
        var sidebar = document.getElementById('adminSidebar');
        if (!sidebar) return;
        if (window.innerWidth < 900) {
            var isClickInside = sidebar.contains(e.target) || e.target.classList.contains('admin-toggle-btn');
            if (!isClickInside && !sidebar.classList.contains('collapsed')) {
                sidebar.classList.add('collapsed');
            }
        }
    });
});
</script>
</body>
</html>
