<?php
declare(strict_types=1);

/**
 * lib/helpers.php
 * - Güvenli helper seti (redeclare korumalı)
 * - cfg(), base_url_dir(), json_out(), session helpers, crypto helpers
 */

if (!function_exists('e')) {
  function e(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  }
}

if (!function_exists('now_ts')) {
  function now_ts(): string {
    return date('Y-m-d H:i:s');
  }
}

if (!function_exists('cfg')) {
  function cfg(): array {
    static $c = null;
    if ($c === null) {
      $c = require __DIR__ . '/../config.php';
      if (!is_array($c)) $c = [];
    }
    return $c;
  }
}

if (!function_exists('is_https')) {
  function is_https(): bool {
    if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') return true;
    if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') return true;
    if (!empty($_SERVER['HTTP_CF_VISITOR']) && is_string($_SERVER['HTTP_CF_VISITOR']) && str_contains($_SERVER['HTTP_CF_VISITOR'], 'https')) return true;
    if (!empty($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] === 'https') return true;
    if (!empty($_SERVER['SERVER_PORT']) && (string)$_SERVER['SERVER_PORT'] === '443') return true;
    return false;
  }
}

/**
 * ✅ KRİTİK FIX:
 * Artık tam URL değil, SADECE path döndürür.
 * Örn: /tahta veya /tahta/admin
 */
if (!function_exists('base_url_dir')) {
  function base_url_dir(): string {
    $script = $_SERVER['SCRIPT_NAME'] ?? '/';
    $dir    = rtrim(str_replace('\\', '/', dirname($script)), '/');
    if ($dir === '' || $dir === '.') $dir = '/';
    // mutlaka "/" ile başlasın
    if ($dir[0] !== '/') $dir = '/' . $dir;
    return $dir;
  }
}

/**
 * Tam URL lazımsa bunu kullan.
 * Örn: https://domain.com/tahta/admin
 */
if (!function_exists('base_url_abs')) {
  function base_url_abs(): string {
    $scheme = is_https() ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
    return $scheme . '://' . $host . base_url_dir();
  }
}

if (!function_exists('json_out')) {
  function json_out(array $data, int $code = 200): void {
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
  }
}

/* Random helpers */
if (!function_exists('random_board_id')) {
  function random_board_id(): string {
    return 'B' . bin2hex(random_bytes(10)); // B + 20 hex
  }
}
if (!function_exists('random_code')) {
  function random_code(): string {
    return str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);
  }
}
if (!function_exists('random_nonce')) {
  function random_nonce(): string {
    return bin2hex(random_bytes(16)); // 32 hex
  }
}

/* Hash helpers */
if (!function_exists('sha256')) {
  function sha256(string $s): string {
    return hash('sha256', $s);
  }
}
if (!function_exists('hmac')) {
  function hmac(string $msg, string $key): string {
    return hash_hmac('sha256', $msg, $key);
  }
}

/* Session helpers */
if (!function_exists('start_session')) {
  function start_session(): void {
    if (session_status() === PHP_SESSION_ACTIVE) return;

    $c = cfg();
    $path = $c['cookie_path'] ?? '/';
    if (!is_string($path) || $path === '') $path = '/';

    // Aynı domainde çakışmasın
    if (session_name() !== 'TAHTA_SESS') {
      session_name('TAHTA_SESS');
    }

    session_set_cookie_params([
      'lifetime' => 0,
      'path'     => $path,
      'secure'   => is_https(),
      'httponly' => true,
      'samesite' => 'Lax',
    ]);

    session_start();
  }
}

if (!function_exists('csrf_token')) {
  function csrf_token(): string {
    start_session();
    if (empty($_SESSION['csrf'])) {
      $_SESSION['csrf'] = bin2hex(random_bytes(16));
    }
    return (string)$_SESSION['csrf'];
  }
}

if (!function_exists('require_login')) {
  function require_login(): void {
    start_session();
    if (empty($_SESSION['uid'])) {
      header('Location: login.php');
      exit;
    }
  }
}

/* Logging helper */
if (!function_exists('log_action')) {
  function log_action(mysqli $db, string $boardId, string $action, ?int $userId = null): void {
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    $ua = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255);
    $created = now_ts();

    $stmt = $db->prepare("INSERT INTO tahta_logs (board_id, action, user_id, ip, ua, created_at) VALUES (?,?,?,?,?,?)");
    if (!$stmt) return;

    $stmt->bind_param('ssisss', $boardId, $action, $userId, $ip, $ua, $created);
    $stmt->execute();
    $stmt->close();
  }
}
