<?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 değişikliği isteği
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 . '/admins/lists');
	}
	$targetId = (int)($_POST['admin_id'] ?? 0);
	$newRole = trim((string)($_POST['role'] ?? ''));
	if ($targetId > 0 && in_array($newRole, ['admin','super_admin'], true)){
		// Son kalan süper admin'i normal admin yapmayı engelle
		if ($newRole === 'admin'){
			if (!has_other_super_admins($targetId)){
				m_set_session('formSuccess', false);
				m_set_session('error_message', lang('admins.cannot_demote_last_super', [], 'Son süper admin düşürülemez.'));
				m_redirect(ADMIN_URL . '/admins/lists');
			}
		}
		$db->table('admins')->where('id', '=', $targetId)->update(['role' => $newRole]);
		m_set_session('formSuccess', true);
		m_set_session('success_message', lang('admins.role_updated', [], 'Rol güncellendi.'));
	}
	m_redirect(ADMIN_URL . '/admins/lists');
}

// Basit pagination
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Toplam
$all = $db->table('admins')->where('role','!=','super_admin')->get();
$total = (int)($all['total_count'] ?? 0);

// Sayfa verisi
$admins = $db->table('admins')->where('role','!=','super_admin')->order('id','asc')->limit($perPage)->get();

?>
<div class="container-fluid">
	<h1 class="mb-4"><?= lang('admins.title', [], 'Yöneticiler') ?></h1>
	<div class="card">
		<div class="card-body table-responsive">
			<div class="row g-4 mb-3">
				<div class="col-sm-auto">
					<div>
						<?php if (!function_exists('can') || can('create','admins')): ?>
						<a href="<?= ADMIN_URL ?>/admins/create" class="btn btn-success add-btn"><i class="ri-add-line align-bottom me-1"></i><?=lang('create')?></a>
						<?php endif; ?>
					</div>
				</div>
			</div>
			<table class="table table-striped align-middle">
				<thead>
					<tr>
						<th>ID</th>
						<th><?= lang('profile.fields.email', [], 'Email') ?></th>
						<th><?= lang('profile.fields.name', [], 'Ad') ?></th>
						<th><?= lang('profile.fields.lastname', [], 'Soyad') ?></th>
						<th><?= lang('admins.role', [], 'Rol') ?></th>
						<th><?= lang('published', [], 'İşlemler') ?></th>
					</tr>
				</thead>
				<tbody>
<?php foreach (($admins['data'] ?? []) as $a): ?>
					<tr>
						<td><?= (int)$a['id'] ?></td>
						<td><?= htmlspecialchars((string)($a['email'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
						<td><?= htmlspecialchars((string)($a['name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
						<td><?= htmlspecialchars((string)($a['lastname'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
						<td>
							<span class="badge bg-<?= (isset($a['role']) && $a['role']==='super_admin') ? 'primary' : 'secondary' ?>">
								<?= isset($a['role']) ? htmlspecialchars((string)$a['role']) : 'admin' ?>
							</span>
						</td>
						<td>
							<form method="post" class="d-inline">
								<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']['value'] ?? '', ENT_QUOTES, 'UTF-8') ?>" />
								<input type="hidden" name="admin_id" value="<?= (int)$a['id'] ?>" />
								<?php if (!function_exists('can') || can('edit','admins')): ?>
								<select class="form-select form-select-sm d-inline w-auto" name="role">
									<option value="admin" <?= ((string)($a['role'] ?? 'admin')==='admin') ? 'selected' : '' ?>>admin</option>
								</select>
								<button type="submit" class="btn btn-sm btn-primary ms-2"><?= lang('save', [], 'Kaydet') ?></button>
								<?php endif; ?>
							</form>
							<?php if (!function_exists('can') || can('edit','admins')): ?>
							<a class="btn btn-sm btn-secondary ms-1" href="<?= ADMIN_URL ?>/admins/edit?id=<?= (int)$a['id'] ?>"><?= lang('edit', [], 'Düzenle') ?></a>
							<?php endif; ?>
							<?php if ((int)$a['id'] !== (int)m_get_session('m_admin') && (!function_exists('can') || can('delete','admins'))): ?>
							<a class="btn btn-sm btn-danger ms-1" href="<?= ADMIN_URL ?>/admins/delete?id=<?= (int)$a['id'] ?>" onclick="return confirm('Silinsin mi?');"><?= lang('remove', [], 'Sil') ?></a>
							<?php endif; ?>
						</td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		</div>
	</div>
</div>

<?php
// Basit pager
$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 ?>/admins/lists?page=<?= $p ?>"><?= $p ?></a></li>
		<?php endfor; ?>
	</ul>
</nav>
<?php endif; ?>


