<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/config.php';

date_default_timezone_set(defined('APP_TIMEZONE') ? APP_TIMEZONE : 'Asia/Dhaka');

function pdo(): PDO {
    static $pdo = null;
    if ($pdo instanceof PDO) return $pdo;
    $charset = defined('DB_CHARSET') ? DB_CHARSET : 'utf8mb4';
    $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . $charset;
    $pdo = new PDO($dsn, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
    $pdo->exec('SET NAMES ' . $charset);
    return $pdo;
}

function e($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
function redirect(string $path): void { header('Location: ' . $path); exit; }
function now_sql(): string { return date('Y-m-d H:i:s'); }
function currency_symbol(): string { return '৳'; }
function money($amount): string { return currency_symbol() . number_format((float)$amount, 2); }

function default_settings(): array {
    return [
        'site_name' => defined('SITE_NAME') ? SITE_NAME : 'CK444.COM',
        'announcement' => '🔥 CK444.COM এ স্লট, লাইভ ক্যাসিনো, স্পোর্টস ও Aviator খেলুন। দ্রুত ডিপোজিট, স্মুথ উইথড্র এবং ২৪/৭ সাপোর্ট।',
        'withdraw_min' => '500',
        'withdraw_max' => '25000',
        'withdraw_fee' => '0',
        'support_url' => 'service.php',
        'aviator_url' => '../spribe/',
    ];
}

function get_setting(string $key, ?string $fallback = null): string {
    $defaults = default_settings();
    if ($fallback === null) $fallback = $defaults[$key] ?? '';
    try {
        $stmt = pdo()->prepare('SELECT setting_value FROM settings WHERE setting_key=? LIMIT 1');
        $stmt->execute([$key]);
        $v = $stmt->fetchColumn();
        return $v === false ? $fallback : (string)$v;
    } catch (Throwable $e) {
        return $fallback;
    }
}

function set_setting(string $key, string $value): void {
    $stmt = pdo()->prepare('INSERT INTO settings(setting_key,setting_value,updated_at) VALUES(?,?,?) ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value), updated_at=VALUES(updated_at)');
    $stmt->execute([$key, $value, now_sql()]);
}

function all_settings(): array {
    $s = default_settings();
    try {
        foreach (pdo()->query('SELECT setting_key, setting_value FROM settings') as $r) {
            $s[$r['setting_key']] = $r['setting_value'];
        }
    } catch (Throwable $e) {}
    return $s;
}

function clean_phone(string $phone): string {
    $phone = trim($phone);
    $phone = preg_replace('/[^0-9+]/', '', $phone);
    if (strpos($phone, '00') === 0) $phone = '+' . substr($phone, 2);
    return $phone;
}

function detect_country(string $phone): array {
    $p = clean_phone($phone);
    $digits = preg_replace('/\D+/', '', $p);
    if (strpos($p, '+92') === 0 || strpos($digits, '92') === 0 || preg_match('/^03[0-9]{9}$/', $digits)) {
        return ['PK', 'Pakistan', '+92'];
    }
    return ['BD', 'Bangladesh', '+880'];
}

function normalize_phone_for_country(string $phone): string {
    $phone = clean_phone($phone);
    [$cc, $country, $dial] = detect_country($phone);
    $digits = preg_replace('/\D+/', '', $phone);
    if ($cc === 'BD') {
        if (preg_match('/^01[0-9]{9}$/', $digits)) return '+88' . $digits;
        if (preg_match('/^8801[0-9]{9}$/', $digits)) return '+' . $digits;
    }
    if ($cc === 'PK') {
        if (preg_match('/^03[0-9]{9}$/', $digits)) return '+92' . substr($digits, 1);
        if (preg_match('/^92[0-9]{10}$/', $digits)) return '+' . $digits;
    }
    return $phone;
}

function normalize_phone_selected(string $phone, string $countryCode, string $dialCode): string {
    $digits = preg_replace('/\D+/', '', $phone);
    $countryCode = strtoupper(trim($countryCode));
    $dialCode = trim($dialCode) ?: ($countryCode === 'PK' ? '+92' : '+880');
    if ($digits === '') return '';
    if ($countryCode === 'PK') {
        if (preg_match('/^03[0-9]{9}$/', $digits)) return '+92' . substr($digits, 1);
        if (preg_match('/^3[0-9]{9}$/', $digits)) return '+92' . $digits;
        if (preg_match('/^92[0-9]{10}$/', $digits)) return '+' . $digits;
    }
    if ($countryCode === 'BD') {
        if (preg_match('/^01[0-9]{9}$/', $digits)) return '+88' . $digits;
        if (preg_match('/^1[0-9]{9}$/', $digits)) return '+880' . $digits;
        if (preg_match('/^8801[0-9]{9}$/', $digits)) return '+' . $digits;
    }
    if (strpos($phone, '+') === 0) return clean_phone($phone);
    return $dialCode . ltrim($digits, '0');
}

function country_from_code(string $code): array {
    $code = strtoupper(trim($code));
    if ($code === 'PK') return ['PK', 'Pakistan', '+92'];
    return ['BD', 'Bangladesh', '+880'];
}

function next_user_id(): string {
    $stmt = pdo()->query("SELECT id FROM users WHERE id LIKE 'U%' ORDER BY CAST(SUBSTRING(id,2) AS UNSIGNED) DESC LIMIT 1");
    $last = $stmt->fetchColumn();
    $num = $last ? ((int)substr((string)$last, 1) + 1) : 1;
    return 'U' . str_pad((string)$num, 5, '0', STR_PAD_LEFT);
}

function findUserById(string $id): ?array {
    $stmt = pdo()->prepare('SELECT * FROM users WHERE id=? LIMIT 1');
    $stmt->execute([$id]);
    $u = $stmt->fetch();
    return $u ?: null;
}

function phone_search_variants(string $phone): array {
    $normalized = normalize_phone_for_country($phone);
    $digits = preg_replace('/\D+/', '', $normalized);
    $variants = [$normalized, $digits];
    if (strpos($normalized, '+880') === 0) {
        $local = substr($digits, 3);
        $variants[] = $local;
        $variants[] = '0' . $local;
    }
    if (strpos($normalized, '+92') === 0) {
        $local = substr($digits, 2);
        $variants[] = $local;
        $variants[] = '0' . $local;
    }
    $clean = [];
    foreach ($variants as $v) { if ($v !== '' && !in_array($v, $clean, true)) $clean[] = $v; }
    return $clean;
}

function findUserByPhone(string $phone): ?array {
    $variants = phone_search_variants($phone);
    $marks = implode(',', array_fill(0, count($variants), '?'));
    $stmt = pdo()->prepare('SELECT * FROM users WHERE phone IN (' . $marks . ') LIMIT 1');
    $stmt->execute($variants);
    $u = $stmt->fetch();
    return $u ?: null;
}

function currentUser(): ?array {
    if (empty($_SESSION['user_id'])) return null;
    return findUserById((string)$_SESSION['user_id']);
}

function authRequired(): array {
    $u = currentUser();
    if (!$u) redirect('index.php#login');
    return $u;
}

function updateUserById(string $id, array $newUser): bool {
    if (!$newUser) return true;
    $allowed = ['phone','email','password_hash','country_code','country_name','dial_code','balance','bonus','safe_income','status','avatar','invite_code','referral_code','last_login'];
    $sets = [];
    $vals = [];
    foreach ($newUser as $k => $v) {
        if (!in_array($k, $allowed, true)) continue;
        $sets[] = "$k=?";
        $vals[] = $v;
    }
    if (!$sets) return true;
    $vals[] = $id;
    $stmt = pdo()->prepare('UPDATE users SET ' . implode(',', $sets) . ' WHERE id=?');
    return $stmt->execute($vals);
}

function addTransaction(string $userId, string $type, float $amount, string $status='success', string $note=''): void {
    $stmt = pdo()->prepare('INSERT INTO transactions(id,user_id,type,amount,status,note,created_at) VALUES(?,?,?,?,?,?,?)');
    $stmt->execute([uniqid('TX', true), $userId, $type, $amount, $status, $note, now_sql()]);
}

function userTransactions(string $userId, int $limit=12): array {
    $stmt = pdo()->prepare('SELECT * FROM transactions WHERE user_id=? ORDER BY created_at DESC LIMIT ' . (int)$limit);
    $stmt->execute([$userId]);
    return $stmt->fetchAll();
}

function payment_methods_for_country(string $countryCode, bool $activeOnly=true): array {
    $sql = 'SELECT * FROM payment_methods WHERE country_code=?';
    if ($activeOnly) $sql .= ' AND active=1';
    $sql .= ' ORDER BY sort_order ASC, id ASC';
    $stmt = pdo()->prepare($sql);
    $stmt->execute([$countryCode]);
    return $stmt->fetchAll();
}

function withdraw_method_options(string $countryCode): array {
    if ($countryCode === 'PK') {
        return [
            'easypaisa' => 'EasyPaisa',
            'jazzcash' => 'JazzCash',
            'bank_pk' => 'Pakistan Bank Transfer',
        ];
    }
    return [
        'bkash' => 'bKash',
        'nagad' => 'Nagad',
        'rocket' => 'Rocket',
        'bank_bd' => 'Bangladesh Bank Transfer',
    ];
}

function builtin_game_catalog(): array {
    return [
        ['title'=>'Super Ace','icon'=>'🎰','provider'=>'JILI','category'=>'slots','image_url'=>'assets/games/super-ace.png','game_url'=>'game.php?game=super-ace','is_hot'=>1,'active'=>1,'sort_order'=>10],
        ['title'=>'Aviator','icon'=>'✈️','provider'=>'SPRIBE','category'=>'crash','image_url'=>'assets/games/aviator.png','game_url'=>'../spribe/','is_hot'=>1,'active'=>1,'sort_order'=>20],
        ['title'=>'Fortune Tiger','icon'=>'🐯','provider'=>'PG SOFT','category'=>'slots','image_url'=>'assets/games/fortune-tiger.png','game_url'=>'game.php?game=fortune-tiger','is_hot'=>1,'active'=>1,'sort_order'=>30],
        ['title'=>'Fortune Gems','icon'=>'💎','provider'=>'JILI','category'=>'slots','image_url'=>'assets/games/fortune-gems.png','game_url'=>'game.php?game=fortune-gems','is_hot'=>1,'active'=>1,'sort_order'=>40],
        ['title'=>'Money Tree','icon'=>'🌳','provider'=>'JILI','category'=>'slots','image_url'=>'assets/games/money-tree.png','game_url'=>'game.php?game=money-tree','is_hot'=>1,'active'=>1,'sort_order'=>50],
        ['title'=>'Boxing King','icon'=>'🥊','provider'=>'JILI','category'=>'slots','image_url'=>'assets/games/boxing-king.png','game_url'=>'game.php?game=boxing-king','is_hot'=>1,'active'=>1,'sort_order'=>60],
        ['title'=>'Go Rush','icon'=>'🚀','provider'=>'JILI','category'=>'crash','image_url'=>'assets/games/go-rush.png','game_url'=>'game.php?game=go-rush','is_hot'=>1,'active'=>1,'sort_order'=>70],
        ['title'=>'JILI Provider','icon'=>'🎮','provider'=>'JILI','category'=>'slots','image_url'=>'assets/games/provider-jili.png','game_url'=>'game.php?provider=jili','is_hot'=>1,'active'=>1,'sort_order'=>80],
        ['title'=>'PG Soft','icon'=>'🎮','provider'=>'PG SOFT','category'=>'slots','image_url'=>'assets/games/provider-pg-soft.png','game_url'=>'game.php?provider=pg-soft','is_hot'=>1,'active'=>1,'sort_order'=>90],
        ['title'=>'PG Games','icon'=>'🎮','provider'=>'PG','category'=>'slots','image_url'=>'assets/games/provider-pg.png','game_url'=>'game.php?provider=pg','is_hot'=>1,'active'=>1,'sort_order'=>95],
        ['title'=>'Pragmatic Play','icon'=>'🎮','provider'=>'PRAGMATIC PLAY','category'=>'slots','image_url'=>'assets/games/provider-pragmatic-play.png','game_url'=>'game.php?provider=pragmatic-play','is_hot'=>1,'active'=>1,'sort_order'=>100],
        ['title'=>'Evolution Live','icon'=>'🎥','provider'=>'EVOLUTION','category'=>'casino','image_url'=>'assets/games/provider-evolution.png','game_url'=>'game.php?provider=evolution','is_hot'=>1,'active'=>1,'sort_order'=>110],
        ['title'=>'INOUT Live','icon'=>'🎥','provider'=>'INOUT','category'=>'casino','image_url'=>'assets/games/provider-inout.png','game_url'=>'game.php?provider=inout','is_hot'=>1,'active'=>1,'sort_order'=>120],
        ['title'=>'BGAMING','icon'=>'🎲','provider'=>'BGAMING','category'=>'casino','image_url'=>'assets/games/provider-bgaming.png','game_url'=>'game.php?provider=bgaming','is_hot'=>1,'active'=>1,'sort_order'=>130],
        ['title'=>'CQ9 Arcade','icon'=>'🎣','provider'=>'CQ9','category'=>'fishing','image_url'=>'assets/games/provider-cq9.png','game_url'=>'game.php?provider=cq9','is_hot'=>1,'active'=>1,'sort_order'=>140],
        ['title'=>'JDB Gaming','icon'=>'🕹️','provider'=>'JDB','category'=>'casino','image_url'=>'assets/games/provider-jdb.png','game_url'=>'game.php?provider=jdb','is_hot'=>1,'active'=>1,'sort_order'=>150],
        ['title'=>'Turbo Sports','icon'=>'⚽','provider'=>'TURBO GAMES','category'=>'sports','image_url'=>'assets/games/provider-turbo-games.png','game_url'=>'game.php?provider=turbo-games','is_hot'=>1,'active'=>1,'sort_order'=>160],
        ['title'=>'MG Games','icon'=>'🎮','provider'=>'MG','category'=>'slots','image_url'=>'assets/games/provider-mg.png','game_url'=>'game.php?provider=mg','is_hot'=>1,'active'=>1,'sort_order'=>170],
        ['title'=>'Mega Slots','icon'=>'🎰','provider'=>'JILI','category'=>'slots','image_url'=>'','game_url'=>'game.php?game=mega-slots','is_hot'=>1,'active'=>1,'sort_order'=>180],
        ['title'=>'Lucky Dice','icon'=>'🎲','provider'=>'PG SOFT','category'=>'casino','image_url'=>'','game_url'=>'game.php?game=lucky-dice','is_hot'=>1,'active'=>1,'sort_order'=>190],
        ['title'=>'Baccarat','icon'=>'🃏','provider'=>'EVOLUTION','category'=>'casino','image_url'=>'','game_url'=>'game.php?game=baccarat','is_hot'=>1,'active'=>1,'sort_order'=>200],
        ['title'=>'Dragon Tiger','icon'=>'🐉','provider'=>'SA GAMING','category'=>'casino','image_url'=>'','game_url'=>'game.php?game=dragon-tiger','is_hot'=>1,'active'=>1,'sort_order'=>210],
        ['title'=>'Fishing War','icon'=>'🎣','provider'=>'KA GAMING','category'=>'fishing','image_url'=>'','game_url'=>'game.php?game=fishing-war','is_hot'=>1,'active'=>1,'sort_order'=>220],
    ];
}

function merge_builtin_games(array $games): array {
    $seen = [];
    foreach ($games as $g) {
        $seen[strtolower(trim((string)($g['title'] ?? '')))] = true;
    }
    foreach (builtin_game_catalog() as $g) {
        $key = strtolower(trim($g['title']));
        if (!isset($seen[$key])) {
            $games[] = $g;
            $seen[$key] = true;
        }
    }
    usort($games, fn($a,$b) => ((int)($a['sort_order'] ?? 999)) <=> ((int)($b['sort_order'] ?? 999)));
    return $games;
}

function home_games(int $limit=80): array {
    try {
        $stmt = pdo()->prepare('SELECT * FROM games WHERE active=1 ORDER BY sort_order ASC, id ASC LIMIT ' . (int)$limit);
        $stmt->execute();
        return array_slice(merge_builtin_games($stmt->fetchAll()), 0, $limit);
    } catch (Throwable $e) {
        return array_slice(builtin_game_catalog(), 0, $limit);
    }
}

function get_deposit_requests(string $status='pending'): array {
    if ($status === 'all') $stmt = pdo()->query('SELECT d.*,u.country_name FROM deposit_requests d LEFT JOIN users u ON u.id=d.user_id ORDER BY d.created_at DESC LIMIT 300');
    else { $stmt = pdo()->prepare('SELECT d.*,u.country_name FROM deposit_requests d LEFT JOIN users u ON u.id=d.user_id WHERE d.status=? ORDER BY d.created_at DESC LIMIT 300'); $stmt->execute([$status]); }
    return $stmt->fetchAll();
}

function get_withdraw_requests(string $status='pending'): array {
    if ($status === 'all') $stmt = pdo()->query('SELECT w.*,u.phone,u.country_name FROM withdraw_requests w LEFT JOIN users u ON u.id=w.user_id ORDER BY w.created_at DESC LIMIT 300');
    else { $stmt = pdo()->prepare('SELECT w.*,u.phone,u.country_name FROM withdraw_requests w LEFT JOIN users u ON u.id=w.user_id WHERE w.status=? ORDER BY w.created_at DESC LIMIT 300'); $stmt->execute([$status]); }
    return $stmt->fetchAll();
}

function latest_users(int $limit=100): array {
    $stmt = pdo()->prepare('SELECT * FROM users ORDER BY created_at DESC LIMIT ' . (int)$limit);
    $stmt->execute();
    return $stmt->fetchAll();
}

function user_admin_summary(string $userId): array {
    $summary = ['tx'=>0, 'deposit_pending'=>0, 'withdraw_pending'=>0, 'deposit_total'=>0, 'withdraw_total'=>0];
    $st = pdo()->prepare('SELECT COUNT(*) FROM transactions WHERE user_id=?'); $st->execute([$userId]); $summary['tx'] = (int)$st->fetchColumn();
    $st = pdo()->prepare("SELECT COUNT(*) FROM deposit_requests WHERE user_id=? AND status='pending'"); $st->execute([$userId]); $summary['deposit_pending'] = (int)$st->fetchColumn();
    $st = pdo()->prepare("SELECT COUNT(*) FROM withdraw_requests WHERE user_id=? AND status='pending'"); $st->execute([$userId]); $summary['withdraw_pending'] = (int)$st->fetchColumn();
    $st = pdo()->prepare("SELECT COALESCE(SUM(amount),0) FROM deposit_requests WHERE user_id=? AND status='approved'"); $st->execute([$userId]); $summary['deposit_total'] = (float)$st->fetchColumn();
    $st = pdo()->prepare("SELECT COALESCE(SUM(amount),0) FROM withdraw_requests WHERE user_id=? AND status='approved'"); $st->execute([$userId]); $summary['withdraw_total'] = (float)$st->fetchColumn();
    return $summary;
}

function require_admin(): void {
    if (empty($_SESSION['admin_ok'])) redirect('login.php');
}

function check_installed(): bool {
    try { pdo()->query('SELECT 1 FROM users LIMIT 1'); return true; } catch (Throwable $e) { return false; }
}
