<?php
// ============================================================
//  includes/user_auth.php — User Portal Session Guard
//  Add at the TOP of every user-protected page:
//    require_once __DIR__ . '/includes/user_auth.php';
//  OR from a subfolder:
//    require_once dirname(__DIR__) . '/includes/user_auth.php';
// ============================================================

$_root = (defined('ROOT_PATH')) ? ROOT_PATH : dirname(__DIR__);
require_once $_root . '/includes/db.php';

if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.cookie_httponly', 1);
    ini_set('session.use_strict_mode', 1);
    session_start();
}

// ── Check login ───────────────────────────────────────────────
if (empty($_SESSION[USER_SESSION_KEY]) || empty($_SESSION['user_id'])) {
    header('Location: ' . APP_URL . '/user_login.php');
    exit;
}

// ── Session timeout ───────────────────────────────────────────
if (!empty($_SESSION['user_login_time'])) {
    if (time() - $_SESSION['user_login_time'] > USER_SESSION_LIFETIME) {
        session_unset();
        session_destroy();
        header('Location: ' . APP_URL . '/user_login.php?expired=1');
        exit;
    }
    $_SESSION['user_login_time'] = time();
}

// ── Refresh user data from DB ─────────────────────────────────
$current_user = db_fetch_one(
    "SELECT id, full_name, username, email, phone, bio, avatar, status, email_verified,
            last_login, created_at, program_interest, registration_source
     FROM users WHERE id = ? LIMIT 1",
    [$_SESSION['user_id']]
);

if (!$current_user) {
    // User deleted from DB — destroy session
    session_unset();
    session_destroy();
    header('Location: ' . APP_URL . '/user_login.php');
    exit;
}

// Banned or inactive check
if (in_array($current_user['status'], ['banned', 'inactive'])) {
    session_unset();
    session_destroy();
    header('Location: ' . APP_URL . '/user_login.php?suspended=1');
    exit;
}

// Keep session in sync with DB
$_SESSION['user_name']     = $current_user['full_name'];
$_SESSION['user_username'] = $current_user['username'];
$_SESSION['user_email']    = $current_user['email'];
$_SESSION['user_avatar']   = $current_user['avatar'];
$_SESSION['user_status']   = $current_user['status'];

// ── Unread notification count ─────────────────────────────────
$unread_notifications = (int)(db_fetch_one(
    "SELECT COUNT(*) AS c FROM notifications WHERE user_id = ? AND is_read = 0",
    [$current_user['id']]
)['c'] ?? 0);

// ── Enrolment count ───────────────────────────────────────────
$active_enrolments = (int)(db_fetch_one(
    "SELECT COUNT(*) AS c FROM enrolments
     WHERE user_id = ? AND status IN ('confirmed','in_progress')",
    [$current_user['id']]
)['c'] ?? 0);

// ── Helpers ───────────────────────────────────────────────────
function get_user_avatar_src(array $user, string $base = ''): string {
    $av = $user['avatar'] ?? '';
    if ($av && $av !== 'default_avatar.png') {
        return rtrim($base, '/') . '/assets/images/avatars/' . htmlspecialchars($av);
    }
    return rtrim($base, '/') . '/assets/images/avatars/default_avatar.png';
}

function get_user_initials(string $full_name): string {
    $parts = explode(' ', trim($full_name));
    if (count($parts) >= 2) {
        return strtoupper(substr($parts[0], 0, 1) . substr($parts[1], 0, 1));
    }
    return strtoupper(substr($full_name, 0, 1));
}