<?php
// auth_check.php — include at top of every user page
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/currency.php';
$user_id = $_SESSION['user_id'];

// Fetch user row
$u = $conn->query("SELECT * FROM users WHERE id=$user_id")->fetch_assoc();

// Auto-join internship for new users (within 2 days of registration)
$intern = $conn->query("SELECT * FROM plans WHERE slug='internship' LIMIT 1")->fetch_assoc();
if ($intern) {
    $existing = $conn->query("SELECT * FROM user_plans WHERE user_id=$user_id AND plan_id={$intern['id']} LIMIT 1")->fetch_assoc();
    if (!$existing) {
        $exp = date('Y-m-d H:i:s', strtotime('+2 days'));
        $conn->query("INSERT INTO user_plans (user_id,plan_id,expires_at) VALUES ($user_id,{$intern['id']},'$exp')");
    }
}

// Get user's active plan (highest tier active)
$active_plan = $conn->query("
    SELECT p.*, up.expires_at, up.joined_at
    FROM user_plans up
    JOIN plans p ON p.id = up.plan_id
    WHERE up.user_id = $user_id
      AND up.active = 1
      AND (up.expires_at IS NULL OR up.expires_at > NOW())
    ORDER BY p.sort_order DESC
    LIMIT 1
")->fetch_assoc();