<?php
// Generated by setup_mariadb_project.sh — edit as needed.
// Baota / Local Deployment Settings - Change these to match your database
define('DB_HOST', '127.0.0.1');
define('DB_NAME', 'app_38451');
define('DB_USER', 'app_38451');
define('DB_PASS', '05a5bcfb-fa2e-4781-9241-aec4868564f1');

function db() {
  static $pdo;
  if (!$pdo) {
    $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,
    ]);
  }
  return $pdo;
}

function getRealIP() {
    if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        return $_SERVER['HTTP_CF_CONNECTING_IP'];
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    }
    return $_SERVER['REMOTE_ADDR'];
}

function getUserTotalRecharge($userId) {
    $stmt = db()->prepare("SELECT SUM(amount) FROM finance_requests WHERE user_id = ? AND type='recharge' AND status='approved' AND symbol='USDT'");
    $stmt->execute([$userId]);
    return (float)$stmt->fetchColumn() ?: 0;
}

function getAutoVipLevel($totalRecharge) {
    if ($totalRecharge >= 250000) return 5;
    if ($totalRecharge >= 180000) return 4;
    if ($totalRecharge >= 100000) return 3;
    if ($totalRecharge >= 50000) return 2;
    if ($totalRecharge >= 10000) return 1;
    return 0;
}

if (!function_exists('getSetting')) {
    function getSetting($key, $default = null) {
        try {
            $stmt = db()->prepare("SELECT setting_value FROM system_settings WHERE setting_key = ?");
            $stmt->execute([$key]);
            $val = $stmt->fetchColumn();
            return ($val !== false && $val !== '') ? $val : $default;
        } catch (Exception $e) {
            return $default;
        }
    }
}
