<?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 DISTINCT profile FROM profiles ORDER BY profile";
        $result = metodGet($query);
        
        $profiles = $result->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($profiles);
        exit();
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
        exit();
    }
}

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

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

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