<?php
/**
 * Enterprise HRM ERP System - Edit Permission
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

// Check if user is Super Admin - with better error handling
startSession();

// Force refresh role_code from database
$roleCode = $_SESSION['role_code'] ?? '';
if (empty($roleCode) && isset($_SESSION['user_id'])) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT r.role_code 
            FROM users u
            INNER JOIN roles r ON u.role_id = r.role_id
            WHERE u.user_id = ?
        ");
        $stmt->execute([$_SESSION['user_id']]);
        $userRole = $stmt->fetch();
        if ($userRole && !empty($userRole['role_code'])) {
            $roleCode = $userRole['role_code'];
            $_SESSION['role_code'] = $roleCode;
        }
    } catch (Exception $e) {
        error_log("Error loading role_code: " . $e->getMessage());
    }
}

// Check if Super Admin (case-insensitive)
if (strtolower($roleCode) !== 'super_admin') {
    $_SESSION['error'] = 'Only Super Admin can edit permissions. Your role: ' . ($roleCode ?: 'Unknown');
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$pageTitle = 'Edit Permission';
$currentModule = 'settings';

$permissionId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($permissionId <= 0) {
    redirect(BASE_URL . '/admin/permissions.php', 'Invalid permission ID.', 'error');
}

// Get permission
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM permissions WHERE permission_id = ?");
    $stmt->execute([$permissionId]);
    $permission = $stmt->fetch();
    
    if (!$permission) {
        redirect(BASE_URL . '/admin/permissions.php', 'Permission not found.', 'error');
    }
    
} catch (Exception $e) {
    error_log("Error loading permission: " . $e->getMessage());
    redirect(BASE_URL . '/admin/permissions.php', 'Error loading permission data.', 'error');
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'permission_name' => sanitize($_POST['permission_name'] ?? ''),
        'permission_module' => sanitize($_POST['permission_module'] ?? ''),
        'permission_description' => sanitize($_POST['permission_description'] ?? ''),
    ];
    
    // Validation
    if (empty($formData['permission_name'])) {
        $errors[] = 'Permission name is required.';
    }
    
    if (empty($formData['permission_module'])) {
        $errors[] = 'Permission module is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $stmt = $db->prepare("
                UPDATE permissions SET
                    permission_name = ?,
                    permission_module = ?,
                    permission_description = ?
                WHERE permission_id = ?
            ");
            $stmt->execute([
                $formData['permission_name'],
                $formData['permission_module'],
                $formData['permission_description'] ?: null,
                $permissionId
            ]);
            
            logAudit('UPDATE', 'permissions', $permissionId);
            
            redirect(BASE_URL . '/admin/permissions.php', 'Permission updated successfully.');
            
        } catch (Exception $e) {
            error_log("Error updating permission: " . $e->getMessage());
            $errors[] = 'An error occurred while updating permission.';
        }
    }
}

include __DIR__ . '/../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Edit Permission</h2>
        <div style="display: flex; gap: 10px;">
            <a href="<?php echo BASE_URL; ?>/modules/settings/index.php" class="btn btn-secondary">Back to Settings</a>
            <a href="<?php echo BASE_URL; ?>/admin/permissions.php" class="btn btn-secondary">Back to Permissions</a>
        </div>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="margin-top: 20px;">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <form method="POST" style="margin-top: 20px;">
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <div class="form-group">
                <label class="form-label">Permission Code</label>
                <input type="text" class="form-control" value="<?php echo htmlspecialchars($permission['permission_code']); ?>" disabled>
                <small style="color: var(--text-secondary);">Permission code cannot be changed</small>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="permission_name">Permission Name *</label>
                <input type="text" id="permission_name" name="permission_name" class="form-control" required
                       value="<?php echo htmlspecialchars($permission['permission_name']); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="permission_module">Module *</label>
                <input type="text" id="permission_module" name="permission_module" class="form-control" required
                       value="<?php echo htmlspecialchars($permission['permission_module']); ?>">
            </div>
            
            <div class="form-group" style="grid-column: 1 / -1;">
                <label class="form-label" for="permission_description">Description</label>
                <textarea id="permission_description" name="permission_description" class="form-control" rows="3"><?php echo htmlspecialchars($permission['permission_description'] ?? ''); ?></textarea>
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right; padding-top: 20px; border-top: 1px solid var(--border-color);">
            <a href="<?php echo BASE_URL; ?>/admin/permissions.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Update Permission</button>
        </div>
    </form>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
