<?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 roles";
    $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 roles (role, user_cre) VALUES (:role, :user_cre)";
        $queryAutoIncrement = "SELECT MAX(role) as role FROM roles";
        $params = array(
            ':role' => $_POST['role'],
            ':user_cre' => $_POST['user_cre']
        );
        $result = metodPost($query, $queryAutoIncrement, $params, 'roles');
        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']);
    $role = $_GET['role'];
    
    $query = "UPDATE roles SET role = :new_role, user_upd = :user_upd WHERE role = :role";
    $params = array(
        ':role' => $role,
        ':new_role' => $_POST['new_role'],
        ':user_upd' => $_POST['user_upd']
    );
    
    $result = metodPut($query, $params, 'roles');
    echo json_encode($result);
    header("HTTP/1.1 200 OK");
    exit();
}

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

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