<?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 tiers";
    $result = metodGet($query);
    echo json_encode($result->fetchAll());
    header("HTTP/1.1 200 OK");
    exit();
}

if ($_POST['METHOD'] == 'POST') {
    unset($_POST['METHOD']);

    try {
        $query = "INSERT INTO tiers (description, user_cre) VALUES (:description, :user_cre)";
        $queryAutoIncrement = "SELECT MAX(id) as id FROM tiers"; // Assuming tiers table has an auto-incrementing id column

        $params = array(
            ':description' => $_POST['description'],
            ':user_cre' => $_POST['user_cre']
        );

        $result = metodPost($query, $queryAutoIncrement, $params, 'tiers');
        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']);
    $id = $_GET['id']; // Assuming tiers table has an auto-incrementing id column

    $query = "UPDATE tiers SET 
                description = :description,
                user_upd = :user_upd
              WHERE id = :id";

    $params = array(
        ':id' => $id,
        ':description' => $_POST['description'],
        ':user_upd' => $_POST['user_upd']
    );

    $result = metodPut($query, $params, 'tiers');
    echo json_encode($result);
    header("HTTP/1.1 200 OK");
    exit();
}

if ($_POST['METHOD'] == 'DELETE') {
    unset($_POST['METHOD']);
    $id = $_GET['id']; // Assuming tiers table has an auto-incrementing id column
    $query = "DELETE FROM tiers WHERE id = :id";
    $params = array(':id' => $id);
    $result = metodDelete($query, $params, 'tiers');
    echo json_encode($result);
    header("HTTP/1.1 200 OK");
    exit();
}

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