<?php
// ─── Output / URLs ───
function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function redirect($url){ header('Location: ' . $url); exit; }
function base_url($p = ''){ $b = rtrim((string)config('base_url'), '/'); return $b . '/' . ltrim($p, '/'); }
function admin_url($p = ''){ return base_url('admin/' . ltrim($p, '/')); }
function link_url($u){ if ($u === '' || $u === null) return base_url(); return $u[0] === '/' ? base_url($u) : $u; }

// ─── Settings ───
function settings(){
  static $s = null;
  if ($s === null){ $s = []; foreach (db()->query('SELECT skey,svalue FROM settings') as $r){ $s[$r['skey']] = $r['svalue']; } }
  return $s;
}
function setting($k, $d = ''){ $s = settings(); return $s[$k] ?? $d; }

// ─── Auth ───
function current_user(){ return $_SESSION['user'] ?? null; }
function require_login(){ if (!current_user()) redirect(admin_url('?p=login')); }
function attempt_login($email, $pass){
  $st = db()->prepare('SELECT * FROM users WHERE email = ?');
  $st->execute([trim($email)]);
  $u = $st->fetch();
  if ($u && password_verify($pass, $u['password_hash'])){
    $_SESSION['user'] = ['id' => $u['id'], 'name' => $u['name'], 'email' => $u['email'], 'role' => $u['role']];
    return true;
  }
  return false;
}

// ─── CSRF ───
function csrf_token(){ if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16)); return $_SESSION['csrf']; }
function csrf_field(){ return '<input type="hidden" name="_csrf" value="' . csrf_token() . '">'; }
function csrf_check(){ if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['_csrf'] ?? '')){ http_response_code(419); exit('Session expired — go back and try again.'); } }

// ─── Flash ───
function flash($msg = null){
  if ($msg !== null){ $_SESSION['flash'] = $msg; return null; }
  $m = $_SESSION['flash'] ?? null; unset($_SESSION['flash']); return $m;
}

function slugify($t){ $t = strtolower(trim($t)); $t = preg_replace('/[^a-z0-9]+/', '-', $t); return trim($t, '-') ?: 'section'; }

// ─── Data access ───
function all_pages(){ return db()->query('SELECT * FROM pages ORDER BY sort, id')->fetchAll(); }
function find_page($slug, $publishedOnly = false){
  $q = 'SELECT * FROM pages WHERE slug = ?' . ($publishedOnly ? " AND status='published'" : '');
  $st = db()->prepare($q); $st->execute([$slug]); return $st->fetch();
}
function page_by_id($id){ $st = db()->prepare('SELECT * FROM pages WHERE id = ?'); $st->execute([$id]); return $st->fetch(); }
function page_sections($pid, $visibleOnly = false){
  $q = 'SELECT * FROM sections WHERE page_id = ?' . ($visibleOnly ? ' AND visible=1' : '') . ' ORDER BY sort, id';
  $st = db()->prepare($q); $st->execute([$pid]); return $st->fetchAll();
}
function all_posts($publishedOnly = false){
  $q = 'SELECT * FROM posts' . ($publishedOnly ? " WHERE status='published'" : '') . ' ORDER BY published_at DESC, id DESC';
  return db()->query($q)->fetchAll();
}
function find_post($slug, $publishedOnly = false){
  $q = 'SELECT * FROM posts WHERE slug = ?' . ($publishedOnly ? " AND status='published'" : '');
  $st = db()->prepare($q); $st->execute([$slug]); return $st->fetch();
}
function count_rows($table){ return (int) db()->query("SELECT COUNT(*) FROM `$table`")->fetchColumn(); }
