<?php
// permissions.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']);

// Get user permissions
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    try {
        if (isset($_GET['profile'])) {
            $query = "SELECT * FROM profile WHERE profile = :profile";
            $params = array(':profile' => $_GET['profile']);
            $result = metodGet($query, $params);
            
            $permissions = $result->fetchAll(PDO::FETCH_ASSOC);
            if (empty($permissions)) {
                header("HTTP/1.1 404 Not Found");
                echo json_encode(['error' => 'No permissions found for this profile']);
                exit();
            }
            
            echo json_encode($permissions);
        } else {
            // Get all permissions
            $query = "SELECT * FROM profile";
            $result = metodGet($query);
            echo json_encode($result->fetchAll(PDO_FETCH_ASSOC));
        }
        header("HTTP/1.1 200 OK");
        exit();
    } catch (Exception $e) {
        header("HTTP/1.1 500 Internal Server Error");
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
        exit();
    }
}

// Add new permission
if ($_POST['METHOD'] == 'POST') {
    unset($_POST['METHOD']);
    
    $query = "INSERT INTO profile (
                profile, page, visibility, op_add, op_edit, 
                op_delete,  user_cre
              ) VALUES (
                :profile, :page, :visibility, :op_add, :op_edit,
                :op_delete, :user_cre
              )";
    
    $queryAutoIncrement = "SELECT MAX(idAPU) as idAPU FROM profile";
    
    $params = array(
        ':profile' => $_POST['profile'],
        ':page' => $_POST['page'],
        ':visibility' => $_POST['visibility'],
        ':op_add' => $_POST['op_add'],
        ':op_edit' => $_POST['op_edit'],
        ':op_delete' => $_POST['op_delete'],
        // ':idUser' => $_POST['idUser'],
        ':user_cre' => $_POST['user_cre']
    );
    
    try {
        $result = metodPost($query, $queryAutoIncrement, $params, 'profile');
        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' => 'Error adding permission: ' . $e->getMessage()]);
    }
    exit();
}

// Update permission
if ($_POST['METHOD'] == 'PUT') {
    unset($_POST['METHOD']);
    $idAPU = $_GET['idAPU'];
    
    $query = "UPDATE profile SET 
                visibility = :visibility,
                op_add = :op_add,
                op_edit = :op_edit,
                op_delete = :op_delete,
                user_upd = :user_upd
              WHERE idAPU = :idAPU";
    
    $params = array(
        ':idAPU' => $idAPU,
        ':visibility' => $_POST['visibility'],
        ':op_add' => $_POST['op_add'],
        ':op_edit' => $_POST['op_edit'],
        ':op_delete' => $_POST['op_delete'],
        ':user_upd' => $_POST['user_upd']
    );
    
    try {
        $result = metodPut($query, $params, 'profile');
        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' => 'Error updating permission: ' . $e->getMessage()]);
    }
    exit();
}


if ($_POST['METHOD'] == 'DELETE') {
    unset($_POST['METHOD']);
    $idAPU = $_GET['idAPU'];
    
    $query = "DELETE FROM profile WHERE idAPU = :idAPU";
    $params = array(':idAPU' => $idAPU);
    
    try {
        $result = metodDelete($query, $params, 'profile');
        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' => 'Error deleting permission: ' . $e->getMessage()]);
    }
    exit();
}

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