<?php
// api/role-permissions/index.php

require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../helpers/response.php';
require_once '../../helpers/request.php';
require_once '../../helpers/auth.php';

$method = getRequestMethod();
// Check for _method override
if (isset($_POST['_method'])) {
    $_SERVER['REQUEST_METHOD'] = strtoupper($_POST['_method']);
}
if ($method === 'OPTIONS') {
    http_response_code(200);
    exit;
}

requireAdmin();

// GET - Get permissions for a role
if ($method === 'GET') {    
    $role_id = isset($_GET['role_id']) ? intval($_GET['role_id']) : null;
    
    if (!$role_id) {
        sendError('role_id required', 400);
    }
    
    try {
        // Check if role exists
        $stmt = $pdo->prepare("SELECT id FROM roles WHERE id = :id");
        $stmt->execute([':id' => $role_id]);
        if (!$stmt->fetch()) {
            sendError('Role not found', 404);
        }
        
        // Get permissions for this role
        $stmt = $pdo->prepare("
            SELECT p.id, p.name 
            FROM permissions p
            JOIN role_permissions rp ON rp.permission_id = p.id
            WHERE rp.role_id = :role_id
            ORDER BY p.name
        ");
        $stmt->execute([':role_id' => $role_id]);
        $permissions = $stmt->fetchAll();
        
        sendSuccess($permissions);
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
// POST - Assign permission to role
} elseif ($method === 'POST') {
    $data = getRequestData();
    
    validateRequiredFields($data, ['role_id', 'permission_id']);
    
    try {
        // Check if role exists
        $stmt = $pdo->prepare("SELECT id FROM roles WHERE id = :id");
        $stmt->execute([':id' => $data['role_id']]);
        if (!$stmt->fetch()) {
            sendError('Role not found', 404);
        }
        
        // Check if permission exists
        $stmt = $pdo->prepare("SELECT id FROM permissions WHERE id = :id");
        $stmt->execute([':id' => $data['permission_id']]);
        if (!$stmt->fetch()) {
            sendError('Permission not found', 404);
        }
        
        // Check if already assigned
        $stmt = $pdo->prepare("
            SELECT id FROM role_permissions 
            WHERE role_id = :role_id AND permission_id = :permission_id
        ");
        $stmt->execute([
            ':role_id' => $data['role_id'],
            ':permission_id' => $data['permission_id']
        ]);
        
        if ($stmt->fetch()) {
            sendError('Permission already assigned to this role', 400);
        }
        
        // Assign permission
        $stmt = $pdo->prepare("
            INSERT INTO role_permissions (role_id, permission_id) 
            VALUES (:role_id, :permission_id)
        ");
        $stmt->execute([
            ':role_id' => $data['role_id'],
            ':permission_id' => $data['permission_id']
        ]);
        
        sendSuccess([
            'role_id' => $data['role_id'],
            'permission_id' => $data['permission_id']
        ], 'Permission assigned to role');
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
    
// DELETE - Remove permission from role
// DELETE - Remove permission from role
} elseif ($method === 'DELETE') {
    // Try to get from query string first, then from body
    $role_id = isset($_GET['role_id']) ? intval($_GET['role_id']) : null;
    $permission_id = isset($_GET['permission_id']) ? intval($_GET['permission_id']) : null;
    
    // If not in query, try to get from request body
    if (!$role_id || !$permission_id) {
        $data = getRequestData();
        $role_id = $data['role_id'] ?? null;
        $permission_id = $data['permission_id'] ?? null;
    }
    
    if (!$role_id || !$permission_id) {
        sendError('Missing required fields: role_id, permission_id', 400);
    }
    
    try {
        $stmt = $pdo->prepare("
            DELETE FROM role_permissions 
            WHERE role_id = :role_id AND permission_id = :permission_id
        ");
        $stmt->execute([
            ':role_id' => $role_id,
            ':permission_id' => $permission_id
        ]);
        
        if ($stmt->rowCount() === 0) {
            sendError('Permission assignment not found', 404);
        }
        
        sendSuccess(null, 'Permission removed from role');
        
    } catch (PDOException $e) {
        sendError('Database error: ' . $e->getMessage(), 500);
    }
} else {
    sendError('Method not allowed', 405);
}
?>