<?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();

// Rol listesi (distinct)
$roleRows = $db->table('role_permissions')->where('1','=','1')->get();
$roles = [];
if (!empty($roleRows['data'])){
	foreach ($roleRows['data'] as $r){ $roles[(string)$r['role_name']] = true; }
}
// Varsayılan rolleri dahil et
$roles['admin'] = true; $roles['super_admin'] = true;
$roles = array_keys($roles);
// Süper admin listede gizli
$roles = array_values(array_filter($roles, function($r){ return (string)$r !== 'super_admin'; }));
sort($roles);

// Basit pagination (array tabanlı)
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$total = count($roles);
$start = ($page - 1) * $perPage;
$rolesPage = array_slice($roles, $start, $perPage);

$builtInRoles = ['super_admin','admin'];

$selectedRole = isset($_GET['role']) && $_GET['role'] !== '' ? preg_replace('/[^a-zA-Z0-9_\-]/','_', $_GET['role']) : 'admin';

// Modül listesi (admin/model/* klasörleri)
$modules = list_admin_modules();
// 'themes' modülünü listeden kaldır (sadece süper admin yetkisi için)
$modules = array_values(array_filter($modules, function($m){ return (string)$m !== 'themes'; }));
sort($modules);

// Rol ekleme
if (isset($_POST['action']) && $_POST['action']==='add_role'){
	$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/lists');
	}
	$name = trim((string)($_POST['role_name'] ?? ''));
	$name = preg_replace('/[^a-zA-Z0-9_\-]/','_', $name);
	if ($name === ''){ m_redirect(ADMIN_URL . '/roles/lists'); }
	// wildcard ile başlangıç kaydı
	$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_redirect(ADMIN_URL . '/roles/lists?role='.$name);
}

// Rol silme
if (isset($_POST['action']) && $_POST['action']==='delete_role'){
	$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/lists');
	}
	$name = trim((string)($_POST['role_name'] ?? ''));
	$name = preg_replace('/[^a-zA-Z0-9_\-]/','_', $name);
    if ($name !== '' && !in_array($name, $builtInRoles, true)){
        // Bu rolü kullanan admin var mı?
        $adminsWithRole = $db->table('admins')->where('role','=',$name)->get();
        if (!empty($adminsWithRole['data'])){
            m_set_session('formSuccess', false);
            m_set_session('error_message', lang('roles.cannot_delete_in_use', [], 'Bu rol bir veya daha fazla yönetici tarafından kullanılıyor.'));
            m_redirect(ADMIN_URL . '/roles/lists');
        }
        $db->table('role_permissions')->where('role_name','=',$name)->delete();
        m_set_session('formSuccess', true);
        m_set_session('success_message', lang('roles.deleted', [], 'Rol silindi.'));
    }
	m_redirect(ADMIN_URL . '/roles/lists');
}

// İzin kaydetme
if (isset($_POST['action']) && $_POST['action']==='save_perms'){
	$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/lists?role='.$selectedRole);
	}
	$role = $selectedRole;
	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/lists?role='.$selectedRole);
}

// Mevcut izinleri oku (seçili rol)
$permRows = $db->table('role_permissions')->where('role_name','=',$selectedRole)->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') ?></h1>
    <div class="card mb-3">
        <div class="card-body">
            <h5 class="card-title mb-3"><?= lang('roles.list', [], 'Roller') ?></h5>
            <div class="table-responsive">
                <table class="table table-striped align-middle">
                    <thead>
                        <tr>
                            <th><?= lang('roles.role_name', [], 'Rol') ?></th>
                            <th><?= lang('published', [], 'İşlemler') ?></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($rolesPage as $r): if ((string)$r==='super_admin') continue; ?>
                        <tr>
                            <td><?= htmlspecialchars($r, ENT_QUOTES, 'UTF-8') ?></td>
                            <td>
                                <a class="btn btn-sm btn-secondary" href="<?= ADMIN_URL ?>/roles/lists?role=<?= htmlspecialchars($r, ENT_QUOTES, 'UTF-8') ?>"><?= lang('edit', [], 'Düzenle') ?></a>
                                <?php if (!in_array($r, $builtInRoles, true) && (string)$r!=='super_admin'): ?>
                                <form method="post" class="d-inline" onsubmit="return confirm('<?= lang('roles.delete_confirm', [], 'Bu rolü silmek istediğinize emin misiniz?') ?>');">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']['value'] ?? '', ENT_QUOTES, 'UTF-8') ?>" />
                                    <input type="hidden" name="action" value="delete_role" />
                                    <input type="hidden" name="role_name" value="<?= htmlspecialchars($r, ENT_QUOTES, 'UTF-8') ?>" />
                                    <button type="submit" class="btn btn-sm btn-danger"><?= lang('remove', [], 'Sil') ?></button>
                                </form>
                                <?php else: ?>
                                <span class="text-muted ms-2"><?= lang('roles.builtin_protected', [], 'Yerleşik rol') ?></span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="row g-3 mb-3">
		<div class="col-12 d-flex justify-content-end">
			<?php $totalPages = (int)ceil(max(1,$total)/$perPage); if ($totalPages>1): ?>
			<nav>
				<ul class="pagination">
					<?php for ($p=1; $p<=$totalPages; $p++): ?>
					<li class="page-item <?= $p===$page ? 'active' : '' ?>"><a class="page-link" href="<?= ADMIN_URL ?>/roles/lists?page=<?= $p ?>"><?= $p ?></a></li>
					<?php endfor; ?>
				</ul>
			</nav>
			<?php endif; ?>
		</div>
		<div class="col-md-6">
			<form method="get" class="d-flex align-items-center gap-2">
				<input type="hidden" name="url" value="/roles/lists" />
				<label class="form-label m-0"><?= lang('roles.select_role', [], 'Rol Seçin') ?></label>
				<select name="role" class="form-select w-auto" onchange="this.form.submit()">
					<?php foreach ($roles as $r): ?>
					<option value="<?= htmlspecialchars($r, ENT_QUOTES, 'UTF-8') ?>" <?= $r===$selectedRole?'selected':'' ?>><?= htmlspecialchars($r, ENT_QUOTES, 'UTF-8') ?></option>
					<?php endforeach; ?>
				</select>
			</form>
		</div>
		<div class="col-md-6 text-end">
			<form method="post" class="d-inline-flex align-items-center gap-2">
				<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']['value'] ?? '', ENT_QUOTES, 'UTF-8') ?>" />
				<input type="hidden" name="action" value="add_role" />
				<label class="form-label m-0"><?= lang('roles.add_role', [], 'Rol Ekle') ?></label>
				<input type="text" name="role_name" class="form-control w-auto" placeholder="editor, manager ..." required />
				<button type="submit" class="btn btn-primary"><?= lang('create', [], 'Oluştur') ?></button>
			</form>
		</div>
	</div>

	<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') ?>" />
				<input type="hidden" name="action" value="save_perms" />
				<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>


