<?php
/**
 * connection/db.php
 * Core DB connection + helper functions
 *
 * ── SETUP: Edit DB_NAME, DB_USER, DB_PASS below to match your server ──
 */

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

// ══ DB CREDENTIALS — EDIT THESE ══════════════════════════════════════════════
define('DB_HOST', 'localhost');
define('DB_USER', 'root');          // your MySQL username
define('DB_PASS', '');              // your MySQL password
define('DB_NAME', 'hisshogloabl'); // your database name

// ══ TRON / CONTRACT ══════════════════════════════════════════════════════════
define('CONTRACT_ADDRESS', 'TFrxf8ipZxETDjLNkE5q4xjK3t6EPA5gwi');
define('ADMIN_WALLET',     'TNGYrezy6AsTLzbbg44WYjYT96JgJ1ZoPL');

// ══ FEES ══════════════════════════════════════════════════════════════════════
define('ADMIN_FEE_PCT',  5.00);
define('REG_STEP1_USD', 30.00);
define('REG_STEP2_USD', 40.00);

// ══ PDO CONNECTION ════════════════════════════════════════════════════════════
function getDB(): PDO
{
    static $pdo = null;
    if ($pdo === null) {
        // NEVER die() here — let caller handle the exception
        $pdo = new PDO(
            'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]
        );
    }
    return $pdo;
}

// ══ URL HELPER ════════════════════════════════════════════════════════════════
function getBaseUrl(): string
{
    $proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    // Walk up to project root (2 levels from any page: User/Page.php or register/Page.php)
    $script = $_SERVER['SCRIPT_NAME'] ?? '';
    // Find the project folder (everything up to and including /DreamNew12 or similar)
    $parts = explode('/', trim($script, '/'));
    // Project root = first folder after host (index 0)
    $root = '/' . ($parts[0] ?? '');
    return $proto . '://' . $host . $root;
}

// ══ AUTH HELPERS ═════════════════════════════════════════════════════════════
function requireLogin(): void
{
    if (empty($_SESSION['member_id'])) {
        header('Location: ' . getBaseUrl() . '/register/Login.php');
        exit;
    }
}

function redirectIfLoggedIn(): void
{
    if (!empty($_SESSION['member_id'])) {
        header('Location: ' . getBaseUrl() . '/User/Dashboard.php');
        exit;
    }
}

// ══ USER HELPERS ══════════════════════════════════════════════════════════════
function getCurrentUser(): array
{
    if (empty($_SESSION['member_id']))
        return [];
    $st = getDB()->prepare('SELECT * FROM meddolic_user_details WHERE member_id=? LIMIT 1');
    $st->execute([$_SESSION['member_id']]);
    return $st->fetch() ?: [];
}

function getUserById(int $memberId): array
{
    if ($memberId <= 0)
        return [];
    $st = getDB()->prepare('SELECT * FROM meddolic_user_details WHERE member_id=? LIMIT 1');
    $st->execute([$memberId]);
    return $st->fetch() ?: [];
}

function generateUserId(): string
{
    $db = getDB();
    do {
        $id = (string) random_int(100000, 999999);
        $st = $db->prepare('SELECT member_id FROM meddolic_user_details WHERE user_id=? LIMIT 1');
        $st->execute([$id]);
    } while ($st->fetch());
    return $id;
}

// ══ PACKAGE / SETTINGS HELPERS ═══════════════════════════════════════════════
function getMiscSetting(): array
{
    try {
        $st = getDB()->query('SELECT * FROM meddolic_config_misc_setting LIMIT 1');
        return $st->fetch() ?: ['adminCharge' => 5.00, 'minPayout' => 0.004, 'maxPayout' => 120.00];
    } catch (Throwable $e) {
        return ['adminCharge' => 5.00, 'minPayout' => 0.004, 'maxPayout' => 120.00];
    }
}

function getPoolList(): array
{
    $st = getDB()->query('SELECT * FROM meddolic_config_pool_list WHERE poolStatus=1 ORDER BY poolLevel ASC');
    return $st->fetchAll();
}

function getMatrixPackages(): array
{
    $st = getDB()->query('SELECT * FROM meddolic_config_matrix_package ORDER BY poolPrice ASC');
    return $st->fetchAll();
}

// ══ INCOME TOTALS ════════════════════════════════════════════════════════════
function getReferralIncomeTotal(int $memberId): float
{
    $st = getDB()->prepare('SELECT COALESCE(SUM(netIncome),0) AS t FROM meddolic_user_referral_income WHERE memberId=? AND incomeType=1');
    $st->execute([$memberId]);
    return (float) ($st->fetch()['t'] ?? 0);
}

function getsponsorIncomeTotal(int $memberId): float
{
    $st = getDB()->prepare('SELECT COALESCE(SUM(netIncome),0) AS t FROM meddolic_user_referral_income WHERE memberId=? AND incomeType=2');
    $st->execute([$memberId]);
    return (float) ($st->fetch()['t'] ?? 0);
}

function getLevelIncomeTotal(int $memberId): float
{
    try {
        $st = getDB()->prepare('SELECT COALESCE(SUM(levelIncome),0) AS t FROM meddolic_user_level_income WHERE memberId=?');
        $st->execute([$memberId]);
        return (float) ($st->fetch()['t'] ?? 0);
    } catch (Throwable $e) {
        return 0.0;
    }
}

function getPoolIncomeTotal(int $memberId): float
{
    $st = getDB()->prepare('SELECT COALESCE(SUM(poolIncome),0) AS t FROM meddolic_user_pool_income WHERE memberId=?');
    $st->execute([$memberId]);
    return (float) ($st->fetch()['t'] ?? 0);
}

function getUpgradeIncomeTotal(int $memberId): float
{
    $st = getDB()->prepare('SELECT COALESCE(SUM(netIncome),0) AS t FROM meddolic_user_upgrade_income WHERE memberId=?');
    $st->execute([$memberId]);
    return (float) ($st->fetch()['t'] ?? 0);
}

function getDirectCount(int $memberId): int
{
    $st = getDB()->prepare('SELECT COUNT(*) AS c FROM meddolic_user_details WHERE sponser_id=? AND topup_flag=1');
    $st->execute([$memberId]);
    return (int) ($st->fetch()['c'] ?? 0);
}

function getTeamCount(int $memberId): int
{
    $st = getDB()->prepare('SELECT COUNT(*) AS c FROM meddolic_user_child_ids WHERE member_id=?');
    $st->execute([$memberId]);
    return (int) ($st->fetch()['c'] ?? 0);
}

// ══ FORMATTING ════════════════════════════════════════════════════════════════
function e(string $s): string
{
    return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}
function fmt(float $v, int $d = 2): string
{
    return number_format($v, $d);
}
function fmtUSD(float $v): string
{
    return '$' . number_format($v, 2);
}
