<?php
/**
 * API endpoint to manage featured pages
 * Used for AJAX requests from admin or frontend
 */

header('Content-Type: application/json');

session_start();

// Check if user is admin (optional - remove this check for public toggle)
// if (empty($_SESSION['user_id']) || empty($_SESSION['is_admin'])) {
//     http_response_code(403);
//     echo json_encode(['success' => false, 'error' => 'Unauthorized']);
//     exit;
// }

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

$action = $_POST['action'] ?? '';
$response = ['success' => false];

try {
    switch ($action) {
        case 'toggle_featured':
            $pageId = (int)($_POST['page_id'] ?? 0);
            $isFeatured = isset($_POST['is_featured']) ? (int)$_POST['is_featured'] : 0;
            
            if ($pageId <= 0) {
                throw new Exception('Invalid page ID');
            }
            
            if (NavigationHelper::toggleFeatured($pageId, $isFeatured)) {
                $response['success'] = true;
                $response['message'] = 'Page updated successfully';
            } else {
                throw new Exception('Failed to update page');
            }
            break;
            
        case 'get_featured_pages':
            $pages = NavigationHelper::getFeaturedPages();
            $response['success'] = true;
            $response['pages'] = $pages;
            break;
            
        case 'get_all_pages':
            $pages = NavigationHelper::getAllPages();
            $response['success'] = true;
            $response['pages'] = $pages;
            break;
            
        default:
            throw new Exception('Unknown action: ' . $action);
    }
} catch (Exception $e) {
    http_response_code(400);
    $response['success'] = false;
    $response['error'] = $e->getMessage();
}

echo json_encode($response);
?>
