<?php
if (!defined('ROOT_FOLDER')) { require_once(dirname(__DIR__, 3) . '/init.php'); }
m_secure_session_start();
if (!m_admin_check()) { m_redirect(ADMIN_URL . '/login'); }
m_validate_session_security();


$db = new DB();

if ($_SERVER['REQUEST_METHOD'] === 'POST'){
	$csrf = $_POST['csrf_token'] ?? '';
	if (!isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token']['value'] ?? '', $csrf)) {
		m_set_session('formSuccess', false);
		m_set_session('error_message', lang('security.csrf_invalid', [], 'Güvenlik token\'ı geçersiz!'));
		m_redirect(ADMIN_URL . '/roles/create');
	}
	$name = trim((string)($_POST['role_name'] ?? ''));
	$name = preg_replace('/[^a-zA-Z0-9_\-]/','_', $name);
	if ($name === ''){ m_redirect(ADMIN_URL . '/roles/create'); }
	$exists = $db->table('role_permissions')->where('role_name','=',$name)->where('module','=','*')->get();
	if (empty($exists['data'])){
		$db->table('role_permissions')->insert([
			'role_name' => $name,
			'module' => '*',
			'can_view' => 1,
			'can_create' => 0,
			'can_edit' => 0,
			'can_delete' => 0,
		]);
	}
	m_set_session('formSuccess', true);
	m_set_session('success_message', lang('form_success_message', [], 'Değişiklikler Başarıyla Uygulandı!'));
	m_redirect(ADMIN_URL . '/roles/edit?role=' . urlencode($name));
}
?>
<div class="container-fluid">
	<h1 class="mb-4"><?= lang('roles.add_role', [], 'Rol Ekle') ?></h1>
	<div class="card">
		<div class="card-body">
			<form method="post">
				<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']['value'] ?? '', ENT_QUOTES, 'UTF-8') ?>" />
				<div class="row g-3">
					<div class="col-md-6">
						<label class="form-label"><?= lang('roles.role_name', [], 'Rol') ?></label>
						<input name="role_name" type="text" class="form-control" placeholder="editor, manager ..." required>
					</div>
				</div>
				<div class="mt-3">
					<button type="submit" class="btn btn-primary"><?= lang('create', [], 'Oluştur') ?></button>
				</div>
			</form>
		</div>
	</div>
</div>


