<?php
// ============================================================
// FXHUNTER PORTAL — USER AUTH MIDDLEWARE (NEW VPS SYSTEM)
// ============================================================

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

require_once __DIR__ . "/../config.php";

if (!isset($conn)) {
    die("❌ Database connection missing — check config.php");
}

// ------------------------------------------------------------
// 1. USER MUST BE LOGGED IN
// ------------------------------------------------------------
if (empty($_SESSION['user_id'])) {
    header("Location: /portal/login.php");
    exit;
}

$user_id = intval($_SESSION['user_id']);

// ------------------------------------------------------------
// 2. LOAD USER FROM fxh_users
// ------------------------------------------------------------
$stmt = $conn->prepare("
    SELECT id, email, password_hash, status, created_at
    FROM fxh_users
    WHERE id = ?
    LIMIT 1
");
$stmt->bind_param("i", $user_id);
$stmt->execute();

$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    session_destroy();
    header("Location: /portal/login.php");
    exit;
}

$_SESSION['user'] = $user;
$user_email = $user['email'];

// ------------------------------------------------------------
// 3. LOAD LICENSES FROM fxh_licenses (BY EMAIL, NOT ID)
// ------------------------------------------------------------
$stmt = $conn->prepare("
    SELECT 
        id,
        license_key,
        plan,
        active,
        mt5_account,
        expires_at,
        created_at
    FROM fxh_licenses
    WHERE user_email = ?
    ORDER BY id DESC
");
$stmt->bind_param("s", $user_email);
$stmt->execute();
$res = $stmt->get_result();

$licenses = [];
$now = time();

while ($row = $res->fetch_assoc()) {

    // Status
    $row['status_label'] = intval($row['active']) === 1 ? "ACTIVE" : "INACTIVE";

    // Expiry Check
    if (!empty($row['expires_at'])) {
        $exp = strtotime($row['expires_at']);
        $row['expired'] = ($exp !== false && $exp < $now);
    } else {
        $row['expired'] = false;
    }

    $licenses[] = $row;
}

// Save in session
$_SESSION['licenses'] = $licenses;
?>
