<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) session_start();

// DB
$dbFile = __DIR__ . '/../core/db.php';
if (!is_file($dbFile)) $dbFile = __DIR__ . '/../../core/db.php';
require_once $dbFile;

function db_is_pdo(): bool    { return isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO; }
function db_is_mysqli(): bool { return isset($GLOBALS['db']) && $GLOBALS['db'] instanceof mysqli; }

function db_fetch_one(string $sql, array $params = []): ?array {
  if (db_is_pdo()) {
    $pdo = $GLOBALS['pdo'];
    $st = $pdo->prepare($sql);
    $st->execute($params);
    $row = $st->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
  }
  if (db_is_mysqli()) {
    $db = $GLOBALS['db'];
    $st = $db->prepare($sql);
    if (!$st) return null;
    if ($params) { $types = str_repeat('s', count($params)); $st->bind_param($types, ...$params); }
    $st->execute();
    $res = $st->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $st->close();
    return $row ?: null;
  }
  return null;
}

function db_exec(string $sql, array $params = []): bool {
  if (db_is_pdo()) {
    $pdo = $GLOBALS['pdo'];
    $st = $pdo->prepare($sql);
    return $st->execute($params);
  }
  if (db_is_mysqli()) {
    $db = $GLOBALS['db'];
    $st = $db->prepare($sql);
    if (!$st) return false;
    if ($params) { $types = str_repeat('s', count($params)); $st->bind_param($types, ...$params); }
    $ok = $st->execute();
    $st->close();
    return (bool)$ok;
  }
  return false;
}

// giriş zorunlu
if (empty($_SESSION['user_id'])) {
  header("Location: login.php");
  exit;
}

// kullanıcıyı DB’den doğrula (status kontrol + lang çek)
$uid = (int)$_SESSION['user_id'];
$u = db_fetch_one("SELECT id, full_name, role, status, lang FROM users WHERE id=? LIMIT 1", [(string)$uid]);

if (!$u || ($u['status'] ?? '') !== 'active') {
  // pasif/yanlış ise logout
  header("Location: logout.php");
  exit;
}

// session sync
$_SESSION['full_name'] = (string)$u['full_name'];
$_SESSION['role']      = (string)$u['role'];

// Dil: DB > session > cookie
if (!empty($u['lang'])) {
  $_SESSION['lang'] = (string)$u['lang'];
  setcookie('lang', (string)$u['lang'], time() + (86400 * 365), "/");
}

// Role guard (sayfa bazında opsiyonel)
function require_role(array $allowedRoles): void {
  $r = (string)($_SESSION['role'] ?? '');
  if (!in_array($r, $allowedRoles, true)) {
    http_response_code(403);
    die("403 Yetkisiz erişim");
  }
}

// Dil değiştirme (header dropdown POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'set_lang') {
  $new = (string)($_POST['lang'] ?? 'tr');
  $new = in_array($new, ['tr','en'], true) ? $new : 'tr';

  $_SESSION['lang'] = $new;
  setcookie('lang', $new, time() + (86400 * 365), "/");
  db_exec("UPDATE users SET lang=? WHERE id=?", [$new, (string)$uid]);

  // aynı sayfaya dön
  $back = $_POST['back'] ?? ($_SERVER['HTTP_REFERER'] ?? 'dashboard.php');
  header("Location: " . $back);
  exit;
}
