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

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

// Protect route with authentication
requireAuth();

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    try {
        // Get the user's profile from the token
        $decoded = Auth::validateToken();
        $userId = $decoded->user->id;
        
        // If user is admin, return all permissions as enabled
        if ($decoded->user->role === 'admin') {
            $query = "SELECT DISTINCT page FROM profile";
            $result = metodGet($query);
            $pages = $result->fetchAll(PDO::FETCH_COLUMN);
            
            $fullPermissions = array();
            foreach ($pages as $page) {
                $fullPermissions[] = array(
                    'page' => $page,
                    'visibility' => '1',
                    'op_add' => '1',
                    'op_edit' => '1',
                    'op_delete' => '1'
                );
            }
            
            echo json_encode($fullPermissions);
            exit();
        }

        // For non-admin users, get their specific permissions
        $query = "
            SELECT pr.* 
            FROM profile pr
            JOIN users u ON u.profile = pr.profile
            WHERE u.idUser = :userId
        ";
        
        $params = array(':userId' => $userId);
        $result = metodGet($query, $params);
        
        echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit();
}

http_response_code(400);
echo json_encode(['error' => 'Invalid request method']);
?>  