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

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

requireAuth();

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    $query = "SELECT * FROM poscte";
    $result = metodGet($query);
    echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
    header("HTTP/1.1 200 OK");
    exit();
}

if ($_POST['METHOD'] == 'POST') {
    unset($_POST['METHOD']);
    
    try {
        $query = "INSERT INTO poscte (description) VALUES (:description)";
        $params = array(
            ':description' => $_POST['description']
        );
        $result = metodPost($query, null, $params, 'poscte');
        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']);
    $description = $_GET['description'];
    
    $query = "UPDATE poscte SET description = :new_description WHERE description = :description";
    $params = array(
        ':description' => $description,
        ':new_description' => $_POST['new_description']
    );
    
    $result = metodPut($query, $params, 'poscte');
    echo json_encode($result);
    header("HTTP/1.1 200 OK");
    exit();
}

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

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