<?php
include 'bd/myData.php';
require_once 'auth.php';
include 'cors.php';
setupCORS();

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}



requireAuth(['admin']);

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    try {
        $query = "SELECT page FROM pages ORDER BY page";
        $result = metodGet($query);
        
        echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
        exit();
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
        exit();
    }
}


if ($_POST['METHOD'] == 'POST') {
    unset($_POST['METHOD']);
    
    try {
        $query = "INSERT INTO pages(page) VALUES (:page)";
        
        $params = array(
            ':page' => $_POST['page']
        );
        
        $result = metodPost($query, null, $params, 'pages');
        echo json_encode($result);
        header("HTTP/1.1 200 OK");
        
    } catch (Exception $e) {
        header("HTTP/1.1 500 Internal Server Error");
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit();
}

if ($_POST['METHOD'] == 'PUT') {
    unset($_POST['METHOD']);
    $old_page = $_GET['page'];
    
    $query = "UPDATE pages SET page = :new_page WHERE page = :old_page";
    
    $params = array(
        ':old_page' => $old_page,
        ':new_page' => $_POST['page']
    );
    
    $result = metodPut($query, $params, 'pages');
    echo json_encode($result);
    header("HTTP/1.1 200 OK");
    exit();
}

if ($_POST['METHOD'] == 'DELETE') {
    unset($_POST['METHOD']);
    $page = $_GET['page'];
    $query = "DELETE FROM pages WHERE page = :page";
    $params = array(':page' => $page);
    $result = metodDelete($query, $params, 'pages');
    echo json_encode($result);
    header("HTTP/1.1 200 OK");
    exit();
}

header("HTTP/1.1 400 Bad Request");
?>
