<?php
/**
 * মাস্টার GGR API
 * তোমার ক্লায়েন্ট প্যানেলের সাথে ১০০% মিল রাখা হয়েছে
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// ================== ডাটাবেস কানেকশন ==================
$host     = 'localhost';
$dbname   = 'mofhjrxa_ggrpanel';      // তোমার ডাটাবেসের নাম
$username = 'mofhjrxa_ggrpanel';       // ইউজারনেম
$password = 'mofhjrxa_ggrpanel';   // পাসওয়ার্ড

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'msg' => 'ডাটাবেস কানেকশন ব্যর্থ']);
    exit;
}

// ================== হেল্পার ফাংশন ==================
function respond($data) {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function get_client_ip() {
    return $_SERVER['HTTP_CF_CONNECTING_IP'] 
        ?? $_SERVER['HTTP_X_FORWARDED_FOR'] 
        ?? $_SERVER['REMOTE_ADDR'] 
        ?? '0.0.0.0';
}

// ================== অ্যাকশন নেওয়া ==================
$action = $_POST['action'] ?? $_GET['action'] ?? '';

if (empty($action)) {
    respond(['status' => 'error', 'msg' => 'Action দিতে হবে']);
}

$domain = trim($_POST['domain'] ?? $_GET['domain'] ?? '');

// ================== ডোমেইন চেক ==================
function is_domain_authorized($pdo, $domain) {
    if (empty($domain)) return false;
    
    $stmt = $pdo->prepare("SELECT id, status FROM clients WHERE domain = ? LIMIT 1");
    $stmt->execute([$domain]);
    $client = $stmt->fetch(PDO::FETCH_ASSOC);
    
    return $client && $client['status'] === 'active';
}

// ================== সব অ্যাকশন ==================

switch ($action) {

    // --------------------------------------------------
    // ১. কনফিগারেশন পাঠানো
    // --------------------------------------------------
    case 'get_config':
        if (!is_domain_authorized($pdo, $domain)) {
            respond(['status' => 'error', 'msg' => 'Domain Not Authorized']);
        }

        $stmt = $pdo->prepare("SELECT * FROM clients WHERE domain = ? LIMIT 1");
        $stmt->execute([$domain]);
        $client = $stmt->fetch(PDO::FETCH_ASSOC);

        // অ্যাকটিভ গেমস
        $games = [];
        $gameStmt = $pdo->query("SELECT name FROM active_games WHERE status = 1 ORDER BY sort_order ASC");
        while ($row = $gameStmt->fetch(PDO::FETCH_ASSOC)) {
            $games[] = $row['name'];
        }

        respond([
            'status'             => 'success',
            'account_balance'    => (float)$client['balance'],
            'target_ggr_percent' => (float)$client['ggr_percent'],
            'deposit_address'    => $client['deposit_address'] ?: 'TYourUSDTAddressHere',
            'network_name'       => $client['network'] ?: 'TRC20',
            'min_deposit'        => (float)$client['min_deposit'],
            'active_games'       => $games,
            'notice'             => $client['notice'] ?? '',
            'allowed_domain'     => $client['domain']
        ]);
        break;

    // --------------------------------------------------
    // ২. পেমেন্ট রিকোয়েস্ট সাবমিট
    // --------------------------------------------------
    case 'submit_payment':
        if (!is_domain_authorized($pdo, $domain)) {
            respond(['status' => 'error', 'msg' => 'Domain Not Authorized']);
        }

        $amount = floatval($_POST['amount'] ?? 0);
        $hash   = trim($_POST['hash'] ?? '');

        if ($amount <= 0 || empty($hash)) {
            respond(['status' => 'error', 'msg' => 'অ্যামাউন্ট বা হ্যাশ সঠিক নয়']);
        }

        // একই হ্যাশ আগে আছে কিনা চেক
        $check = $pdo->prepare("SELECT id FROM payment_requests WHERE transaction_hash = ? LIMIT 1");
        $check->execute([$hash]);
        if ($check->fetch()) {
            respond(['status' => 'error', 'msg' => 'এই ট্রানজেকশন হ্যাশ আগেই ব্যবহার করা হয়েছে']);
        }

        $stmt = $pdo->prepare("SELECT id, min_deposit FROM clients WHERE domain = ?");
        $stmt->execute([$domain]);
        $client = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($amount < $client['min_deposit']) {
            respond(['status' => 'error', 'msg' => 'মিনিমাম ডিপোজিটের কম অ্যামাউন্ট']);
        }

        $insert = $pdo->prepare("
            INSERT INTO payment_requests 
            (client_id, domain, amount, transaction_hash, status, ip_address, created_at) 
            VALUES (?, ?, ?, ?, 'pending', ?, NOW())
        ");
        $insert->execute([
            $client['id'],
            $domain,
            $amount,
            $hash,
            get_client_ip()
        ]);

        respond([
            'status' => 'success',
            'msg'    => 'পেমেন্ট রিকোয়েস্ট সফলভাবে সাবমিট হয়েছে'
        ]);
        break;

    // --------------------------------------------------
    // ৩. পেমেন্ট স্ট্যাটাস চেক (অটো সিঙ্ক)
    // --------------------------------------------------
    case 'check_payment_status':
        if (!is_domain_authorized($pdo, $domain)) {
            respond(['status' => 'error', 'msg' => 'Domain Not Authorized']);
        }

        $hashes = json_decode($_POST['hashes'] ?? '[]', true);
        if (!is_array($hashes) || empty($hashes)) {
            respond(['status' => 'success', 'updates' => []]);
        }

        $updates = [];
        $placeholders = implode(',', array_fill(0, count($hashes), '?'));

        $stmt = $pdo->prepare("
            SELECT transaction_hash, status 
            FROM payment_requests 
            WHERE domain = ? AND transaction_hash IN ($placeholders)
        ");
        $stmt->execute(array_merge([$domain], $hashes));

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            if (in_array($row['status'], ['approved', 'rejected'])) {
                $updates[$row['transaction_hash']] = $row['status'];
            }
        }

        respond([
            'status'  => 'success',
            'updates' => $updates
        ]);
        break;

    // --------------------------------------------------
    // ৪. গেম লগ সিঙ্ক
    // --------------------------------------------------
    case 'sync_game_logs':
        if (!is_domain_authorized($pdo, $domain)) {
            respond(['status' => 'error', 'msg' => 'Domain Not Authorized']);
        }

        $logs = json_decode($_POST['logs'] ?? '[]', true);
        if (!is_array($logs) || empty($logs)) {
            respond(['status' => 'success', 'msg' => 'কোনো লগ নেই']);
        }

        $stmt = $pdo->prepare("SELECT id FROM clients WHERE domain = ?");
        $stmt->execute([$domain]);
        $client = $stmt->fetch(PDO::FETCH_ASSOC);

        $insert = $pdo->prepare("
            INSERT INTO game_logs 
            (client_id, domain, user_id, game_uid, bet_amount, win_amount, created_at, synced_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
        ");

        $pdo->beginTransaction();
        try {
            foreach ($logs as $log) {
                $insert->execute([
                    $client['id'],
                    $domain,
                    $log['user_id'] ?? 0,
                    $log['game_uid'] ?? '',
                    floatval($log['bet_amount'] ?? 0),
                    floatval($log['win_amount'] ?? 0),
                    $log['created_at'] ?? date('Y-m-d H:i:s')
                ]);
            }
            $pdo->commit();
            respond(['status' => 'success', 'msg' => 'লগ সফলভাবে সিঙ্ক হয়েছে']);
        } catch (Exception $e) {
            $pdo->rollBack();
            respond(['status' => 'error', 'msg' => 'লগ সিঙ্ক করতে ব্যর্থ']);
        }
        break;

    default:
        respond(['status' => 'error', 'msg' => 'অবৈধ Action']);
}