<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

role_module_boot();

if (!is_post()) {
    redirect('app/modules/roles/index.php');
}

require_valid_csrf();

$action = (string) ($_POST['action'] ?? '');

if ($action === 'create') {
    role_module_boot(true);
    remember_old_input($_POST);

    $errors = [];
    $payload = validate_role_payload($_POST, $errors, null);

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the role form errors.']);
        redirect('app/modules/roles/create.php');
    }

    db_query(
        'INSERT INTO roles (name, description, created_at) VALUES (:name, :description, NOW())',
        ['name' => $payload['name'], 'description' => $payload['description'] !== '' ? $payload['description'] : null]
    );

    $roleId = (int) db()->lastInsertId();
    foreach ($payload['permission_ids'] as $permissionId) {
        db_query('INSERT INTO role_permissions (role_id, permission_id) VALUES (:role_id, :permission_id)', [
            'role_id' => $roleId,
            'permission_id' => $permissionId,
        ]);
    }

    audit_log('create_role', 'roles', $roleId, null, [
        'name' => $payload['name'],
        'description' => $payload['description'],
        'permission_ids' => $payload['permission_ids'],
    ]);

    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Role created successfully.']);
    redirect('app/modules/roles/view.php?id=' . $roleId);
}

if ($action === 'update') {
    role_module_boot(true);
    $roleId = (int) ($_POST['id'] ?? 0);
    $existingRole = find_role_or_abort($roleId);
    remember_old_input($_POST);

    $errors = [];
    $payload = validate_role_payload($_POST, $errors, $roleId);

    if (is_system_super_admin_role($existingRole) && $payload['name'] !== 'Super Admin') {
        $errors['name'] = 'The Super Admin role name is system-protected.';
    }

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the role form errors.']);
        redirect('app/modules/roles/edit.php?id=' . $roleId);
    }

    db_query(
        'UPDATE roles SET name = :name, description = :description WHERE id = :id',
        [
            'id' => $roleId,
            'name' => is_system_super_admin_role($existingRole) ? 'Super Admin' : $payload['name'],
            'description' => $payload['description'] !== '' ? $payload['description'] : null,
        ]
    );

    if (!is_system_super_admin_role($existingRole)) {
        db_query('DELETE FROM role_permissions WHERE role_id = :role_id', ['role_id' => $roleId]);
        foreach ($payload['permission_ids'] as $permissionId) {
            db_query('INSERT INTO role_permissions (role_id, permission_id) VALUES (:role_id, :permission_id)', [
                'role_id' => $roleId,
                'permission_id' => $permissionId,
            ]);
        }
    }

    audit_log('update_role', 'roles', $roleId, $existingRole, [
        'name' => is_system_super_admin_role($existingRole) ? 'Super Admin' : $payload['name'],
        'description' => $payload['description'],
        'permission_ids' => is_system_super_admin_role($existingRole) ? 'bypass' : $payload['permission_ids'],
    ]);

    clear_old_input();
    unset($_SESSION['permissions'], $_SESSION['_permissions_loaded_for']);
    flash('success', ['type' => 'success', 'message' => 'Role updated successfully.']);
    redirect('app/modules/roles/view.php?id=' . $roleId);
}

if ($action === 'delete') {
    $roleId = (int) ($_POST['id'] ?? 0);
    $existingRole = find_role_or_abort($roleId);

    if (is_system_super_admin_role($existingRole)) {
        flash('error', ['type' => 'danger', 'message' => 'The Super Admin role cannot be deleted.']);
        redirect('app/modules/roles/delete.php?id=' . $roleId);
    }

    if (role_is_in_use($roleId)) {
        flash('error', ['type' => 'danger', 'message' => 'This role is still assigned to users and cannot be deleted.']);
        redirect('app/modules/roles/delete.php?id=' . $roleId);
    }

    db_query('DELETE FROM role_permissions WHERE role_id = :role_id', ['role_id' => $roleId]);
    db_query('DELETE FROM roles WHERE id = :id', ['id' => $roleId]);

    audit_log('delete_role', 'roles', $roleId, $existingRole, null);
    flash('success', ['type' => 'success', 'message' => 'Role deleted successfully.']);
    redirect('app/modules/roles/index.php');
}

redirect('app/modules/roles/index.php');
