<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/helpers.php';

function current_user(): ?array {
  start_app_session();
  if (empty($_SESSION['uid'])) return null;

  try {
    $st = db()->prepare("SELECT id, role, name, email, status FROM users WHERE id=? LIMIT 1");
    $st->execute([ (int)$_SESSION['uid'] ]);
    $u = $st->fetch();
    if (!$u || ($u['status'] ?? '') !== 'active') return null;
    return $u;
  } catch (Throwable $e) {
    return null;
  }
}

function require_role(string $role): array {
  $u = current_user();
  if (!$u || ($u['role'] ?? '') !== $role) {
    header('Location: ' . app_base('seller/login.php'));
    exit;
  }
  return $u;
}

function login_attempt(string $email, string $pass): array {
  $email = trim(mb_strtolower($email));

  $st = db()->prepare("SELECT id, role, name, email, password_hash, status FROM users WHERE email=? LIMIT 1");
  $st->execute([$email]);
  $row = $st->fetch();

  if (!$row || ($row['status'] ?? '') !== 'active') {
    return ['ok'=>false,'err'=>'E-posta veya şifre hatalı.'];
  }
  if (!password_verify($pass, (string)$row['password_hash'])) {
    return ['ok'=>false,'err'=>'E-posta veya şifre hatalı.'];
  }

  start_app_session();
  session_regenerate_id(true);

  $id   = (int)$row['id'];
  $name = (string)($row['name'] ?? 'Satıcı');

  // ✅ ana oturum
  $_SESSION['uid'] = $id;

  // ✅ eski/alternatif anahtarlar (loop önleyici)
  $_SESSION['seller_id'] = $id;
  $_SESSION['satici_id'] = $id;

  $_SESSION['firma_adi']        = $name;
  $_SESSION['seller_firma_adi'] = $name;

  db()->prepare("UPDATE users SET last_login_at=NOW() WHERE id=?")->execute([$id]);

  return ['ok'=>true,'role'=>(string)$row['role']];
}



function logout(): void {
  start_app_session();
  $_SESSION = [];
  if (ini_get('session.use_cookies')) {
    $p = session_get_cookie_params();
    setcookie(session_name(), '', time()-42000, $p['path'], $p['domain'], (bool)$p['secure'], (bool)$p['httponly']);
  }
  session_destroy();
}
