<?php
/**
 * BAITARI — Auth Middleware
 * Include at the top of any protected page
 */
require_once __DIR__ . '/config.php';
session_start_secure();

$user = current_user();
if (!$user) {
    header('Location: ' . APP_URL . '/login.php?redirect=' . urlencode($_SERVER['REQUEST_URI']));
    exit;
}

// Inject user data as JS global
function inject_user_js(array $user): string {
    $safe = [
        'id'    => (int)$user['id'],
        'name'  => htmlspecialchars($user['name']),
        'role'  => htmlspecialchars($user['role']),
        'lang'  => htmlspecialchars($user['lang_pref'] ?? 'ar'),
        'theme' => htmlspecialchars($user['theme_pref'] ?? 'light'),
    ];
    return '<script>window.BAITARI_USER = ' . json_encode($safe, JSON_HEX_TAG) . ';</script>';
}

// Shorthand vars for views
$lang  = $user['lang_pref']  ?? 'ar';
$theme = $user['theme_pref'] ?? 'light';
$role  = $user['role']       ?? 'pet_owner';
$uid   = (int)($user['id']   ?? 0);
