<?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();
$role = isset($_GET['role']) ? preg_replace('/[^a-zA-Z0-9_\-]/','_', (string)$_GET['role']) : '';
if ($role === ''){ m_redirect(ADMIN_URL . '/roles/lists'); }
if ($role === 'super_admin'){ m_redirect(ADMIN_URL . '/roles/lists'); }

// Modül listesi
$modules = list_admin_modules();
// themes modülünü gizle (süper admin özel)
$modules = array_values(array_filter($modules, function($m){ return (string)$m !== 'themes'; }));
sort($modules);

// Kaydet
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/edit?role=' . urlencode($role));
	}
	foreach ($modules as $m){
		$view = isset($_POST['perm'][$m]['view']) ? 1 : 0;
		$create = isset($_POST['perm'][$m]['create']) ? 1 : 0;
		$edit = isset($_POST['perm'][$m]['edit']) ? 1 : 0;
		$delete = isset($_POST['perm'][$m]['delete']) ? 1 : 0;
		$existing = $db->table('role_permissions')->where('role_name','=',$role)->where('module','=',$m)->get();
		$data = ['role_name'=>$role,'module'=>$m,'can_view'=>$view,'can_create'=>$create,'can_edit'=>$edit,'can_delete'=>$delete];
		if (!empty($existing['data'])){
			$db->table('role_permissions')->where('id','=',$existing['data'][0]['id'])->update($data);
		} else {
			$db->table('role_permissions')->insert($data);
		}
	}
	m_set_session('formSuccess', true);
	m_set_session('success_message', lang('roles.saved', [], 'İzinler kaydedildi.'));
	m_redirect(ADMIN_URL . '/roles/edit?role=' . urlencode($role));
}

// İzinleri oku
$permRows = $db->table('role_permissions')->where('role_name','=',$role)->get();
$permMap = [];
if (!empty($permRows['data'])){
	foreach ($permRows['data'] as $r){ $permMap[(string)$r['module']] = $r; }
}
?>
<div class="container-fluid">
	<h1 class="mb-4"><?= lang('roles.title', [], 'Roller & İzinler') ?> - <small class="text-muted"><?= htmlspecialchars($role, ENT_QUOTES, 'UTF-8') ?></small></h1>
	<div class="card">
		<div class="card-body table-responsive">
			<form method="post">
				<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']['value'] ?? '', ENT_QUOTES, 'UTF-8') ?>" />
				<table class="table table-striped align-middle">
					<thead>
                        <tr>
                            <th><?= lang('table_title', [], 'Başlık') ?></th>
							<th><?= lang('status', [], 'Durum') ?> (view) <input type="checkbox" id="chk-view-all" class="ms-1"></th>
							<th>create <input type="checkbox" id="chk-create-all" class="ms-1"></th>
							<th>edit <input type="checkbox" id="chk-edit-all" class="ms-1"></th>
							<th>delete <input type="checkbox" id="chk-delete-all" class="ms-1"></th>
						</tr>
					</thead>
					<tbody>
                    <?php foreach ($modules as $m):
						$row = $permMap[$m] ?? ['can_view'=>1,'can_create'=>0,'can_edit'=>0,'can_delete'=>0];
					?>
						<tr>
                            <td><?= htmlspecialchars(module_label($m), ENT_QUOTES, 'UTF-8') ?></td>
							<td><input type="checkbox" class="perm-view" name="perm[<?= htmlspecialchars($m, ENT_QUOTES, 'UTF-8') ?>][view]" <?= ((int)($row['can_view'] ?? 0)===1)?'checked':'' ?>></td>
							<td><input type="checkbox" class="perm-create" name="perm[<?= htmlspecialchars($m, ENT_QUOTES, 'UTF-8') ?>][create]" <?= ((int)($row['can_create'] ?? 0)===1)?'checked':'' ?>></td>
							<td><input type="checkbox" class="perm-edit" name="perm[<?= htmlspecialchars($m, ENT_QUOTES, 'UTF-8') ?>][edit]" <?= ((int)($row['can_edit'] ?? 0)===1)?'checked':'' ?>></td>
							<td><input type="checkbox" class="perm-delete" name="perm[<?= htmlspecialchars($m, ENT_QUOTES, 'UTF-8') ?>][delete]" <?= ((int)($row['can_delete'] ?? 0)===1)?'checked':'' ?>></td>
						</tr>
					<?php endforeach; ?>
					</tbody>
				</table>
				<button type="submit" class="btn btn-success"><?= lang('save', [], 'Kaydet') ?></button>
			</form>
		</div>
	</div>
</div>

<script>
(function(){
	function toggleAll(selector, checked){
		document.querySelectorAll(selector).forEach(function(cb){ cb.checked = checked; });
	}
	document.getElementById('chk-view-all')?.addEventListener('change', function(){ toggleAll('.perm-view', this.checked); });
	document.getElementById('chk-create-all')?.addEventListener('change', function(){ toggleAll('.perm-create', this.checked); });
	document.getElementById('chk-edit-all')?.addEventListener('change', function(){ toggleAll('.perm-edit', this.checked); });
	document.getElementById('chk-delete-all')?.addEventListener('change', function(){ toggleAll('.perm-delete', this.checked); });
})();
</script>


