<?php
require_once __DIR__ . '/db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start(); // لازم قبل أي استخدام لـ $_SESSION
}

function require_login() {
  if (empty($_SESSION['admin_id'])) {
    header('Location: /admin/login.php');
    exit;
  }
}

function login($username, $password) {
  $stmt = db()->prepare('SELECT * FROM admins WHERE username = ?');
  $stmt->execute([$username]);
  $u = $stmt->fetch();
  if ($u && password_verify($password, $u['password'])) {
    $_SESSION['admin_id'] = $u['id'];
    $_SESSION['admin_username'] = $u['username'];
    $_SESSION['avatar'] = $u['avatar'] ?: 'default.png'; // صورة افتراضية لو مفيش

    return true;
  }
  return false;
}

function logout() {
  session_destroy();
}

function current_user(): ?array {
  return $_SESSION['user'] ?? null;
}

function current_user_id(): ?int {
  return $_SESSION['user']['id'] ?? null;
}
