<?php
// ✅ Standard PHP session setup
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.gc_maxlifetime', 31536000);
    ini_set('session.cookie_lifetime', 31536000);

    session_set_cookie_params([
        'lifetime' => 31536000,
        'path' => '/',
        'secure' => isset($_SERVER['HTTPS']),
        'httponly' => true,
        'samesite' => 'Lax'
    ]);

    session_start();
}

// ✅ Connect to the database
$host = "YOUR_DB_HOST";
$dbname = "YOUR_DB_NAME";
$username = "YOUR_DB_USER";
$password = "YOUR_DB_PASS";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
    $pdo->exec("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// ✅ Check license key (only once per session to reduce load)
if (!isset($_SESSION['license_check_status'])) {
    $stmt = $pdo->query("SELECT license_key, brand_name FROM branding WHERE id = 1");
    $row = $stmt->fetch();
    $licenseKey = $row['license_key'] ?? '';
    $brandName = urlencode($row['brand_name'] ?? '');

    $domain = $_SERVER['HTTP_HOST'];

    if (empty($licenseKey)) {
        die("<h1 style='color:red'>❌ System inactive: License key missing</h1>");
    }

    $validationURL = "https://mlmlead.pro/licenses/check-license.php?key=$licenseKey&domain=$domain&brand=$brandName";

    $result = @file_get_contents($validationURL);
    if (trim($result) !== 'VALID') {
        die("<h1 style='color:red'>❌ System inactive: Invalid license</h1>");
    }

    $_SESSION['license_check_status'] = 'valid';
}

// ✅ Redirect protection
$currentPage = basename($_SERVER['PHP_SELF']);
$protectedPages = [
    'user-dashboard.php', 'profile.php', 'my_leads.php', 'referrals.php',
    'settings.php', 'lead-capture.php', 'strategy-directory.php',
    'training-center.php', 'clicks.php', 'lead-source-matcher.php',
    'user-referred-activity.php', 'user-programs.php', 'bridge-settings.php',
    'create-lead-capture.php', 'submit-strategy.php', 'global-stats.php',
    'marketing-tools.php'
];

if (!isset($_SESSION['logged_in_user']) && in_array($currentPage, $protectedPages)) {
    $redirectTarget = basename($_SERVER['PHP_SELF']);
    header("Location: user-login.php?redirect=" . $redirectTarget);
    exit;
}
