<?php
/**
 * Admin Page Management System
 * Allows admin to manage featured pages and menu order
 */

session_start();

// Check if user is admin (comment out for testing)
// if (empty($_SESSION['user_id']) || empty($_SESSION['is_admin'])) {
//     header('Location: admin_login.php');
//     exit;
// }

require_once __DIR__ . '/db_config.php';
require_once __DIR__ . '/helpers/navigation_helper.php';

$message = '';
$messageType = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        $action = $_POST['action'];
        
        // Toggle featured status
        if ($action === 'toggle_featured') {
            $pageId = (int)$_POST['page_id'] ?? 0;
            $isFeatured = isset($_POST['is_featured']) ? 1 : 0;
            
            if ($pageId > 0) {
                if (NavigationHelper::toggleFeatured($pageId, $isFeatured)) {
                    $message = 'Page featured status updated successfully!';
                    $messageType = 'success';
                } else {
                    $message = 'Error updating page. Please try again.';
                    $messageType = 'error';
                }
            }
        }
        
        // Update menu order
        else if ($action === 'update_order') {
            $orders = $_POST['menu_order'] ?? [];
            $success = true;
            
            foreach ($orders as $pageId => $order) {
                $pageId = (int)$pageId;
                $order = (int)$order;
                
                if ($pageId > 0 && !NavigationHelper::updateMenuOrder($pageId, $order)) {
                    $success = false;
                }
            }
            
            if ($success) {
                $message = 'Menu order updated successfully!';
                $messageType = 'success';
            } else {
                $message = 'Error updating menu order. Please try again.';
                $messageType = 'error';
            }
        }
        
        // Add new page
        else if ($action === 'add_page') {
            $title = $_POST['title'] ?? '';
            $slug = $_POST['slug'] ?? '';
            $url = $_POST['url'] ?? '';
            
            if (empty($title) || empty($slug) || empty($url)) {
                $message = 'Please fill in all required fields.';
                $messageType = 'error';
            } else {
                $pageData = [
                    'title' => $title,
                    'slug' => $slug,
                    'url' => $url,
                    'is_featured' => isset($_POST['is_featured']) ? 1 : 0,
                    'menu_order' => 999
                ];
                
                if (NavigationHelper::addPage($pageData)) {
                    $message = 'Page added successfully!';
                    $messageType = 'success';
                } else {
                    $message = 'Error adding page. Please try again.';
                    $messageType = 'error';
                }
            }
        }
        
        // Delete page
        else if ($action === 'delete_page') {
            $pageId = (int)$_POST['page_id'] ?? 0;
            
            if ($pageId > 0) {
                if (NavigationHelper::deletePage($pageId)) {
                    $message = 'Page deleted successfully!';
                    $messageType = 'success';
                } else {
                    $message = 'Error deleting page. Please try again.';
                    $messageType = 'error';
                }
            }
        }
    }
}

// Get all pages
$allPages = NavigationHelper::getAllPages();
$featuredCount = count(array_filter($allPages, function($p) { return $p['is_featured'] === 1; }));

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Manage Navigation Pages - Admin</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="css/responsive-system.css">
    <style>
        .admin-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .admin-header {
            background: #f5f5f5;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
        }
        
        .admin-header h1 {
            margin: 0 0 5px 0;
            color: #333;
        }
        
        .admin-header p {
            margin: 0;
            color: #666;
            font-size: 14px;
        }
        
        .alert {
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .alert.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .form-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
            border: 1px solid #e6e6e6;
        }
        
        .form-section h2 {
            margin-top: 0;
            color: #333;
            border-bottom: 2px solid #F07E2D;
            padding-bottom: 10px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: 500;
            font-size: 14px;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            font-size: 14px;
            font-family: inherit;
            box-sizing: border-box;
        }
        
        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #F07E2D;
            box-shadow: 0 0 0 3px rgba(240, 126, 45, 0.1);
        }
        
        .form-group.checkbox {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .form-group.checkbox input {
            width: auto;
            margin: 0;
        }
        
        .form-group.checkbox label {
            margin-bottom: 0;
            font-weight: normal;
        }
        
        .btn {
            display: inline-block;
            padding: 10px 20px;
            background: #F07E2D;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn:hover {
            background: #e66e1f;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(240, 126, 45, 0.2);
        }
        
        .btn.btn-danger {
            background: #dc3545;
        }
        
        .btn.btn-danger:hover {
            background: #c82333;
        }
        
        .btn.btn-secondary {
            background: #6c757d;
        }
        
        .btn.btn-secondary:hover {
            background: #5a6268;
        }
        
        .table-container {
            overflow-x: auto;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            background: white;
        }
        
        th {
            background: #f5f5f5;
            padding: 12px;
            text-align: left;
            font-weight: 600;
            color: #333;
            border-bottom: 2px solid #e6e6e6;
            font-size: 13px;
            text-transform: uppercase;
        }
        
        td {
            padding: 12px;
            border-bottom: 1px solid #f0f0f0;
            font-size: 14px;
        }
        
        tr:hover {
            background-color: #fafafa;
        }
        
        .featured-badge {
            background: #F07E2D;
            color: white;
            padding: 4px 8px;
            border-radius: 3px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .status-enabled {
            color: #28a745;
            font-weight: 600;
        }
        
        .status-disabled {
            color: #6c757d;
        }
        
        .action-buttons {
            display: flex;
            gap: 8px;
        }
        
        .action-buttons form {
            display: inline;
        }
        
        .action-buttons .btn {
            padding: 6px 12px;
            font-size: 12px;
            margin: 0;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #F07E2D, #f09c4f);
            color: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }
        
        .stat-card .number {
            font-size: 32px;
            font-weight: 700;
            margin-bottom: 5px;
        }
        
        .stat-card .label {
            font-size: 13px;
            opacity: 0.95;
        }
        
        .two-column {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        @media (max-width: 768px) {
            .two-column {
                grid-template-columns: 1fr;
            }
            
            .admin-container {
                padding: 15px;
            }
            
            .form-section {
                padding: 15px;
            }
        }
    </style>
</head>
<body style="background: #f9f9f9; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;">

<!-- <php include 'header.php'; ?> -->

<div class="admin-container">


<?php
// Default link
$dashboardLink = "admin_dashboard.php";

// Adjust based on role
if (isset($_SESSION['role'])) {
    switch ($_SESSION['role']) {
        case 'admin':
            $dashboardLink = "admin_dashboard.php";
            break;
        case 'subadmin':
            $dashboardLink = "subadmin_dashboard.php";
            break;
        case 'editor':
            $dashboardLink = "subadmin_dashboard.php";
            break;
        default:
            $dashboardLink = "admin_dashboard.php"; // fallback
    }
}
?>

<a href="<?php echo $dashboardLink; ?>" class="back-btn">← Back to Dashboard</a>

<style>
.back-btn {
    background-color: orange;
    color: white;
    padding: 8px 14px;
    text-decoration: none;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
}
.back-btn:hover {
    background-color: darkorange;
}
</style>
    <!-- <a href="admin_dashboard.php" class="back-btn">← Back to Dashboard</a>
     -->
    <div class="admin-header">
        <h1>📄 Navigation Menu Management</h1>
        <p>Manage featured pages in header navigation and menu ordering</p>
    </div>
    
    <?php if ($message): ?>
        <div class="alert <?php echo $messageType; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>
    
    <!-- Statistics -->
    <div class="stats">
        <div class="stat-card">
            <div class="number"><?php echo count($allPages); ?></div>
            <div class="label">Total Pages</div>
        </div>
        <div class="stat-card">
            <div class="number"><?php echo $featuredCount; ?>/4</div>
            <div class="label">Featured Pages</div>
        </div>
    </div>
    
    <div class="two-column">
        <!-- Add New Page Section -->
        <div class="form-section">
            <h2>➕ Add New Page</h2>
            <form method="POST">
                <input type="hidden" name="action" value="add_page">
                
                <div class="form-group">
                    <label for="title">Page Title *</label>
                    <input type="text" id="title" name="title" required placeholder="e.g., About Us">
                </div>
                
                <div class="form-group">
                    <label for="slug">URL Slug *</label>
                    <input type="text" id="slug" name="slug" required placeholder="e.g., about-us">
                </div>
                
                <div class="form-group">
                    <label for="url">Full URL or Path *</label>
                    <input type="text" id="url" name="url" required placeholder="e.g., about.php or /pages/about.html">
                </div>
                
                <div class="form-group checkbox">
                    <input type="checkbox" id="is_featured_new" name="is_featured" value="1">
                    <label for="is_featured_new">Make this page featured (shows in main menu)</label>
                </div>
                
                <button type="submit" class="btn">Add Page</button>
            </form>
        </div>
        
        <!-- Update Menu Order Section -->
        <div class="form-section">
            <h2>📋 Menu Order</h2>
            <p style="color: #666; font-size: 13px; margin-bottom: 15px;">Set the order pages appear in navigation (lower numbers appear first)</p>
            
            <form method="POST">
                <input type="hidden" name="action" value="update_order">
                
                <?php foreach ($allPages as $page): ?>
                    <div class="form-group">
                        <label for="order_<?php echo $page['id']; ?>">
                            <?php echo htmlspecialchars($page['title']); ?>
                            <?php if (isset($page['is_featured']) && $page['is_featured']): ?>
                                <span class="featured-badge">Featured</span>
                            <?php endif; ?>
                        </label>
                        <input type="number" id="order_<?php echo $page['id']; ?>" name="menu_order[<?php echo $page['id']; ?>]" value="<?php echo isset($page['menu_order']) ? $page['menu_order'] : 999; ?>" min="1" max="999">
                    </div>
                <?php endforeach; ?>
                
                <button type="submit" class="btn">Update Order</button>
            </form>
        </div>
    </div>
    
    <!-- Pages List Section -->
    <div class="form-section">
        <h2>📑 All Pages</h2>
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Slug</th>
                        <th>URL</th>
                        <th>Featured</th>
                        <th>Order</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($allPages)): ?>
                        <tr>
                            <td colspan="6" style="text-align: center; color: #999; padding: 30px;">
                                No pages found. Add a page using the form above.
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($allPages as $page): ?>
                            <tr>
                                <td>
                                    <strong><?php echo htmlspecialchars($page['title'] ?? ''); ?></strong>
                                </td>
                                <td>
                                    <code style="background: #f5f5f5; padding: 2px 6px; border-radius: 3px; font-size: 12px;">
                                        <?php echo htmlspecialchars($page['slug'] ?? ''); ?>
                                    </code>
                                </td>
                                <td>
                                    <small><?php echo htmlspecialchars($page['url'] ?? ''); ?></small>
                                </td>
                                <td>
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="action" value="toggle_featured">
                                        <input type="hidden" name="page_id" value="<?php echo $page['id']; ?>">
                                        <input type="hidden" name="is_featured" value="<?php echo (isset($page['is_featured']) && $page['is_featured']) ? '0' : '1'; ?>">
                                        
                                        <?php if (isset($page['is_featured']) && $page['is_featured']): ?>
                                            <span class="featured-badge">✓ Featured</span>
                                            <button type="submit" class="btn btn-secondary" style="padding: 3px 8px; font-size: 11px; margin-left: 8px;">Unfeature</button>
                                        <?php else: ?>
                                            <span class="status-disabled">Not featured</span>
                                            <button type="submit" class="btn" style="padding: 3px 8px; font-size: 11px; margin-left: 8px;">Make Featured</button>
                                        <?php endif; ?>
                                    </form>
                                </td>
                                <td>
                                    <span style="background: #f5f5f5; padding: 4px 8px; border-radius: 3px; font-weight: 600;">
                                        <?php echo isset($page['menu_order']) ? $page['menu_order'] : 999; ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <form method="POST" onsubmit="return confirm('Are you sure you want to delete this page?');">
                                            <input type="hidden" name="action" value="delete_page">
                                            <input type="hidden" name="page_id" value="<?php echo $page['id']; ?>">
                                            <button type="submit" class="btn btn-danger">Delete</button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Help Section -->
    <div class="form-section" style="background: #f0f8ff; border-color: #b3d9ff;">
        <h2>ℹ️ How It Works</h2>
        <ul style="margin: 15px 0; padding-left: 20px; color: #555; line-height: 1.8;">
            <li><strong>Featured Pages:</strong> Up to 4 pages display directly in the header navigation menu</li>
            <li><strong>More Menu:</strong> All other pages appear in a dropdown "MORE" menu on hover</li>
            <li><strong>Menu Order:</strong> Control which pages appear first (lower numbers appear first)</li>
            <li><strong>Toggle Featured:</strong> Click the "Make Featured" or "Unfeature" button to change status</li>
            <li><strong>Add Pages:</strong> Create new pages and optionally mark them as featured</li>
            <li><strong>Delete Pages:</strong> Remove pages from navigation (requires confirmation)</li>
        </ul>
    </div>
</div>

<?php include 'footer.php'; ?>

</body>
</html>
