<?php
// shop.php - SUPER VERSION (BAKONG + CRYPTOMUS USDT INTEGRATION)

require_once 'config.php';
require_once __DIR__ . '/vendor/autoload.php';

// ==========================================
// 🛡️ SECURITY CHECK
// ==========================================
$client_token = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '';
if (isset($SECRET_TOKEN) && $client_token !== $SECRET_TOKEN) {
    http_response_code(403);
    die('⛔ Access Denied!');
}

ini_set('display_errors', 0); 
error_reporting(E_ALL);

// ==========================================
// 🗄️ DATABASE CONNECTION & INIT
// ==========================================
function getPDO() {
    global $db_config; 
    $dsn = "mysql:host={$db_config['h']};dbname={$db_config['d']};charset=utf8mb4";
    $opt = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];
    return new PDO($dsn, $db_config['u'], $db_config['p'], $opt);
}

function initDB() {
    try {
        $pdo = getPDO();
        
        $pdo->exec("CREATE TABLE IF NOT EXISTS transactions (
            id INT AUTO_INCREMENT PRIMARY KEY,
            md5 VARCHAR(100) UNIQUE,
            user_id BIGINT,
            pkg_code VARCHAR(20),
            amount DECIMAL(10,2),
            status VARCHAR(20) DEFAULT 'PENDING',
            target_key VARCHAR(100) DEFAULT NULL,
            pay_type VARCHAR(20) DEFAULT 'KHQR',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )");

        $pdo->exec("CREATE TABLE IF NOT EXISTS licenses (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_name VARCHAR(100),
            license_key VARCHAR(100) UNIQUE,
            expiry_date DATE,
            is_active TINYINT(1) DEFAULT 1,
            package_type VARCHAR(20),
            hwid VARCHAR(255) DEFAULT NULL,
            reset_count INT DEFAULT 0,
            last_reset_date DATE DEFAULT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )");
        
        $pdo->exec("CREATE TABLE IF NOT EXISTS used_slips (
            id INT AUTO_INCREMENT PRIMARY KEY,
            file_unique_id VARCHAR(100) UNIQUE,
            user_id BIGINT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )");

        $pdo->exec("CREATE TABLE IF NOT EXISTS user_states (
            user_id BIGINT PRIMARY KEY,
            state VARCHAR(100),
            temp_data TEXT,
            target_key VARCHAR(100) DEFAULT NULL,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )");

        // Add new columns safely if they don't exist
        try { $pdo->exec("ALTER TABLE transactions ADD COLUMN target_key VARCHAR(100) DEFAULT NULL"); } catch(Exception $e){}
        try { $pdo->exec("ALTER TABLE user_states ADD COLUMN target_key VARCHAR(100) DEFAULT NULL"); } catch(Exception $e){}
        try { $pdo->exec("ALTER TABLE transactions ADD COLUMN pay_type VARCHAR(20) DEFAULT 'KHQR'"); } catch(Exception $e){}

    } catch (Exception $e) {}
}
initDB();

// ==========================================
// ==========================================
// 🛒 PRICING CONFIG (PRO 1 ONLY)
// ==========================================
$PACKAGES = [
    // កញ្ចប់ PRO 1
    "1m" => ["name" => "💎 1 Month PRO 1", "price" => "7$", "days" => 30, "limit" => 2, "type" => "PRO"],
    "3m" => ["name" => "🔥 3 Months PRO 1 (+15 Days Free)", "price" => "21$", "days" => 105, "limit" => 8, "type" => "PRO"],
    "6m" => ["name" => "🚀 6 Months PRO 1 (+1 Month Free)", "price" => "42$", "days" => 210, "limit" => 15, "type" => "PRO"],
    "1y" => ["name" => "👑 1 Year PRO 1 (+3 Months Free)", "price" => "84$", "days" => 455, "limit" => 30, "type" => "PRO"]
];

// ==========================================
// 🔧 HELPER FUNCTIONS (API)
// ==========================================
function sendMessage($chat_id, $text, $keyboard = null) {
    global $BOT_TOKEN;
    $url = "https://api.telegram.org/bot$BOT_TOKEN/sendMessage";
    $data = ['chat_id' => $chat_id, 'text' => $text, 'parse_mode' => 'HTML', 'disable_web_page_preview' => true];
    if ($keyboard) $data['reply_markup'] = json_encode($keyboard);
    $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_exec($ch); curl_close($ch);
}

function deleteMessage($chat_id, $message_id) {
    global $BOT_TOKEN;
    $url = "https://api.telegram.org/bot$BOT_TOKEN/deleteMessage";
    $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, ['chat_id' => $chat_id, 'message_id' => $message_id]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_exec($ch); curl_close($ch);
}

function sendPhoto($chat_id, $photo_path, $caption, $keyboard = null) {
    global $BOT_TOKEN;
    $url = "https://api.telegram.org/bot$BOT_TOKEN/sendPhoto";
    
    // កែឲ្យវាស្គាល់ទាំង URL, Local File និង Telegram File ID
    if (filter_var($photo_path, FILTER_VALIDATE_URL) || !file_exists($photo_path)) {
        $data = ['chat_id' => $chat_id, 'photo' => $photo_path, 'caption' => $caption, 'parse_mode' => 'HTML'];
    } else {
        $cfile = new CURLFile(realpath($photo_path));
        $data = ['chat_id' => $chat_id, 'photo' => $cfile, 'caption' => $caption, 'parse_mode' => 'HTML'];
    }
    
    if ($keyboard) $data['reply_markup'] = json_encode($keyboard);
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_exec($ch); 
    curl_close($ch);
}

function answerCallbackQuery($callback_id, $text = null, $alert = false) {
    global $BOT_TOKEN;
    $url = "https://api.telegram.org/bot$BOT_TOKEN/answerCallbackQuery";
    $data = ['callback_query_id' => $callback_id, 'show_alert' => $alert];
    if ($text) $data['text'] = $text;
    $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_exec($ch); curl_close($ch);
}

function getTelegramUserInfo($chat_id) {
    global $BOT_TOKEN;
    $url = "https://api.telegram.org/bot$BOT_TOKEN/getChat?chat_id=$chat_id";
    $response = @file_get_contents($url);
    if ($response) {
        $data = json_decode($response, true);
        if (isset($data['ok']) && $data['ok'] == true) {
            $first_name = $data['result']['first_name'] ?? '';
            $username = isset($data['result']['username']) ? '@' . $data['result']['username'] : '';
            return $username ? "$first_name ($username)" : ($first_name ?: "ID: $chat_id");
        }
    }
    return "ID: $chat_id";
}

// ==========================================
// 🪙 CRYPTOMUS API FUNCTIONS
// ==========================================
function createCryptomusPayment($amount, $order_id) {
    global $CRYPTOMUS_MERCHANT_ID, $CRYPTOMUS_API_KEY;
    
    $payload = [
        'amount' => (string)$amount,
        'currency' => 'USD',
        'order_id' => $order_id,
        'network' => 'tron', // Default to TRC20 for lower fees, user can still change on site
        'url_return' => "@za_farm_support_3337" // ដាក់ Username Bot បងនៅទីនេះ ដើម្បីឱ្យវាលោតមក Telegram វិញ
    ];
    $json_payload = json_encode($payload);
    $sign = md5(base64_encode($json_payload) . $CRYPTOMUS_API_KEY);

    $ch = curl_init('https://api.cryptomus.com/v1/payment');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'merchant: ' . $CRYPTOMUS_MERCHANT_ID,
        'sign: ' . $sign,
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

function checkCryptomusPayment($uuid) {
    global $CRYPTOMUS_MERCHANT_ID, $CRYPTOMUS_API_KEY;
    
    $payload = ['uuid' => $uuid];
    $json_payload = json_encode($payload);
    $sign = md5(base64_encode($json_payload) . $CRYPTOMUS_API_KEY);

    $ch = curl_init('https://api.cryptomus.com/v1/payment/info');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'merchant: ' . $CRYPTOMUS_MERCHANT_ID,
        'sign: ' . $sign,
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

// ==========================================
// 💾 STATE MANAGEMENT & DB BUSINESS LOGIC
// ==========================================
// (រក្សាមុខងារ Database ចាស់ទាំងអស់នៅដដែល - setUserState, generateKey, extendKey, ល។)
function setUserState($user_id, $state) { try { getPDO()->prepare("INSERT INTO user_states (user_id, state) VALUES (?, ?) ON DUPLICATE KEY UPDATE state = ?")->execute([$user_id, $state, $state]); } catch (Exception $e) {} }
function getUserState($user_id) { try { $stmt = getPDO()->prepare("SELECT state FROM user_states WHERE user_id = ?"); $stmt->execute([$user_id]); $row = $stmt->fetch(); return $row ? $row['state'] : null; } catch (Exception $e) { return null; } }
function clearUserState($user_id) { try { getPDO()->prepare("DELETE FROM user_states WHERE user_id = ?")->execute([$user_id]); } catch (Exception $e) {} }
function saveTempSlip($user_id, $file_id) { try { getPDO()->prepare("INSERT INTO user_states (user_id, temp_data) VALUES (?, ?) ON DUPLICATE KEY UPDATE temp_data = ?")->execute([$user_id, $file_id, $file_id]); } catch (Exception $e) {} }
function getTempSlip($user_id) { try { $stmt = getPDO()->prepare("SELECT temp_data FROM user_states WHERE user_id = ?"); $stmt->execute([$user_id]); $row = $stmt->fetch(); return $row ? $row['temp_data'] : null; } catch (Exception $e) { return null; } }
function clearTempSlip($user_id) { try { getPDO()->prepare("UPDATE user_states SET temp_data = NULL WHERE user_id = ?")->execute([$user_id]); } catch (Exception $e) {} }
function setTargetKey($user_id, $key) { try { getPDO()->prepare("UPDATE user_states SET target_key = ? WHERE user_id = ?")->execute([$key, $user_id]); } catch (Exception $e) {} }
function getTargetKey($user_id) { try { $stmt = getPDO()->prepare("SELECT target_key FROM user_states WHERE user_id = ?"); $stmt->execute([$user_id]); $row = $stmt->fetch(); return $row ? $row['target_key'] : null; } catch (Exception $e) { return null; } }

function checkAndSaveSlip($unique_id, $user_id) {
    try {
        $pdo = getPDO();
        $stmt = $pdo->prepare("SELECT id FROM used_slips WHERE file_unique_id = ? LIMIT 1"); $stmt->execute([$unique_id]);
        if ($stmt->fetch()) return false;
        $pdo->prepare("INSERT INTO used_slips (file_unique_id, user_id) VALUES (?, ?)")->execute([$unique_id, $user_id]); return true;
    } catch (Exception $e) { return true; } 
}

function generateKey($pkg_code, $username) {
    global $PACKAGES;
    if (!isset($PACKAGES[$pkg_code])) return [null, null];
    $days = $PACKAGES[$pkg_code]['days'];
    // ចាប់យកប្រភេទ Key (PRO ឬ PREMIUM) ពីកញ្ចប់ដែលបានរើស
    $key_type = isset($PACKAGES[$pkg_code]['type']) ? $PACKAGES[$pkg_code]['type'] : "PRO";
    
    try {
        $pdo = getPDO();
        $parts = []; for ($i = 0; $i < 4; $i++) $parts[] = substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 4);
        // បង្កើត Key ដោយភ្ជាប់ជាមួយប្រភេទ (PRO- ឬ PREMIUM-)
        $key = $key_type . "-" . implode("-", $parts);
        $exp = date('Y-m-d', strtotime("+$days days"));
        $pdo->prepare("INSERT INTO licenses (user_name, license_key, expiry_date, is_active, package_type, reset_count) VALUES (?, ?, ?, 1, ?, 0)")->execute([$username, $key, $exp, $pkg_code]);
        return [$key, $exp];
    } catch (Exception $e) { return [null, null]; }
}

function extendKey($key, $pkg_code, $buyer_info) {
    global $PACKAGES;
    $days = $PACKAGES[$pkg_code]['days'];
    try {
        $pdo = getPDO();
        $stmt = $pdo->prepare("SELECT expiry_date FROM licenses WHERE license_key = ?"); $stmt->execute([$key]);
        $row = $stmt->fetch();
        if (!$row) return [null, null];

        $current_exp = strtotime($row['expiry_date']);
        $now = time();
        $new_exp = ($current_exp < $now) ? date('Y-m-d', strtotime("+$days days")) : date('Y-m-d', strtotime($row['expiry_date'] . " + $days days"));
        
        $pdo->prepare("UPDATE licenses SET expiry_date = ?, hwid = NULL, reset_count = 0, package_type = ?, user_name = ? WHERE license_key = ?")->execute([$new_exp, $pkg_code, $buyer_info, $key]);
        return [$key, $new_exp];
    } catch (Exception $e) { return [null, null]; }
}

function validateKeyForRenew($key) {
    try { $pdo = getPDO(); $stmt = $pdo->prepare("SELECT id FROM licenses WHERE license_key = ?"); $stmt->execute([trim($key)]); return $stmt->fetch() ? true : false; } catch (Exception $e) { return false; }
}

function resetLicenseHWID($license_key) {
    global $PACKAGES;
    try {
        $pdo = getPDO(); $today = date('Y-m-d'); $license_key = trim(strip_tags($license_key));
        $stmt = $pdo->prepare("SELECT * FROM licenses WHERE license_key = ?"); $stmt->execute([$license_key]);
        $license = $stmt->fetch();

        if (!$license) return "❌ <b>មិនត្រឹមត្រូវ!</b>\nរកមិនឃើញ Key នេះទេ។";
        if ($license['is_active'] == 0) return "⛔ <b>BANNED!</b>\nKey របស់អ្នកត្រូវបានបិទដោយ Admin។ សូមទាក់ទងមកយើងខ្ញុំ។";
        if ($license['expiry_date'] < $today) return "⚠️ <b>Expired!</b>\nKey នេះផុតកំណត់ហើយនៅថ្ងៃទី: {$license['expiry_date']}\nសូមចុចពាក្យ '🔋 បន្តថ្ងៃ (Renew)' ដើម្បីប្រើបន្ត។";
        if ($license['last_reset_date'] == $today) return "⏳ <b>រង់ចាំថ្ងៃស្អែក!</b>\nអ្នកបាន Reset ម្ដងរួចហើយថ្ងៃនេះ។";

        $pkg_code = $license['package_type'] ?? '1m';
        $max_limit = $PACKAGES[$pkg_code]['limit'] ?? 2;
        $current_count = $license['reset_count'];

        if ($current_count >= $max_limit) return "🚫 <b>អស់សិទ្ធិ Reset!</b>\nកញ្ចប់នេះ Reset បានត្រឹម $max_limit ដង។";

        $pdo->prepare("UPDATE licenses SET hwid = NULL, reset_count = reset_count + 1, last_reset_date = ? WHERE license_key = ?")->execute([$today, $license_key]);
        $remaining = $max_limit - ($current_count + 1);
        return "✅ <b>Reset ជោគជ័យ!</b>\n🔹 សិទ្ធិនៅសល់: $remaining ដង";
    } catch (Exception $e) { return "❌ Error System: " . $e->getMessage(); }
}

function checkLicenseDetails($license_key) {
    try {
        $pdo = getPDO(); $stmt = $pdo->prepare("SELECT * FROM licenses WHERE license_key = ?"); $stmt->execute([trim($license_key)]);
        $license = $stmt->fetch();
        if (!$license) return "❌ <b>រកមិនឃើញ Key នេះទេ!</b>";
        
        $status = ($license['expiry_date'] >= date('Y-m-d')) ? "✅ Active" : "⚠️ Expired";
        if ($license['is_active'] == 0) $status = "⛔ BANNED (បិទ)";
        $hwid_status = !empty($license['hwid']) ? "🔒 ជាប់ HWID" : "🔓 ទំនេរ";
        
        return "📂 <b>ព័ត៌មាន License</b>\n👤 ម្ចាស់: <b>{$license['user_name']}</b>\n🔑 Key: <code>{$license['license_key']}</code>\n📅 Exp: {$license['expiry_date']}\n🟢 Status: $status\n💻 Device: $hwid_status\n🔄 Resets: {$license['reset_count']}";
    } catch (Exception $e) { return "❌ Error DB."; }
}

function adminResetHWID($key) {
    try {
        $pdo = getPDO(); $stmt = $pdo->prepare("UPDATE licenses SET hwid = NULL WHERE license_key = ?"); $stmt->execute([trim($key)]);
        return $stmt->rowCount() > 0 ? "✅ <b>ជោគជ័យ!</b> Admin បានទម្លាក់ HWID ឱ្យ Key <code>$key</code> នេះរួចរាល់។" : "❌ <b>រកមិនឃើញ Key នេះទេ!</b>";
    } catch (Exception $e) { return "❌ Error: " . $e->getMessage(); }
}

function adminAddDays($key, $days) {
    try {
        $pdo = getPDO(); $stmt = $pdo->prepare("UPDATE licenses SET expiry_date = DATE_ADD(expiry_date, INTERVAL ? DAY) WHERE license_key = ?"); $stmt->execute([(int)$days, trim($key)]);
        return $stmt->rowCount() > 0 ? "✅ <b>ជោគជ័យ!</b> បានថែម $days ថ្ងៃទៅឱ្យ Key <code>$key</code> រួចរាល់។" : "❌ <b>រកមិនឃើញ Key នេះទេ!</b>";
    } catch (Exception $e) { return "❌ Error: " . $e->getMessage(); }
}

function adminToggleLicenseStatus($key) {
    try {
        $pdo = getPDO();
        $stmt = $pdo->prepare("SELECT is_active, user_name FROM licenses WHERE license_key = ?"); $stmt->execute([trim($key)]);
        $license = $stmt->fetch();
        if (!$license) return "❌ <b>រកមិនឃើញ Key នេះទេ!</b>";

        $new_status = $license['is_active'] == 1 ? 0 : 1;
        $status_text = $new_status == 1 ? "🟢 <b>បើកដំណើរការវិញ (Unbanned)</b>" : "⛔ <b>ត្រូវបានបិទ (Banned)</b>";

        $pdo->prepare("UPDATE licenses SET is_active = ? WHERE license_key = ?")->execute([$new_status, trim($key)]);
        return "✅ <b>ការផ្លាស់ប្តូរជោគជ័យ!</b>\n👤 ម្ចាស់: {$license['user_name']}\n🔑 Key: <code>$key</code>\nស្ថានភាពថ្មី: $status_text";
    } catch (Exception $e) { return "❌ Error: " . $e->getMessage(); }
}

// ==========================================
// 🚀 PROCESS TELEGRAM UPDATES
// ==========================================
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (!$update) exit;

$chat_id_check = $update['message']['chat']['id'] ?? ($update['callback_query']['message']['chat']['id'] ?? 0);
global $ADMIN_ID; 

$keyboard_buttons = [
    [['text' => "🛒 ទិញថ្មី (New Key)"], ['text' => "🔋 បន្តថ្ងៃ (Renew Key)"]],
    [['text' => "📂 ឆែក License"], ['text' => "🔄 Reset HWID"]],
    [['text' => "🆘 ជំនួយ (Support)"]]
];
if (isset($ADMIN_ID) && $chat_id_check == $ADMIN_ID) {
    $keyboard_buttons[] = [['text' => "🔑 Create Key (Admin)"], ['text' => "🔄 Admin Reset Key"]];
    $keyboard_buttons[] = [['text' => "➕ ថែមថ្ងៃឲ្យភ្ញៀវ"], ['text' => "🚫 បិទ/បើក Key (Ban/Unban)"]];
}

$main_keyboard = ['keyboard' => $keyboard_buttons, 'resize_keyboard' => true, 'persistent' => true];
$cancel_keyboard = ['keyboard' => [[['text' => "❌ បោះបង់"]]], 'resize_keyboard' => true];

// ==========================================
// HANDLE CALLBACK QUERY
// ==========================================
if (isset($update['callback_query'])) {
    $callback = $update['callback_query']; $chat_id = $callback['message']['chat']['id'];
    $data = $callback['data']; $msg_id = $callback['message']['message_id']; $callback_id = $callback['id'];
    answerCallbackQuery($callback_id);

    // 1. ជ្រើសរើសកញ្ចប់ -> ឱ្យរើស Payment Method
    if (strpos($data, 'buy_') === 0 || strpos($data, 'renewbuy_') === 0) {
        $is_renew = (strpos($data, 'renewbuy_') === 0);
        $code = str_replace($is_renew ? 'renewbuy_' : 'buy_', '', $data);
        
        if (isset($PACKAGES[$code])) {
            $prefix = $is_renew ? 'renew_' : 'new_';
            
            // បើកញ្ចប់ 1 ខែ មិនឱ្យរើស Crypto ទេ លោតទៅ KHQR តែម្តង
            if ($code == '1m') {
                answerCallbackQuery($callback_id, "Processing...");
                $fake_data = "pay_khqr_{$prefix}{$code}";
                $data = $fake_data; // Force it to execute the KHQR block below
            } else {
                // ឱ្យរើស Bank ឬ Crypto
                $keyboard = [
                    'inline_keyboard' => [
                        [['text' => "🏦 បង់តាមធនាគារ (KHQR)", 'callback_data' => "pay_khqr_{$prefix}{$code}"]],
                        [['text' => "🪙 Pay via Crypto (USDT) +$1 Fee", 'callback_data' => "pay_crypto_{$prefix}{$code}"]]
                    ]
                ];
                $title = $is_renew ? "Renew Key" : "New Key";
                sendMessage($chat_id, "🛒 <b>$title: {$PACKAGES[$code]['name']}</b>\n\nសូមជ្រើសរើសវិធីសាស្ត្របង់ប្រាក់ / Please select a payment method:", $keyboard);
                exit; // End execution here, wait for next click
            }
        }
    }

    // 2A. PROCESS KHQR PAYMENT
    if (strpos($data, 'pay_khqr_') === 0) {
        $action_data = str_replace('pay_khqr_', '', $data);
        $is_renew = strpos($action_data, 'renew_') === 0;
        $code = str_replace($is_renew ? 'renew_' : 'new_', '', $action_data);
        
        $pkg = $PACKAGES[$code];
        $target_key = $is_renew ? getTargetKey($chat_id) : null;
        setUserState($chat_id, $is_renew ? "renewing_$code" : "buying_$code");

        global $BAKONG_TOKEN, $BAKONG_ACCOUNT_ID, $BAKONG_MERCHANT_NAME, $BAKONG_CITY;
        try {
            $amount = floatval(str_replace('$', '', $pkg['price']));
            $bakong = new \KHQR\BakongKHQR($BAKONG_TOKEN);
            $info = \KHQR\Models\IndividualInfo::withOptionalArray($BAKONG_ACCOUNT_ID, $BAKONG_MERCHANT_NAME, $BAKONG_CITY,
                ['currency' => \KHQR\Helpers\KHQRData::CURRENCY_USD, 'amount' => $amount, 'expirationTimestamp' => (string)(floor(microtime(true) * 1000) + (15 * 60 * 1000))]
            );
            $res = $bakong->generateIndividual($info);

            if ($res->status['code'] == 0) {
                $qr_md5 = $res->data['md5']; $qr_raw = $res->data['qr'];
                $qr_img = "https://api.qrserver.com/v1/create-qr-code/?size=350x350&data=" . urlencode($qr_raw);

                getPDO()->prepare("INSERT INTO transactions (md5, user_id, pkg_code, amount, status, target_key, pay_type) VALUES (?, ?, ?, ?, 'PENDING', ?, 'KHQR')")
                        ->execute([$qr_md5, $chat_id, $code, $amount, $target_key]);

                $title = $is_renew ? "វិក្កយបត្រ (Renew Key ចាស់)" : "វិក្កយបត្រ (ទិញ Key ថ្មី)";
                $key_text = $is_renew ? "\n🔑 <b>Key:</b> <code>$target_key</code>" : "";

                sendPhoto($chat_id, $qr_img, "🧾 <b>$title</b>\n➖➖➖➖➖➖➖➖\n📦 <b>កញ្ចប់:</b> {$pkg['name']}\n💵 <b>តម្លៃ:</b> {$pkg['price']}$key_text\n⏳ <b>សុពលភាព:</b> 15 នាទី\n\n📲 <b>សូម Scan QR តាម App ធនាគារ</b>\nរួចចុចប៊ូតុង <b>'ខ្ញុំបង់រួចហើយ'</b> ខាងក្រោម។", ['inline_keyboard' => [[['text' => "✅ ខ្ញុំបង់រួចហើយ (Check Pay)", 'callback_data' => "check_pay_$qr_md5"]]]]);
            }
        } catch (Exception $e) {}
    }

    // 2B. PROCESS CRYPTO PAYMENT (BINANCE PAY - MANUAL SLIP)
    elseif (strpos($data, 'pay_crypto_') === 0) {
        $action_data = str_replace('pay_crypto_', '', $data);
        $is_renew = strpos($action_data, 'renew_') === 0;
        $code = str_replace($is_renew ? 'renew_' : 'new_', '', $action_data);
        
        $pkg = $PACKAGES[$code];
        $target_key = $is_renew ? getTargetKey($chat_id) : null;
        
        setUserState($chat_id, $is_renew ? "renewing_$code" : "buying_$code");

        $original_price = floatval(str_replace('$', '', $pkg['price']));
        $ref_note = "ZATOC-" . $chat_id . "-" . rand(100, 999); 

        $title = $is_renew ? "Invoice (Renew Key)" : "Invoice (New Key)";
        $key_text = $is_renew ? "\n🔑 <b>Target Key:</b> <code>$target_key</code>" : "";
        
        $binance_id = "911296542"; // លេខ Binance ID របស់បង
        
        // 🔴 កន្លែងសំខាន់: បងត្រូវយករូប QR Code Binance របស់បង ទៅ Upload ទុកលើ Website ណាមួយ រួចយក Link រូបនោះមកដាក់ត្រង់នេះ
        // ឧទាហរណ៍: "https://zatoctools.com/images/my_binance_qr.jpg"
        $qr_image_url = __DIR__ . "/qr.jpg"; // ទាញយករូប qr.jpg ពីក្នុង Folder ផ្ទាល់
        
        // សារជាភាសាអង់គ្លេស និងមានការណែនាំច្បាស់ៗ
        $msg = "🧾 <b>$title</b>\n➖➖➖➖➖➖➖➖\n📦 <b>Package:</b> {$pkg['name']}\n💵 <b>Amount to Pay:</b> <b>\$$original_price USDT</b>$key_text\n\n🟡 <b>Binance Pay (0% Fee)</b>\n🆔 <b>Binance ID:</b> <code>$binance_id</code>\n📝 <b>Reference Note:</b> <code>$ref_note</code>\n\n⚠️ <b>IMPORTANT INSTRUCTIONS:</b>\n1️⃣ Open your Binance App.\n2️⃣ Scan the QR code above <b>OR</b> send USDT to the Binance ID: <code>$binance_id</code>.\n3️⃣ <b>CRITICAL:</b> You MUST copy the Reference Note (<code>$ref_note</code>) and paste it into the <b>\"Add Note\"</b> field during the transfer.\n\n📸 <b>AFTER PAYMENT:</b>\nPlease take a screenshot of the successful payment receipt and send the photo directly to this bot for Admin approval.";

        $keyboard = [
            'inline_keyboard' => [
                [['text' => "❌ Cancel Order", 'callback_data' => "confirm_slip_no"]]
            ]
        ];
        
        // ប្តូរពី sendMessage ទៅជា sendPhoto វិញ ដើម្បីឲ្យវាផ្ញើរូប QR ព្រមជាមួយអត្ថបទខាងលើ
        sendPhoto($chat_id, $qr_image_url, $msg, $keyboard);
    }

    // 3. CHECK PAYMENT STATUS (BOTH KHQR & CRYPTO)
    elseif (strpos($data, 'check_pay_') === 0) {
        $md5_or_uuid = str_replace('check_pay_', '', $data);
        global $DOWNLOAD_LINK, $GROUP_LINK;

        try {
            $pdo = getPDO(); $stmt = $pdo->prepare("SELECT * FROM transactions WHERE md5 = ?"); $stmt->execute([$md5_or_uuid]);
            $trans = $stmt->fetch();

            if (!$trans) { 
                sendMessage($chat_id, "❌ <b>រកមិនឃើញទិន្នន័យ (Transaction not found).</b>"); 
                exit; 
            }
            if ($trans['status'] == 'PAID') { 
                sendMessage($chat_id, "✅ <b>វិក្កយបត្រនេះបង់ប្រាក់រួចរាល់ហើយ (Already Paid)!</b>"); 
                exit; 
            }

            $is_paid = false;

            // -- Check KHQR via mmotool --
            if ($trans['pay_type'] == 'KHQR') {
                $resp = @file_get_contents('https://mmotool.dev/check_payment.php?md5=' . urlencode($md5_or_uuid));
                $api_data = json_decode($resp, true);
                if (isset($api_data['status']) && $api_data['status'] == 'PAID') {
                    $is_paid = true;
                }
            } 
            // -- Check Crypto via Cryptomus API --
            else if ($trans['pay_type'] == 'CRYPTO') {
                $crypto_info = checkCryptomusPayment($md5_or_uuid);
                if (isset($crypto_info['result']['status'])) {
                    $c_status = $crypto_info['result']['status'];
                    // Status can be 'paid', 'paid_over'
                    if ($c_status === 'paid' || $c_status === 'paid_over') {
                        $is_paid = true;
                    } else if ($c_status === 'wrong_amount' || $c_status === 'wrong_amount_waiting') {
                         sendMessage($chat_id, "⚠️ <b>បញ្ហាការបង់ប្រាក់ (Invalid amount)!</b>\nចំនួនលុយដែលអ្នកបង់មិនត្រឹមត្រូវ សូមទាក់ទង Admin។"); 
                         exit;
                    }
                }
            }

            // -- If Payment is Success --
            if ($is_paid) {
                $pdo->prepare("UPDATE transactions SET status = 'PAID' WHERE md5 = ?")->execute([$md5_or_uuid]);
                
                $code = $trans['pkg_code']; $pkg = $PACKAGES[$code];
                $target_key = $trans['target_key'];
                $buyer_info = getTelegramUserInfo($chat_id);
                $is_crypto = ($trans['pay_type'] == 'CRYPTO');
                
                if ($target_key) { 
                    list($new_key, $expiry) = extendKey($target_key, $code, $buyer_info);
                    $msg = $is_crypto 
                        ? "🎉 <b>Renewal Successful!</b>\n➖➖➖➖➖➖➖➖➖➖\n🔑 <b>YOUR KEY:</b>\n<code>$new_key</code>\n➖➖➖➖➖➖➖➖➖➖\n📅 <b>New Expiry:</b> $expiry\n📦 <b>Package:</b> {$pkg['name']}\n(HWID has been reset automatically)"
                        : "🎉 <b>ការបន្តថ្ងៃ (Renew) ជោគជ័យ!</b>\n➖➖➖➖➖➖➖➖➖➖\n🔑 <b>KEY របស់អ្នក:</b>\n<code>$new_key</code>\n➖➖➖➖➖➖➖➖➖➖\n📅 <b>ថ្ងៃផុតកំណត់ថ្មី:</b> $expiry\n📦 <b>កញ្ចប់:</b> {$pkg['name']}\n(HWID ត្រូវបានទម្លាក់ស្វ័យប្រវត្តិ)";
                } else { 
                    list($new_key, $expiry) = generateKey($code, $buyer_info);
                    $msg = $is_crypto 
                        ? "🎉 <b>Payment Successful!</b>\n➖➖➖➖➖➖➖➖➖➖\n🔑 <b>YOUR NEW KEY:</b>\n<code>$new_key</code>\n➖➖➖➖➖➖➖➖➖➖\n📅 <b>Expiry:</b> $expiry\n📦 <b>Package:</b> {$pkg['name']}\n\n⬇️ <b>Download & Join:</b>\n1️⃣ <a href=\"$DOWNLOAD_LINK\">👉 Download App</a>\n2️⃣ <a href=\"$GROUP_LINK\">👉 Join Group</a>"
                        : "🎉 <b>ការបង់ប្រាក់ជោគជ័យ!</b>\n➖➖➖➖➖➖➖➖➖➖\n🔑 <b>KEY ថ្មីរបស់អ្នក:</b>\n<code>$new_key</code>\n➖➖➖➖➖➖➖➖➖➖\n📅 <b>ផុតកំណត់:</b> $expiry\n📦 <b>កញ្ចប់:</b> {$pkg['name']}\n\n⬇️ <b>Download & Join:</b>\n1️⃣ <a href=\"$DOWNLOAD_LINK\">👉 Download App</a>\n2️⃣ <a href=\"$GROUP_LINK\">👉 Join Group</a>";
                }

                if ($new_key) {
                    sendMessage($chat_id, $msg, $main_keyboard);
                    clearUserState($chat_id); deleteMessage($chat_id, $msg_id);
                    global $ADMIN_ID;
                    $type_str = $target_key ? "[RENEW KEY]" : "[NEW KEY]";
                    $pay_via = $is_crypto ? "🪙 (CRYPTO)" : "🏦 (KHQR)";
                    sendMessage($ADMIN_ID, "💰 <b>ការលក់ថ្មី $type_str $pay_via!</b>\n👤 <b>អតិថិជន:</b> $buyer_info\n🆔 <b>User ID:</b> <code>$chat_id</code>\n📦 <b>កញ្ចប់:</b> {$pkg['name']}\n💵 <b>តម្លៃ:</b> {$trans['amount']}$");
                }
            } else {
                // ប្រសិនបើមិនទាន់ឃើញលុយចូល វាទម្លាក់សារប្រាប់ច្បាស់ៗតែម្តង
                $wait_msg = ($trans['pay_type'] == 'CRYPTO') 
                    ? "⏳ <b>Payment not detected yet!</b>\nBlockchains can take 1-3 minutes. Please wait a moment and click again." 
                    : "⏳ <b>មិនទាន់ទទួលបានការបង់ប្រាក់!</b>\nសូមរង់ចាំបន្តិច រួចចុចម្តងទៀត។";
                sendMessage($chat_id, $wait_msg);
            }
        } catch (Exception $e) { sendMessage($chat_id, "❌ Error: " . $e->getMessage()); }
    }

    // 4. ADMIN APPROVAL SYSTEM (For Manual Slip check)
    elseif (strpos($data, 'yes_') === 0 && $chat_id == $ADMIN_ID) {
        list($action, $cust_id, $code) = explode('_', $data);
        
        // លុបរូបភាពដែលមានប៊ូតុង Approve ហ្នឹងចោលភ្លាមៗ ដើម្បីកុំឲ្យជាប់គាំង
        deleteMessage($chat_id, $msg_id); 
        
        if (isset($PACKAGES[$code])) {
            $pkg = $PACKAGES[$code];
            $target_key = getTargetKey($cust_id);
            $buyer_info = getTelegramUserInfo($cust_id);
            
            if ($target_key) {
                list($new_key, $expiry) = extendKey($target_key, $code, $buyer_info);
                $msg = "🎉 <b>Renewal Successful!</b>\n\n🔑 <b>Your Key:</b> <code>$new_key</code>\n📅 <b>New Expiry:</b> $expiry\n📦 <b>Package:</b> {$pkg['name']}";
            } else { 
                list($new_key, $expiry) = generateKey($code, $buyer_info);
                global $DOWNLOAD_LINK;
                $msg = "🎉 <b>Payment Approved!</b>\n\n🔑 <b>New Key:</b> <code>$new_key</code>\n📅 <b>Expiry:</b> $expiry\n📦 <b>Package:</b> {$pkg['name']}\n\n⬇️ <a href=\"$DOWNLOAD_LINK\">👉 Download App Here</a>";
            }
            
            // ផ្ញើសារប្រាប់ Admin ថាជោគជ័យ
            sendMessage($ADMIN_ID, "✅ <b>បានអនុម័ត និងបង្កើត Key ជោគជ័យ!</b>\nបានផ្ញើទៅឲ្យអតិថិជន: $buyer_info Successful");
            
            // ទម្លាក់ Key ទៅឲ្យភ្ញៀវ
            sendMessage($cust_id, $msg, $main_keyboard);
            
            clearUserState($cust_id); 
            clearTempSlip($cust_id);
        }
    }
    elseif (strpos($data, 'no_') === 0 && $chat_id == $ADMIN_ID) {
        $cust_id = explode('_', $data)[1];
        
        // លុបរូបភាពដែលមានប៊ូតុង Reject ហ្នឹងចោលភ្លាមៗ
        deleteMessage($chat_id, $msg_id);
        
        clearUserState($cust_id); 
        clearTempSlip($cust_id);
        
        sendMessage($ADMIN_ID, "❌ <b>បានបដិសេធ (Rejected) រួចរាល់!</b>"); 
        sendMessage($cust_id, "❌ <b>ការបង់ប្រាក់ត្រូវបានបដិសេធដោយ Admin!</b>\n\nសូមពិនិត្យមើលវិក្កយបត្ររបស់អ្នកឡើងវិញ ឬទាក់ទងមកកាន់ Admin ផ្ទាល់។", $main_keyboard);
    }
    
    elseif ($data == 'confirm_slip_yes') {
        deleteMessage($chat_id, $msg_id);
        $state = getUserState($chat_id); 
        $file_id = getTempSlip($chat_id);

        if ($state && (strpos($state, 'buying_') === 0 || strpos($state, 'renewing_') === 0) && $file_id) {
            $is_renew = strpos($state, 'renewing_') === 0;
            $code = str_replace($is_renew ? 'renewing_' : 'buying_', '', $state);
            $pkg = $PACKAGES[$code];
            
            // ប្តូរឈ្មោះប៊ូតុងឲ្យស្រួលមើល
            $admin_kb = ['inline_keyboard' => [[['text' => "✅ ទទួលយក (Approve)", 'callback_data' => "yes_{$chat_id}_{$code}"], ['text' => "❌ បដិសេធ (Reject)", 'callback_data' => "no_{$chat_id}"]]]];
            
            global $ADMIN_ID;
            $buyer_info = getTelegramUserInfo($chat_id);
            $type_str = $is_renew ? "🔴 RENEW KEY ចាស់" : "🟢 ទិញ KEY ថ្មី";
            
            // សារលោតទៅប្រាប់ Admin
            sendPhoto($ADMIN_ID, $file_id, "⚠️ <b>មានភ្ញៀវវេរលុយចូល ($type_str)</b>\n\n👤 <b>អតិថិជន:</b> $buyer_info\n🆔 <b>User ID:</b> <code>$chat_id</code>\n📦 <b>កញ្ចប់:</b> {$pkg['name']}\n\nសូមឆែកមើល Binance របស់អ្នក។ បើលុយចូលត្រូវ សូមចុច <b>✅ ទទួលយក</b> ខាងក្រោម។", $admin_kb);
            
            sendMessage($chat_id, "✅ <b>រូបភាពបានបញ្ជូនទៅ Admin ជោគជ័យ!</b>\nសូមរង់ចាំការអនុម័តបន្តិច...");
        } else {
             sendMessage($chat_id, "⚠️ <b>មានកំហុសបន្តិច សូមចុច /start ដើម្បីធ្វើការទិញម្តងទៀត!</b>", $main_keyboard);
        }
    }
    elseif ($data == 'confirm_slip_no') {
        deleteMessage($chat_id, $msg_id); 
        clearTempSlip($chat_id); 
        sendMessage($chat_id, "❌ ការទិញត្រូវបានបោះបង់។", $main_keyboard);
    }

    elseif (strpos($data, 'gen_') === 0 && $chat_id == $ADMIN_ID) {
        $code = str_replace('gen_', '', $data);
        if (isset($PACKAGES[$code])) {
            list($new_key, $expiry) = generateKey($code, "Created_By_Admin");
            sendMessage($chat_id, "✅ <b>Key Created:</b>\n<code>$new_key</code>\nExp: $expiry");
        }
    }
}

// ==========================================
// HANDLE MESSAGES
// ==========================================
elseif (isset($update['message'])) {
    $msg = $update['message']; $chat_id = $msg['chat']['id']; $text = isset($msg['text']) ? trim($msg['text']) : '';
    $state = getUserState($chat_id);

    if ($text == '/start' || $text == '❌ បោះបង់') {
        clearUserState($chat_id); sendMessage($chat_id, "👋 <b>សួស្តី!</b>\nសូមជ្រើសរើសសេវាកម្មខាងក្រោម៖", $main_keyboard);
    }
    elseif ($text == '🛒 ទិញថ្មី (New Key)') {
        clearUserState($chat_id); $keyboard = ['inline_keyboard' => []];
        foreach ($PACKAGES as $k => $v) $keyboard['inline_keyboard'][] = [['text' => $v['name'] . " (" . $v['price'] . ")", 'callback_data' => "buy_$k"]];
        sendMessage($chat_id, "🛒 <b>ជ្រើសរើសកញ្ចប់សម្រាប់ Key ថ្មី៖</b>", $keyboard);
    }
    elseif ($text == '🔋 បន្តថ្ងៃ (Renew Key)') {
        setUserState($chat_id, "waiting_for_renew_key_input");
        sendMessage($chat_id, "🔋 <b>បន្តថ្ងៃ ឬ Upgrade (Renew)</b>\nសូមផ្ញើ <b>License Key ចាស់</b> របស់អ្នកមកទីនេះ...", $cancel_keyboard);
    }
    elseif ($text == '🔄 Reset HWID') {
        setUserState($chat_id, "waiting_for_reset_key");
        sendMessage($chat_id, "🔄 <b>Reset Hardware ID</b>\nសូមផ្ញើ <b>License Key</b> របស់អ្នកមកទីនេះ...", $cancel_keyboard);
    }
    elseif ($text == '📂 ឆែក License') {
        setUserState($chat_id, "waiting_for_check_key");
        sendMessage($chat_id, "📂 <b>ឆែក License</b>\nសូមផ្ញើ Key របស់អ្នកមកទីនេះ...", $cancel_keyboard);
    }
    elseif ($text == '🆘 ជំនួយ (Support)') {
        global $SUPPORT_USER; sendMessage($chat_id, "🛠 <b>ទំនាក់ទំនងជំនួយ</b>", ['inline_keyboard' => [[['text' => "💬 Chat Admin", 'url' => "https://t.me/$SUPPORT_USER"]]]]);
    }
    elseif ($text == '🔑 Create Key (Admin)' && $chat_id == $ADMIN_ID) {
        $keyboard = ['inline_keyboard' => []]; foreach ($PACKAGES as $k => $v) $keyboard['inline_keyboard'][] = [['text' => "Create " . $v['name'], 'callback_data' => "gen_$k"]];
        sendMessage($chat_id, "👮‍♂️ <b>Admin Panel3. CHECK PAYMENT STATUS (BOTH KHQR & CRYPTO) (Create Key):</b>", $keyboard);
    }
    elseif ($text == '🔄 Admin Reset Key' && $chat_id == $ADMIN_ID) {
        setUserState($chat_id, "admin_waiting_reset_key"); sendMessage($chat_id, "👮‍♂️ <b>[Admin Reset]</b>\nសូមផ្ញើ Key របស់ភ្ញៀវ...", $cancel_keyboard);
    }
    elseif ($text == '➕ ថែមថ្ងៃឲ្យភ្ញៀវ' && $chat_id == $ADMIN_ID) {
        setUserState($chat_id, "admin_waiting_extend_key"); sendMessage($chat_id, "👮‍♂️ <b>[Admin ថែមថ្ងៃ]</b>\nសូមផ្ញើ <b>Key</b> របស់ភ្ញៀវមកសិន...", $cancel_keyboard);
    }
    elseif ($text == '🚫 បិទ/បើក Key (Ban/Unban)' && $chat_id == $ADMIN_ID) {
        setUserState($chat_id, "admin_waiting_toggle_key"); 
        sendMessage($chat_id, "🚫 <b>[Admin បិទ/បើក Key]</b>\nសូមផ្ញើ <b>Key</b> របស់ភ្ញៀវដែលអ្នកចង់ បិទ (Ban) ឬ បើកវិញ (Unban)...", $cancel_keyboard);
    }

    elseif ($state == "waiting_for_renew_key_input") {
        if ((strpos($text, 'PRO-') === 0 || strpos($text, 'PREMIUM-') === 0) && validateKeyForRenew($text)) {
            setTargetKey($chat_id, $text); $keyboard = ['inline_keyboard' => []];
            foreach ($PACKAGES as $k => $v) $keyboard['inline_keyboard'][] = [['text' => $v['name'] . " (" . $v['price'] . ")", 'callback_data' => "renewbuy_$k"]];
            sendMessage($chat_id, "✅ <b>រកឃើញ Key:</b> <code>$text</code>\n\n🛒 <b>សូមជ្រើសរើសកញ្ចប់ដើម្បីបន្តថ្ងៃ៖</b>", $keyboard);
        } else { sendMessage($chat_id, "⚠️ <b>Key មិនត្រឹមត្រូវ ឬ រកមិនឃើញ!</b>"); }
    }
    elseif ($state == "waiting_for_reset_key") {
        if (strpos($text, 'PRO-') === 0 || strpos($text, 'PREMIUM-') === 0) { sendMessage($chat_id, resetLicenseHWID($text), $main_keyboard); clearUserState($chat_id);
        } else { sendMessage($chat_id, "⚠️ <b>Key មិនត្រឹមត្រូវ!</b>"); }
    }
    elseif ($state == "waiting_for_check_key") {
        if (strpos($text, 'PRO-') === 0 || strpos($text, 'PREMIUM-') === 0) { sendMessage($chat_id, checkLicenseDetails($text), $main_keyboard); clearUserState($chat_id);
        } else { sendMessage($chat_id, "⚠️ <b>Key មិនត្រឹមត្រូវ!</b>"); }
    }
    elseif ($state == "admin_waiting_reset_key" && $chat_id == $ADMIN_ID) {
        sendMessage($chat_id, adminResetHWID($text), $main_keyboard); clearUserState($chat_id);
    }
    elseif ($state == "admin_waiting_extend_key" && $chat_id == $ADMIN_ID) {
        if (validateKeyForRenew($text)) { setTargetKey($chat_id, $text); setUserState($chat_id, "admin_waiting_extend_days"); sendMessage($chat_id, "✅ បានជ្រើសរើស Key: <code>$text</code>\n\n🔢 <b>សូមវាយបញ្ចូលចំនួនថ្ងៃដែលចង់ថែម (ឧទាហរណ៍: 15)៖</b>");
        } else { sendMessage($chat_id, "❌ រកមិនឃើញ Key នេះទេ។"); }
    }
    elseif ($state == "admin_waiting_extend_days" && $chat_id == $ADMIN_ID) {
        $days = (int)$text; if ($days > 0) { $key = getTargetKey($chat_id); sendMessage($chat_id, adminAddDays($key, $days), $main_keyboard); clearUserState($chat_id);
        } else { sendMessage($chat_id, "❌ សូមបញ្ចូលចំនួនថ្ងៃជាតួលេខ (ធំជាង ០)។"); }
    }
    elseif ($state == "admin_waiting_toggle_key" && $chat_id == $ADMIN_ID) {
        if (strpos($text, 'PRO-') === 0 || strpos($text, 'PREMIUM-') === 0) {
            sendMessage($chat_id, adminToggleLicenseStatus($text), $main_keyboard); clearUserState($chat_id);
        } else { sendMessage($chat_id, "⚠️ <b>Key មិនត្រឹមត្រូវ!</b> (ត្រូវផ្តើមដោយ PRO- ឬ PREMIUM-)"); }
    }

    elseif (isset($msg['photo'])) {
        if ($state && (strpos($state, 'buying_') === 0 || strpos($state, 'renewing_') === 0)) {
            $photo_array = end($msg['photo']); $file_id = $photo_array['file_id']; $file_unique_id = $photo_array['file_unique_id'];
            if (!checkAndSaveSlip($file_unique_id, $chat_id)) { sendMessage($chat_id, "⚠️ <b>រូបភាពនេះធ្លាប់ផ្ញើរួចហើយ!</b>"); exit; }
            saveTempSlip($chat_id, $file_id);
            $is_renew = strpos($state, 'renewing_') === 0; $code = str_replace($is_renew ? 'renewing_' : 'buying_', '', $state); $pkg = $PACKAGES[$code];
            
            $confirm_kb = ['inline_keyboard' => [[['text' => "✅ ត្រឹមត្រូវ (ផ្ញើទៅ Admin)", 'callback_data' => "confirm_slip_yes"]], [['text' => "❌ មិនត្រឹមត្រូវ (បោះបង់)", 'callback_data' => "confirm_slip_no"]]]];
            global $BOT_TOKEN; $url = "https://api.telegram.org/bot$BOT_TOKEN/sendMessage";
            $data = ['chat_id' => $chat_id, 'text' => "🔎 <b>ពិនិត្យមើលម្ដងទៀត</b>\n\nកញ្ចប់: <b>{$pkg['name']}</b>\nតម្លៃ: <b>{$pkg['price']}</b>\n\nតើត្រឹមត្រូវទេ?", 'parse_mode' => 'HTML', 'reply_to_message_id' => $msg['message_id'], 'reply_markup' => json_encode($confirm_kb)];
            $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_exec($ch); curl_close($ch);
        }
    }
}
?>