<?php
/**
 * Application Bootstrap & Session
 * PHP User Registration - https://rskworld.in
 * Developer: Molla Samser | RSK World
 * Contact: help@rskworld.in | +91 93305 39277
 * Year: 2026
 */

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

require_once __DIR__ . '/../config/database.php';

function isLoggedIn(): bool {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

function requireLogin(): void {
    if (!isLoggedIn()) {
        $redirect = (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '') ?: '/';
        header('Location: login.php?redirect=' . urlencode($redirect));
        exit;
    }
}

function getCurrentUser(): ?array {
    if (!isLoggedIn()) return null;
    $pdo = getDbConnection();
    // Base columns only so it works before migrations (last_login_at, is_admin added later)
    $stmt = $pdo->prepare('SELECT id, name, email, email_verified, created_at FROM users WHERE id = ?');
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();
    if (!$user) return null;
    // Add optional columns if they exist (no error if column missing)
    try {
        $stmt2 = $pdo->prepare('SELECT last_login_at, last_login_ip, is_admin, role, suspended, avatar_path FROM users WHERE id = ?');
        $stmt2->execute([$_SESSION['user_id']]);
        $row = $stmt2->fetch();
        if ($row) {
            $user['last_login_at'] = $row['last_login_at'] ?? null;
            $user['last_login_ip'] = $row['last_login_ip'] ?? null;
            $user['is_admin'] = $row['is_admin'] ?? null;
            $user['role'] = $row['role'] ?? null;
            $user['suspended'] = $row['suspended'] ?? null;
            $user['avatar_path'] = $row['avatar_path'] ?? null;
        }
    } catch (PDOException $e) {
        try {
            $stmt2 = $pdo->prepare('SELECT is_admin, role FROM users WHERE id = ?');
            $stmt2->execute([$_SESSION['user_id']]);
            $row = $stmt2->fetch();
            if ($row !== false) {
                $user['is_admin'] = $row['is_admin'] ?? null;
                $user['role'] = $row['role'] ?? null;
            }
        } catch (PDOException $e2) {
            try {
                $stmt2 = $pdo->prepare('SELECT is_admin FROM users WHERE id = ?');
                $stmt2->execute([$_SESSION['user_id']]);
                $row = $stmt2->fetch();
                if ($row !== false) $user['is_admin'] = $row['is_admin'] ?? null;
            } catch (PDOException $e3) {}
        }
        try {
            $stmt2 = $pdo->prepare('SELECT last_login_at FROM users WHERE id = ?');
            $stmt2->execute([$_SESSION['user_id']]);
            $row = $stmt2->fetch();
            if ($row !== false) $user['last_login_at'] = $row['last_login_at'] ?? null;
        } catch (PDOException $e2) {}
    }
    return $user;
}

function getCurrentUserRole(): string {
    $user = getCurrentUser();
    if ($user === null) return 'user';
    if (!empty($user['role']) && is_string($user['role'])) return $user['role'];
    if (!empty($user['is_admin'])) return 'admin';
    if (!defined('DEMO_ADMIN_EMAIL')) @require_once __DIR__ . '/../config/demo.php';
    if (!empty($user['email']) && defined('DEMO_SUPERADMIN_EMAIL') && strcasecmp($user['email'], DEMO_SUPERADMIN_EMAIL) === 0) return 'superadmin';
    if (!empty($user['email']) && defined('DEMO_ADMIN_EMAIL') && strcasecmp($user['email'], DEMO_ADMIN_EMAIL) === 0) return 'admin';
    return 'user';
}

function isAdmin(): bool {
    $role = getCurrentUserRole();
    return in_array($role, ['admin', 'superadmin'], true);
}

function isSuperAdmin(): bool {
    return getCurrentUserRole() === 'superadmin';
}

function requireAdmin(): void {
    requireLogin();
    if (!isAdmin()) {
        header('Location: dashboard.php');
        exit;
    }
}

function requireSuperAdmin(): void {
    requireLogin();
    if (!isSuperAdmin()) {
        header('Location: dashboard.php');
        exit;
    }
}
