<?php
/*
 * WhatsApp Webhook Handler for MikhMon
 * Handle incoming WhatsApp messages for voucher purchase
 */

session_start();
error_reporting(0);

// Load required files
include('../include/config.php');
include('../include/whatsapp_config.php');
include('../lib/routeros_api.class.php');
include('../lib/formatbytesbites.php');

// Load database config if available (for admin check)
if (file_exists('../include/db_config.php')) {
    include('../include/db_config.php');
}

// IMPORTANT: Save session config before overwriting $data
// $data from config.php contains MikroTik session configuration
if (!isset($data) || !is_array($data)) {
    // Log error if config not loaded
    error_log("WhatsApp Webhook: config.php tidak ter-load dengan benar");
}
$sessionConfig = isset($data) ? $data : array(); // Save session config to separate variable

// Get webhook data
$input = file_get_contents('php://input');
$webhookData = json_decode($input, true);

// Log incoming webhook
logWebhook($input);

// Process webhook based on gateway
$gateway = WHATSAPP_GATEWAY;

switch ($gateway) {
    case 'fonnte':
        processWebhookFonnte($webhookData);
        break;
    case 'wablas':
        processWebhookWablas($webhookData);
        break;
    case 'woowa':
        processWebhookWoowa($webhookData);
        break;
    case 'mpwa':
        processWebhookMPWA($webhookData);
        break;
    default:
        processWebhookCustom($webhookData);
        break;
}

/**
 * Process Fonnte webhook
 */
function processWebhookFonnte($data) {
    if (!isset($data['message']) || !isset($data['sender'])) {
        return;
    }
    
    $phone = $data['sender'];
    $message = strtolower(trim($data['message']));
    
    processCommand($phone, $message);
}

/**
 * Process Wablas webhook
 */
function processWebhookWablas($data) {
    if (!isset($data['message']) || !isset($data['phone'])) {
        return;
    }
    
    $phone = $data['phone'];
    $message = strtolower(trim($data['message']));
    
    processCommand($phone, $message);
}

/**
 * Process WooWA webhook
 */
function processWebhookWoowa($data) {
    if (!isset($data['message']) || !isset($data['from'])) {
        return;
    }
    
    $phone = $data['from'];
    $message = strtolower(trim($data['message']));
    
    processCommand($phone, $message);
}

/**
 * Process MPWA webhook
 */
function processWebhookMPWA($data) {
    // MPWA webhook format: sender, message, device
    if (!isset($data['message']) || !isset($data['sender'])) {
        return;
    }
    
    $phone = $data['sender'];
    $message = strtolower(trim($data['message']));
    
    processCommand($phone, $message);
}

/**
 * Process Custom webhook
 */
function processWebhookCustom($data) {
    // Sesuaikan dengan format webhook gateway Anda
    if (!isset($data['message']) || !isset($data['phone'])) {
        return;
    }
    
    $phone = $data['phone'];
    $message = strtolower(trim($data['message']));
    
    processCommand($phone, $message);
}

/**
 * Load payment settings from database
 */
function loadPaymentSettings() {
    static $paymentSettings = null;
    
    if ($paymentSettings !== null) {
        return $paymentSettings;
    }
    
    $paymentSettings = [
        'bank_name' => 'BCA',
        'account_number' => '1234567890',
        'account_name' => 'Nama Pemilik',
        'wa_confirm' => '08123456789'
    ];
    
    if (function_exists('getDBConnection')) {
        try {
            $db = getDBConnection();
            if ($db) {
                $stmt = $db->query("SELECT setting_key, setting_value FROM agent_settings WHERE setting_key LIKE 'payment_%'");
                while ($row = $stmt->fetch()) {
                    $key = str_replace('payment_', '', $row['setting_key']);
                    switch ($key) {
                        case 'bank_name':
                            $paymentSettings['bank_name'] = $row['setting_value'];
                            break;
                        case 'account_number':
                            $paymentSettings['account_number'] = $row['setting_value'];
                            break;
                        case 'account_name':
                            $paymentSettings['account_name'] = $row['setting_value'];
                            break;
                        case 'wa_confirm':
                            $paymentSettings['wa_confirm'] = $row['setting_value'];
                            break;
                    }
                    
                    // Also handle full key names (backward compatibility)
                    if ($row['setting_key'] == 'payment_bank_name') {
                        $paymentSettings['bank_name'] = $row['setting_value'];
                    } elseif ($row['setting_key'] == 'payment_account_number') {
                        $paymentSettings['account_number'] = $row['setting_value'];
                    } elseif ($row['setting_key'] == 'payment_account_name') {
                        $paymentSettings['account_name'] = $row['setting_value'];
                    } elseif ($row['setting_key'] == 'payment_wa_confirm') {
                        $paymentSettings['wa_confirm'] = $row['setting_value'];
                    }
                }
            }
        } catch (Exception $e) {
            error_log("Error loading payment settings: " . $e->getMessage());
        }
    }
    
    return $paymentSettings;
}

/**
 * Process incoming command
 * Only responds to valid commands, ignores invalid ones
 */
function processCommand($phone, $message) {
    $messageTrimmed = trim($message);
    $messageLower = strtolower($messageTrimmed);
    
    // Command: VOUCHER [USERNAME] <PROFILE> [NOMER] - Username dan Password SAMA
    // Example: VOUCHER 3K, VOUCHER 1JAM, VOUCHER 3K 08123456789
    // Example with manual username: VOUCHER user123 3K, VOUCHER user123 3K 08123456789
    if (strpos($messageLower, 'voucher ') === 0) {
        $rest = trim(str_replace('voucher ', '', $messageLower));
        // Parse: bisa "3K", "3K 08123456789", "user123 3K", atau "user123 3K 08123456789"
        $parts = preg_split('/\s+/', $rest);
        
        $username = null;
        $profile = null;
        $customerPhone = null;
        
        if (count($parts) == 1) {
            // Format: VOUCHER 3K
            $profile = $parts[0];
        } elseif (count($parts) == 2) {
            // Format: VOUCHER 3K 08123456789 atau VOUCHER user123 3K
            // Check if second part is a phone number (starts with 0 or 62)
            if (preg_match('/^[062]/', $parts[1])) {
                // Format: VOUCHER 3K 08123456789
                $profile = $parts[0];
                $customerPhone = $parts[1];
            } else {
                // Format: VOUCHER user123 3K
                $username = $parts[0];
                $profile = $parts[1];
            }
        } elseif (count($parts) == 3) {
            // Format: VOUCHER user123 3K 08123456789
            $username = $parts[0];
            $profile = $parts[1];
            $customerPhone = $parts[2];
        }
        
        if (!empty($profile)) {
            purchaseVoucher($phone, $profile, 'voucher', $customerPhone, $username); // Mode: username = password
        }
        return; // Valid command processed
    }
    // Command: VCR [USERNAME] <PROFILE> [NOMER] - Alias untuk VOUCHER
    // Example: VCR 3K, VCR user123 3K 08123456789
    elseif (strpos($messageLower, 'vcr ') === 0) {
        $rest = trim(str_replace('vcr ', '', $messageLower));
        $parts = preg_split('/\s+/', $rest);
        
        $username = null;
        $profile = null;
        $customerPhone = null;
        
        if (count($parts) == 1) {
            $profile = $parts[0];
        } elseif (count($parts) == 2) {
            if (preg_match('/^[062]/', $parts[1])) {
                $profile = $parts[0];
                $customerPhone = $parts[1];
            } else {
                $username = $parts[0];
                $profile = $parts[1];
            }
        } elseif (count($parts) == 3) {
            $username = $parts[0];
            $profile = $parts[1];
            $customerPhone = $parts[2];
        }
        
        if (!empty($profile)) {
            purchaseVoucher($phone, $profile, 'voucher', $customerPhone, $username);
        }
        return;
    }
    // Command: GENERATE [USERNAME] <PROFILE> [NOMER] - Alias untuk VOUCHER
    // Example: GENERATE 3K, GENERATE user123 3K 08123456789
    elseif (strpos($messageLower, 'generate ') === 0) {
        $rest = trim(str_replace('generate ', '', $messageLower));
        $parts = preg_split('/\s+/', $rest);
        
        $username = null;
        $profile = null;
        $customerPhone = null;
        
        if (count($parts) == 1) {
            $profile = $parts[0];
        } elseif (count($parts) == 2) {
            if (preg_match('/^[062]/', $parts[1])) {
                $profile = $parts[0];
                $customerPhone = $parts[1];
            } else {
                $username = $parts[0];
                $profile = $parts[1];
            }
        } elseif (count($parts) == 3) {
            $username = $parts[0];
            $profile = $parts[1];
            $customerPhone = $parts[2];
        }
        
        if (!empty($profile)) {
            purchaseVoucher($phone, $profile, 'voucher', $customerPhone, $username);
        }
        return;
    }
    // Command: MEMBER <PROFILE> - Username dan Password BEDA
    // Example: MEMBER 3K, MEMBER 1JAM
    elseif (strpos($messageLower, 'member ') === 0) {
        $profile = trim(str_replace('member ', '', $messageLower));
        if (!empty($profile)) {
            purchaseVoucher($phone, $profile, 'member'); // Mode: username ≠ password
        }
        return; // Valid command processed
    }
    // Command: BELI <PROFILE> - Default (menggunakan setting voucher)
    // Example: BELI 1JAM, BELI 3JAM, BELI 1HARI
    elseif (strpos($messageLower, 'beli ') === 0) {
        $profile = trim(str_replace('beli ', '', $messageLower));
        if (!empty($profile)) {
            purchaseVoucher($phone, $profile, 'default'); // Mode: default dari settings
        }
        return; // Valid command processed
    }
    // Command: HARGA or PAKET or LIST
    elseif (in_array($messageLower, ['harga', 'paket', 'list'])) {
        sendPriceList($phone);
        return; // Valid command processed
    }
    // Command: HELP or BANTUAN
    elseif (in_array($messageLower, ['help', 'bantuan'])) {
        sendHelp($phone);
        return; // Valid command processed
    }
    
    // Admin-only commands - Check if admin first
    if (isAdminNumber($phone)) {
        // Command: TAMBAH username password profile - Tambah PPPoE Secret
        // Example: TAMBAH user123 pass123 profile1
        if (strpos($messageLower, 'tambah ') === 0) {
            $rest = trim(str_replace('tambah ', '', $messageLower));
            $parts = preg_split('/\s+/', $rest, 3);
            
            if (count($parts) >= 3) {
                $username = $parts[0];
                $password = $parts[1];
                $profile = $parts[2];
                addPPPoESecret($phone, $username, $password, $profile);
            } else {
                sendWhatsAppMessage($phone, "❌ *FORMAT SALAH*\n\nFormat: TAMBAH <username> <password> <profile>\nContoh: TAMBAH user123 pass123 profile1");
            }
            return;
        }
        // Command: EDIT username profile_baru - Edit PPPoE Secret Profile
        // Example: EDIT user123 profile2
        elseif (strpos($messageLower, 'edit ') === 0) {
            $rest = trim(str_replace('edit ', '', $messageLower));
            $parts = preg_split('/\s+/', $rest, 2);
            
            if (count($parts) == 2) {
                $username = $parts[0];
                $newProfile = $parts[1];
                editPPPoESecret($phone, $username, $newProfile);
            } else {
                sendWhatsAppMessage($phone, "❌ *FORMAT SALAH*\n\nFormat: EDIT <username> <profile_baru>\nContoh: EDIT user123 profile2");
            }
            return;
        }
        // Command: HAPUS username - Hapus PPPoE Secret
        // Example: HAPUS user123
        elseif (strpos($messageLower, 'hapus ') === 0) {
            $rest = trim(str_replace('hapus ', '', $messageLower));
            $username = trim($rest);
            
            if (!empty($username)) {
                deletePPPoESecret($phone, $username);
            } else {
                sendWhatsAppMessage($phone, "❌ *FORMAT SALAH*\n\nFormat: HAPUS <username>\nContoh: HAPUS user123");
            }
            return;
        }
        // Command: PING - Test koneksi ke MikroTik
        elseif (in_array($messageLower, ['ping', 'cek ping'])) {
            checkMikroTikPing($phone);
            return;
        }
        // Command: STATUS or CEK - Cek status MikroTik
        elseif (in_array($messageLower, ['status', 'cek', 'cek status'])) {
            checkMikroTikStatus($phone);
            return;
        }
        // Command: PPPOE or PPP - Cek PPPoE aktif
        elseif (in_array($messageLower, ['pppoe', 'ppp', 'pppoe aktif', 'ppp aktif'])) {
            checkPPPoEActive($phone);
            return;
        }
        // Command: RESOURCE or RES - Cek resource MikroTik
        elseif (in_array($messageLower, ['resource', 'res', 'resource mikrotik'])) {
            checkMikroTikResource($phone);
            return;
        }
        // Command: DISABLE PPPOE username - Disable PPPoE Secret
        // Example: DISABLE PPPOE user123
        elseif (strpos($messageLower, 'disable pppoe ') === 0 || strpos($messageLower, 'disable ppp ') === 0) {
            $rest = trim(str_replace(['disable pppoe ', 'disable ppp '], '', $messageLower));
            $username = trim($rest);
            
            if (!empty($username)) {
                disablePPPoESecret($phone, $username);
            } else {
                sendWhatsAppMessage($phone, "❌ *FORMAT SALAH*\n\nFormat: DISABLE PPPOE <username>\nContoh: DISABLE PPPOE user123");
            }
            return;
        }
        // Command: DISABLE HOTSPOT username - Disable Hotspot User
        // Example: DISABLE HOTSPOT user123
        elseif (strpos($messageLower, 'disable hotspot ') === 0) {
            $rest = trim(str_replace('disable hotspot ', '', $messageLower));
            $username = trim($rest);
            
            if (!empty($username)) {
                disableHotspotUser($phone, $username);
            } else {
                sendWhatsAppMessage($phone, "❌ *FORMAT SALAH*\n\nFormat: DISABLE HOTSPOT <username>\nContoh: DISABLE HOTSPOT user123");
            }
            return;
        }
        // Command: ENABLE PPPOE username - Enable PPPoE Secret
        // Example: ENABLE PPPOE user123
        elseif (strpos($messageLower, 'enable pppoe ') === 0 || strpos($messageLower, 'enable ppp ') === 0) {
            $rest = trim(str_replace(['enable pppoe ', 'enable ppp '], '', $messageLower));
            $username = trim($rest);
            
            if (!empty($username)) {
                enablePPPoESecret($phone, $username);
            } else {
                sendWhatsAppMessage($phone, "❌ *FORMAT SALAH*\n\nFormat: ENABLE PPPOE <username>\nContoh: ENABLE PPPOE user123");
            }
            return;
        }
        // Command: ENABLE HOTSPOT username - Enable Hotspot User
        // Example: ENABLE HOTSPOT user123
        elseif (strpos($messageLower, 'enable hotspot ') === 0) {
            $rest = trim(str_replace('enable hotspot ', '', $messageLower));
            $username = trim($rest);
            
            if (!empty($username)) {
                enableHotspotUser($phone, $username);
            } else {
                sendWhatsAppMessage($phone, "❌ *FORMAT SALAH*\n\nFormat: ENABLE HOTSPOT <username>\nContoh: ENABLE HOTSPOT user123");
            }
            return;
        }
        // Command: PPPOE OFFLINE or PPP OFFLINE - Cek PPPoE yang offline
        // Example: PPPOE OFFLINE, PPP OFFLINE
        elseif (in_array($messageLower, ['pppoe offline', 'ppp offline', 'pppoe mati', 'ppp mati'])) {
            checkPPPoEOffline($phone);
            return;
        }
    }
    
    // Invalid command - ignore (no response sent)
    // Log for monitoring purposes only
    error_log("WhatsApp Webhook: Invalid command ignored from {$phone}: {$messageTrimmed}");
}

/**
 * Check if admin number
 */
function isAdminNumber($phone) {
    // Check if db_config exists
    if (!function_exists('getDBConnection')) {
        return false;
    }
    
    try {
        $db = getDBConnection();
        if (!$db) {
            return false;
        }
        
        $stmt = $db->query("SELECT setting_value FROM agent_settings WHERE setting_key = 'admin_whatsapp_numbers'");
        $result = $stmt->fetch();
        
        if ($result) {
            $adminNumbers = explode(',', $result['setting_value']);
            $adminNumbers = array_map('trim', $adminNumbers);
            return in_array($phone, $adminNumbers);
        }
    } catch (Exception $e) {
        // Log error but don't break
        error_log("Error checking admin number: " . $e->getMessage());
    }
    
    return false;
}

/**
 * Purchase voucher
 * @param string $phone Nomor WhatsApp (agent/admin)
 * @param string $profileName Nama profile MikroTik
 * @param string $mode 'voucher' (username=password), 'member' (username≠password), 'default' (dari settings)
 * @param string|null $customerPhone Nomor WhatsApp pembeli (opsional)
 * @param string|null $manualUsername Username manual/kustom (opsional, jika tidak diisi akan di-generate otomatis)
 */
function purchaseVoucher($phone, $profileName, $mode = 'default', $customerPhone = null, $manualUsername = null) {
    global $sessionConfig;
    
    // Use session config instead of overwritten $data
    $data = $sessionConfig;
    
    // Validate session config is loaded
    if (empty($data) || !is_array($data)) {
        $errorMsg = "❌ *SISTEM ERROR*\n\n";
        $errorMsg .= "Konfigurasi session tidak ter-load.\n";
        $errorMsg .= "Silakan hubungi admin.";
        sendWhatsAppMessage($phone, $errorMsg);
        
        logWebhookError($phone, "BELI $profileName", "Session config tidak ter-load. sessionConfig is empty or not array");
        return;
    }
    
    // Check if admin
    $isAdmin = isAdminNumber($phone);
    
    // Get first session (you can modify this to use specific session)
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        $errorMsg = "❌ *SISTEM ERROR*\n\n";
        $errorMsg .= "Session MikroTik tidak ditemukan.\n";
        $errorMsg .= "Silakan hubungi admin atau coba lagi nanti.";
        sendWhatsAppMessage($phone, $errorMsg);
        
        // Log error with details
        $availableSessions = is_array($data) ? implode(", ", array_keys($data)) : "Tidak ada data";
        $dataCount = is_array($data) ? count($data) : 0;
        logWebhookError($phone, "BELI $profileName", "Session MikroTik tidak ditemukan. Available sessions: $availableSessions, Count: $dataCount");
        return;
    }
    
    // Validate session data exists
    if (!isset($data[$session]) || !is_array($data[$session])) {
        $errorMsg = "❌ *SISTEM ERROR*\n\n";
        $errorMsg .= "Data session tidak ditemukan.\n";
        $errorMsg .= "Silakan hubungi admin.";
        sendWhatsAppMessage($phone, $errorMsg);
        
        logWebhookError($phone, "BELI $profileName", "Data session tidak ditemukan. Session: $session");
        return;
    }
    
    // Load session config with validation
    $iphost = '';
    $userhost = '';
    $passwdhost = '';
    $hotspotname = '';
    $dnsname = '';
    $currency = 'Rp';
    
    $errors = [];
    
    // Check and extract IP (required)
    if (isset($data[$session][1]) && !empty($data[$session][1])) {
        $parts = explode('!', $data[$session][1]);
        if (isset($parts[1])) {
            $iphost = $parts[1];
        } else {
            $errors[] = "IP tidak ditemukan";
        }
    } else {
        $errors[] = "Field [1] IP kosong";
    }
    
    // Check and extract User (required)
    if (isset($data[$session][2]) && !empty($data[$session][2])) {
        $parts = explode('@|@', $data[$session][2]);
        if (isset($parts[1])) {
            $userhost = $parts[1];
        } else {
            $errors[] = "User tidak ditemukan";
        }
    } else {
        $errors[] = "Field [2] User kosong";
    }
    
    // Check and extract Password (required)
    if (isset($data[$session][3]) && !empty($data[$session][3])) {
        $parts = explode('#|#', $data[$session][3]);
        if (isset($parts[1])) {
            $passwdhost = $parts[1];
        } else {
            $errors[] = "Password tidak ditemukan";
        }
    } else {
        $errors[] = "Field [3] Password kosong";
    }
    
    // Check and extract Hotspot Name (required)
    if (isset($data[$session][4]) && !empty($data[$session][4])) {
        $parts = explode('%', $data[$session][4]);
        if (isset($parts[1])) {
            $hotspotname = $parts[1];
        } else {
            $hotspotname = $session; // Fallback to session name
        }
    } else {
        $hotspotname = $session; // Fallback to session name
    }
    
    // Check and extract DNS Name (required)
    if (isset($data[$session][5]) && !empty($data[$session][5])) {
        $parts = explode('^', $data[$session][5]);
        if (isset($parts[1])) {
            $dnsname = $parts[1];
        } else {
            $dnsname = $iphost; // Fallback to IP
        }
    } else {
        $dnsname = $iphost; // Fallback to IP
    }
    
    // Check and extract Currency (optional, default Rp)
    if (isset($data[$session][6]) && !empty($data[$session][6])) {
        $parts = explode('&', $data[$session][6]);
        if (isset($parts[1])) {
            $currency = $parts[1];
        }
    }
    
    // Check if required fields are missing
    if (empty($iphost) || empty($userhost) || empty($passwdhost)) {
        $errorMsg = "❌ *KONFIGURASI SESSION TIDAK LENGKAP*\n\n";
        $errorMsg .= "Field yang hilang:\n";
        foreach ($errors as $error) {
            $errorMsg .= "• $error\n";
        }
        $errorMsg .= "\nSilakan hubungi admin untuk memperbaiki konfigurasi session.";
        
        sendWhatsAppMessage($phone, $errorMsg);
        
        $errorDetails = "Session: $session, Errors: " . implode(", ", $errors);
        $errorDetails .= " | Data count: " . count($data[$session]);
        $errorDetails .= " | Available keys: " . implode(", ", array_keys($data[$session]));
        logWebhookError($phone, "BELI $profileName", $errorDetails);
        return;
    }
    
    // Connect to MikroTik
    $API = new RouterosAPI();
    $API->debug = false;
    
    $connectResult = $API->connect($iphost, $userhost, decrypt($passwdhost));
    
    if (!$connectResult) {
        $errorMsg = "❌ *GAGAL TERHUBUNG KE SERVER*\n\n";
        $errorMsg .= "Tidak dapat terhubung ke MikroTik.\n";
        $errorMsg .= "Kemungkinan penyebab:\n";
        $errorMsg .= "• MikroTik sedang offline\n";
        $errorMsg .= "• Koneksi jaringan bermasalah\n";
        $errorMsg .= "• IP/User/Password salah\n\n";
        $errorMsg .= "Silakan hubungi admin untuk bantuan.";
        
        sendWhatsAppMessage($phone, $errorMsg);
        
        // Log error with details
        logWebhookError($phone, "BELI $profileName", "Gagal connect ke MikroTik: IP=$iphost, User=$userhost");
        return;
    }
    
    // Get profile
    $getprofile = $API->comm("/ip/hotspot/user/profile/print", array("?name" => $profileName));
    
    if (empty($getprofile)) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "Paket *$profileName* tidak ditemukan.\nKetik *HARGA* untuk melihat daftar paket.");
        return;
    }
    
    $profile = $getprofile[0];
    $ponlogin = $profile['on-login'];
    $validity = explode(",", $ponlogin)[3];
    $price = explode(",", $ponlogin)[2];
    $sprice = explode(",", $ponlogin)[4];
    
    // Generate username and password berdasarkan mode
    $username = '';
    $password = '';
    $comment = '';
    
    // Check if manual username is provided
    if (!empty($manualUsername)) {
        // Use manual username
        $username = trim($manualUsername);
        // Validate username (only alphanumeric, underscore, dash)
        $username = preg_replace('/[^a-zA-Z0-9_-]/', '', $username);
        
        if (empty($username)) {
            sendWhatsAppMessage($phone, "❌ *USERNAME TIDAK VALID*\n\nUsername hanya boleh mengandung huruf, angka, underscore (_), dan dash (-).");
            $API->disconnect();
            return;
        }
        
        // Generate password based on mode
        if ($mode == 'voucher') {
            // Mode VOUCHER: password = username
            $password = $username;
            $comment = "VOUCHER-MANUAL-" . substr($phone, -4) . "-" . date("dmy");
        } elseif ($mode == 'member') {
            // Mode MEMBER: generate password
            if (file_exists('../lib/VoucherGenerator.class.php')) {
                include_once('../lib/VoucherGenerator.class.php');
                $voucherGen = new VoucherGenerator();
                $password = $voucherGen->generatePassword();
            } else {
                $password = randNULC(6);
            }
            $comment = "MEMBER-MANUAL-" . substr($phone, -4) . "-" . date("dmy");
        } else {
            // Mode DEFAULT: generate password
            if (file_exists('../lib/VoucherGenerator.class.php')) {
                include_once('../lib/VoucherGenerator.class.php');
                $voucherGen = new VoucherGenerator();
                $password = $voucherGen->generatePassword();
            } else {
                $password = randNULC(6);
            }
            $comment = "WA-MANUAL-" . substr($phone, -4) . "-" . date("dmy");
        }
    } else {
        // Auto-generate username and password
        // Load VoucherGenerator if available
        if (file_exists('../lib/VoucherGenerator.class.php')) {
            include_once('../lib/VoucherGenerator.class.php');
            $voucherGen = new VoucherGenerator();
            
            // Override settings berdasarkan mode
            if ($mode == 'voucher') {
                // Mode VOUCHER: username = password
                $username = $voucherGen->generateUsername();
                $password = $username; // Password sama dengan username
                $comment = "VOUCHER-" . substr($phone, -4) . "-" . date("dmy");
            } elseif ($mode == 'member') {
                // Mode MEMBER: username ≠ password
                $username = $voucherGen->generateUsername();
                $password = $voucherGen->generatePassword(); // Password berbeda
                $comment = "MEMBER-" . substr($phone, -4) . "-" . date("dmy");
            } else {
                // Mode DEFAULT: gunakan settings dari database
                $voucher = $voucherGen->generateVoucher();
                $username = $voucher['username'];
                $password = $voucher['password'];
                $comment = "WA-" . substr($phone, -4) . "-" . date("dmy");
            }
        } else {
            // Fallback jika VoucherGenerator tidak ada
            if ($mode == 'voucher') {
                $username = strtolower($profileName) . randNULC(6);
                $password = $username; // Password sama dengan username
                $comment = "VOUCHER-" . substr($phone, -4) . "-" . date("dmy");
            } elseif ($mode == 'member') {
                $username = strtolower($profileName) . randNULC(6);
                $password = randNULC(6); // Password berbeda
                $comment = "MEMBER-" . substr($phone, -4) . "-" . date("dmy");
            } else {
                $username = strtolower($profileName) . randNULC(6);
                $password = randNULC(6);
                $comment = "WA-" . substr($phone, -4) . "-" . date("dmy");
            }
        }
    }
    
    // Check if username already exists (only for manual username)
    if (!empty($manualUsername)) {
        $checkUser = $API->comm("/ip/hotspot/user/print", array("?name" => $username));
        if (!empty($checkUser)) {
            $errorMsg = "❌ *USERNAME SUDAH TERDAFTAR*\n\n";
            $errorMsg .= "Username *$username* sudah digunakan.\n";
            $errorMsg .= "Silakan gunakan username lain.";
            sendWhatsAppMessage($phone, $errorMsg);
            $API->disconnect();
            return;
        }
    }
    
    // Add user to MikroTik
    $API->comm("/ip/hotspot/user/add", array(
        "server" => "all",
        "name" => $username,
        "password" => $password,
        "profile" => $profileName,
        "comment" => $comment,
    ));
    
    $API->disconnect();
    
    // Format price
    if (strpos($currency, 'Rp') !== false || strpos($currency, 'IDR') !== false) {
        $priceFormatted = $currency . " " . number_format((float)$sprice, 0, ",", ".");
    } else {
        $priceFormatted = $currency . " " . number_format((float)$sprice, 2);
    }
    
    // Send voucher to customer
    $voucherData = [
        'hotspot_name' => $hotspotname,
        'profile' => $profileName,
        'username' => $username,
        'password' => $password,
        'timelimit' => $profile['session-timeout'],
        'datalimit' => '',
        'validity' => $validity,
        'price' => $priceFormatted,
        'login_url' => "http://$dnsname/login?username=$username&password=$password",
        'comment' => $comment
    ];
    
    // Format and send voucher message directly (more reliable)
    $voucherMsg = "🎫 *VOUCHER ANDA*\n\n";
    $voucherMsg .= "━━━━━━━━━━━━━━━━━━━━\n\n";
    $voucherMsg .= "Hotspot: *$hotspotname*\n";
    $voucherMsg .= "Profile: *$profileName*\n\n";
    $voucherMsg .= "Username: `$username`\n";
    $voucherMsg .= "Password: `$password`\n\n";
    
    if (!empty($profile['session-timeout'])) {
        $voucherMsg .= "Time Limit: " . $profile['session-timeout'] . "\n";
    }
    if (!empty($validity)) {
        $voucherMsg .= "Validity: $validity\n";
    }
    if (!empty($priceFormatted)) {
        $voucherMsg .= "Harga: $priceFormatted\n";
    }
    
    $voucherMsg .= "\nLogin URL:\n";
    $voucherMsg .= "http://$dnsname/login?username=$username&password=$password\n\n";
    $voucherMsg .= "━━━━━━━━━━━━━━━━━━━━\n";
    $voucherMsg .= "_Terima kasih telah menggunakan layanan kami_";
    
    // Determine recipient phones
    $recipientPhones = [];
    
    // Always send to agent (the one who made the command)
    $recipientPhones[] = $phone;
    
    // If customer phone is provided, also send to customer
    if (!empty($customerPhone)) {
        // Normalize customer phone number (formatWhatsAppNumber will be called in sendWhatsAppMessage)
        $customerPhone = preg_replace('/[^0-9]/', '', $customerPhone);
        if (!empty($customerPhone)) {
            $recipientPhones[] = $customerPhone;
        }
    }
    
    // Send voucher to all recipients
    foreach ($recipientPhones as $recipientPhone) {
        $voucherResult = sendWhatsAppMessage($recipientPhone, $voucherMsg);
        
        // Log transaction (only for agent phone)
        if ($recipientPhone == $phone) {
            logWhatsAppTransaction($phone, $username, $voucherResult['success'] ? 'SUCCESS' : 'FAILED', json_encode($voucherResult));
            
            // Log if voucher send failed
            if (!$voucherResult['success']) {
                logWebhookError($phone, "BELI $profileName", "Gagal kirim voucher ke agent. Error: " . ($voucherResult['message'] ?? 'Unknown'));
            }
        } else {
            // Log for customer
            if (!$voucherResult['success']) {
                logWebhookError($phone, "BELI $profileName", "Gagal kirim voucher ke customer ($recipientPhone). Error: " . ($voucherResult['message'] ?? 'Unknown'));
            }
        }
        
        // Small delay between sends
        usleep(300000); // 0.3 second delay
    }
    
    // Load payment settings from database
    $paymentSettings = loadPaymentSettings();
    
    // Send payment instruction only to customer (if provided), otherwise to agent
    // Customer phone is already normalized (only digits) if provided
    $paymentRecipient = !empty($customerPhone) ? $customerPhone : $phone;
    
    $paymentMsg = "💳 *INFORMASI PEMBAYARAN*\n\n";
    $paymentMsg .= "Silakan transfer ke:\n";
    $paymentMsg .= $paymentSettings['bank_name'] . ": " . $paymentSettings['account_number'] . "\n";
    $paymentMsg .= "a.n. " . $paymentSettings['account_name'] . "\n\n";
    $paymentMsg .= "Konfirmasi pembayaran:\n";
    $paymentMsg .= "WA: " . $paymentSettings['wa_confirm'];
    
    // Add small delay before sending payment info
    usleep(500000); // 0.5 second delay
    sendWhatsAppMessage($paymentRecipient, $paymentMsg);
}

/**
 * Send price list
 */
function sendPriceList($phone) {
    global $sessionConfig;
    
    // Use session config instead of overwritten $data
    $data = $sessionConfig;
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "Sistem sedang maintenance.");
        return;
    }
    
    // Load session config
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    $hotspotname = explode('%', $data[$session][4])[1];
    $currency = explode('&', $data[$session][6])[1];
    
    // Connect to MikroTik
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "Gagal terhubung ke server.");
        return;
    }
    
    // Get all profiles
    $profiles = $API->comm("/ip/hotspot/user/profile/print");
    $API->disconnect();
    
    $message = "*📋 DAFTAR PAKET WIFI*\n";
    $message .= "*$hotspotname*\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n\n";
    
    foreach ($profiles as $profile) {
        $name = $profile['name'];
        if ($name == 'default' || $name == 'default-encryption') continue;
        
        $ponlogin = $profile['on-login'];
        if (empty($ponlogin)) continue;
        
        $validity = explode(",", $ponlogin)[3];
        $price = explode(",", $ponlogin)[2];
        $sprice = explode(",", $ponlogin)[4];
        
        if (empty($sprice) || $sprice == '0') continue;
        
        if (strpos($currency, 'Rp') !== false || strpos($currency, 'IDR') !== false) {
            $priceFormatted = $currency . " " . number_format((float)$sprice, 0, ",", ".");
        } else {
            $priceFormatted = $currency . " " . number_format((float)$sprice, 2);
        }
        
        $message .= "*$name*\n";
        $message .= "Validity: $validity\n";
        $message .= "Harga: $priceFormatted\n\n";
    }
    
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "Cara order:\n";
    $message .= "Ketik: *BELI <NAMA_PAKET>*\n";
    $message .= "Contoh: *BELI 1JAM*";
    
    sendWhatsAppMessage($phone, $message);
}

/**
 * Add PPPoE Secret
 */
function addPPPoESecret($phone, $username, $password, $profile) {
    global $sessionConfig;
    
    $data = $sessionConfig;
    if (empty($data) || !is_array($data)) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nKonfigurasi session tidak ter-load.");
        return;
    }
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nSession MikroTik tidak ditemukan.");
        return;
    }
    
    // Load session config
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    // Connect to MikroTik
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ *GAGAL TERHUBUNG*\n\nTidak dapat terhubung ke MikroTik.");
        return;
    }
    
    // Check if username already exists
    $checkUser = $API->comm("/ppp/secret/print", array("?name" => $username));
    if (!empty($checkUser)) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "❌ *USERNAME SUDAH ADA*\n\nUsername *$username* sudah terdaftar.");
        return;
    }
    
    // Check if profile exists
    $checkProfile = $API->comm("/ppp/profile/print", array("?name" => $profile));
    if (empty($checkProfile)) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "❌ *PROFILE TIDAK DITEMUKAN*\n\nProfile *$profile* tidak ada di MikroTik.");
        return;
    }
    
    // Add PPPoE secret
    $API->comm("/ppp/secret/add", array(
        "name" => $username,
        "password" => $password,
        "service" => "pppoe",
        "profile" => $profile
    ));
    
    $API->disconnect();
    
    sendWhatsAppMessage($phone, "✅ *PPPoE SECRET BERHASIL DITAMBAH*\n\nUsername: *$username*\nProfile: *$profile*");
}

/**
 * Edit PPPoE Secret Profile
 */
function editPPPoESecret($phone, $username, $newProfile) {
    global $sessionConfig;
    
    $data = $sessionConfig;
    if (empty($data) || !is_array($data)) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nKonfigurasi session tidak ter-load.");
        return;
    }
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nSession MikroTik tidak ditemukan.");
        return;
    }
    
    // Load session config
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    // Connect to MikroTik
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ *GAGAL TERHUBUNG*\n\nTidak dapat terhubung ke MikroTik.");
        return;
    }
    
    // Find user
    $users = $API->comm("/ppp/secret/print", array("?name" => $username));
    if (empty($users)) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "❌ *USERNAME TIDAK DITEMUKAN*\n\nUsername *$username* tidak ada di MikroTik.");
        return;
    }
    
    $userId = $users[0]['.id'];
    
    // Check if new profile exists
    $checkProfile = $API->comm("/ppp/profile/print", array("?name" => $newProfile));
    if (empty($checkProfile)) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "❌ *PROFILE TIDAK DITEMUKAN*\n\nProfile *$newProfile* tidak ada di MikroTik.");
        return;
    }
    
    // Update profile
    $API->comm("/ppp/secret/set", array(
        ".id" => $userId,
        "profile" => $newProfile
    ));
    
    $API->disconnect();
    
    sendWhatsAppMessage($phone, "✅ *PROFILE BERHASIL DIUPDATE*\n\nUsername: *$username*\nProfile Baru: *$newProfile*");
}

/**
 * Delete PPPoE Secret
 */
function deletePPPoESecret($phone, $username) {
    global $sessionConfig;
    
    $data = $sessionConfig;
    if (empty($data) || !is_array($data)) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nKonfigurasi session tidak ter-load.");
        return;
    }
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nSession MikroTik tidak ditemukan.");
        return;
    }
    
    // Load session config
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    // Connect to MikroTik
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ *GAGAL TERHUBUNG*\n\nTidak dapat terhubung ke MikroTik.");
        return;
    }
    
    // Find user
    $users = $API->comm("/ppp/secret/print", array("?name" => $username));
    if (empty($users)) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "❌ *USERNAME TIDAK DITEMUKAN*\n\nUsername *$username* tidak ada di MikroTik.");
        return;
    }
    
    $userId = $users[0]['.id'];
    
    // Delete user
    $API->comm("/ppp/secret/remove", array(".id" => $userId));
    
    $API->disconnect();
    
    sendWhatsAppMessage($phone, "✅ *PPPoE SECRET BERHASIL DIHAPUS*\n\nUsername: *$username*");
}

/**
 * Check MikroTik Ping
 */
function checkMikroTikPing($phone) {
    global $sessionConfig;
    
    $data = $sessionConfig;
    if (empty($data) || !is_array($data)) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nKonfigurasi session tidak ter-load.");
        return;
    }
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nSession MikroTik tidak ditemukan.");
        return;
    }
    
    // Load session config
    $iphost = explode('!', $data[$session][1])[1];
    
    // Test ping
    $startTime = microtime(true);
    $API = new RouterosAPI();
    $API->debug = false;
    
    $connected = $API->connect($iphost, explode('@|@', $data[$session][2])[1], decrypt(explode('#|#', $data[$session][3])[1]));
    $endTime = microtime(true);
    $pingTime = round(($endTime - $startTime) * 1000, 2);
    
    if ($connected) {
        $API->disconnect();
        $message = "✅ *PING BERHASIL*\n\n";
        $message .= "IP: *$iphost*\n";
        $message .= "Response Time: *{$pingTime} ms*";
    } else {
        $message = "❌ *PING GAGAL*\n\n";
        $message .= "IP: *$iphost*\n";
        $message .= "Tidak dapat terhubung ke MikroTik.";
    }
    
    sendWhatsAppMessage($phone, $message);
}

/**
 * Check MikroTik Status
 */
function checkMikroTikStatus($phone) {
    global $sessionConfig;
    
    $data = $sessionConfig;
    if (empty($data) || !is_array($data)) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nKonfigurasi session tidak ter-load.");
        return;
    }
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nSession MikroTik tidak ditemukan.");
        return;
    }
    
    // Load session config
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    // Connect to MikroTik
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ *GAGAL TERHUBUNG*\n\nTidak dapat terhubung ke MikroTik.");
        return;
    }
    
    // Get identity
    $identity = $API->comm("/system/identity/print");
    $identityName = $identity[0]['name'] ?? 'Unknown';
    
    // Get uptime
    $resource = $API->comm("/system/resource/print");
    $uptime = $resource[0]['uptime'] ?? '0s';
    
    // Get version
    $version = $resource[0]['version'] ?? 'Unknown';
    
    $API->disconnect();
    
    $message = "📊 *STATUS MIKROTIK*\n\n";
    $message .= "Identity: *$identityName*\n";
    $message .= "IP: *$iphost*\n";
    $message .= "Version: *$version*\n";
    $message .= "Uptime: *$uptime*";
    
    sendWhatsAppMessage($phone, $message);
}

/**
 * Check PPPoE Active
 */
function checkPPPoEActive($phone) {
    global $sessionConfig;
    
    $data = $sessionConfig;
    if (empty($data) || !is_array($data)) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nKonfigurasi session tidak ter-load.");
        return;
    }
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nSession MikroTik tidak ditemukan.");
        return;
    }
    
    // Load session config
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    // Connect to MikroTik
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ *GAGAL TERHUBUNG*\n\nTidak dapat terhubung ke MikroTik.");
        return;
    }
    
    // Get active PPPoE connections
    $active = $API->comm("/ppp/active/print");
    $API->disconnect();
    
    $message = "📡 *PPPoE AKTIF*\n\n";
    $message .= "Total: *" . count($active) . " koneksi*\n\n";
    
    if (empty($active)) {
        $message .= "Tidak ada koneksi aktif.";
    } else {
        $count = 0;
        foreach ($active as $conn) {
            $count++;
            if ($count > 10) {
                $message .= "\n... dan " . (count($active) - 10) . " koneksi lainnya";
                break;
            }
            $name = $conn['name'] ?? 'Unknown';
            $address = $conn['address'] ?? 'N/A';
            $uptime = $conn['uptime'] ?? 'N/A';
            $message .= "$count. *$name*\n";
            $message .= "   IP: $address\n";
            $message .= "   Uptime: $uptime\n\n";
        }
    }
    
    sendWhatsAppMessage($phone, $message);
}

/**
 * Check MikroTik Resource
 */
function checkMikroTikResource($phone) {
    global $sessionConfig;
    
    $data = $sessionConfig;
    if (empty($data) || !is_array($data)) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nKonfigurasi session tidak ter-load.");
        return;
    }
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nSession MikroTik tidak ditemukan.");
        return;
    }
    
    // Load session config
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    // Connect to MikroTik
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ *GAGAL TERHUBUNG*\n\nTidak dapat terhubung ke MikroTik.");
        return;
    }
    
    // Get resource
    $resource = $API->comm("/system/resource/print");
    $API->disconnect();
    
    $res = $resource[0];
    
    $cpu = $res['cpu-load'] ?? '0%';
    $cpuCount = $res['cpu-count'] ?? '1';
    $ramTotal = $res['total-memory'] ?? '0';
    $ramUsed = $res['used-memory'] ?? '0';
    $ramFree = $res['free-memory'] ?? '0';
    $ramPercent = $ramTotal > 0 ? round(($ramUsed / $ramTotal) * 100, 1) : 0;
    
    $diskTotal = $res['total-hdd-space'] ?? '0';
    $diskFree = $res['free-hdd-space'] ?? '0';
    $diskUsed = $diskTotal - $diskFree;
    $diskPercent = $diskTotal > 0 ? round(($diskUsed / $diskTotal) * 100, 1) : 0;
    
    // Format bytes
    include_once('../lib/formatbytesbites.php');
    $ramTotalFormatted = formatBytes($ramTotal);
    $ramUsedFormatted = formatBytes($ramUsed);
    $ramFreeFormatted = formatBytes($ramFree);
    $diskTotalFormatted = formatBytes($diskTotal);
    $diskUsedFormatted = formatBytes($diskUsed);
    $diskFreeFormatted = formatBytes($diskFree);
    
    $message = "💻 *RESOURCE MIKROTIK*\n\n";
    $message .= "⚙️ *CPU*\n";
    $message .= "Load: *$cpu*\n";
    $message .= "Cores: *$cpuCount*\n\n";
    $message .= "💾 *RAM*\n";
    $message .= "Used: *$ramUsedFormatted* ($ramPercent%)\n";
    $message .= "Free: *$ramFreeFormatted*\n";
    $message .= "Total: *$ramTotalFormatted*\n\n";
    $message .= "💿 *DISK*\n";
    $message .= "Used: *$diskUsedFormatted* ($diskPercent%)\n";
    $message .= "Free: *$diskFreeFormatted*\n";
    $message .= "Total: *$diskTotalFormatted*";
    
    sendWhatsAppMessage($phone, $message);
}

/**
 * Disable PPPoE Secret
 */
function disablePPPoESecret($phone, $username) {
    global $sessionConfig;
    
    $data = $sessionConfig;
    if (empty($data) || !is_array($data)) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nKonfigurasi session tidak ter-load.");
        return;
    }
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nSession MikroTik tidak ditemukan.");
        return;
    }
    
    // Load session config
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    // Connect to MikroTik
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ *GAGAL TERHUBUNG*\n\nTidak dapat terhubung ke MikroTik.");
        return;
    }
    
    // Find user
    $users = $API->comm("/ppp/secret/print", array("?name" => $username));
    if (empty($users)) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "❌ *USERNAME TIDAK DITEMUKAN*\n\nUsername *$username* tidak ada di MikroTik.");
        return;
    }
    
    $userId = $users[0]['.id'];
    $isDisabled = isset($users[0]['disabled']) && $users[0]['disabled'] == 'true';
    
    if ($isDisabled) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "ℹ️ *SUDAH DISABLE*\n\nUsername *$username* sudah dalam keadaan disable.");
        return;
    }
    
    // Disable user
    $API->comm("/ppp/secret/set", array(
        ".id" => $userId,
        "disabled" => "yes"
    ));
    
    $API->disconnect();
    
    sendWhatsAppMessage($phone, "✅ *PPPoE SECRET BERHASIL DISABLE*\n\nUsername: *$username*");
}

/**
 * Enable PPPoE Secret
 */
function enablePPPoESecret($phone, $username) {
    global $sessionConfig;
    
    $data = $sessionConfig;
    if (empty($data) || !is_array($data)) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nKonfigurasi session tidak ter-load.");
        return;
    }
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nSession MikroTik tidak ditemukan.");
        return;
    }
    
    // Load session config
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    // Connect to MikroTik
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ *GAGAL TERHUBUNG*\n\nTidak dapat terhubung ke MikroTik.");
        return;
    }
    
    // Find user
    $users = $API->comm("/ppp/secret/print", array("?name" => $username));
    if (empty($users)) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "❌ *USERNAME TIDAK DITEMUKAN*\n\nUsername *$username* tidak ada di MikroTik.");
        return;
    }
    
    $userId = $users[0]['.id'];
    $isDisabled = isset($users[0]['disabled']) && $users[0]['disabled'] == 'true';
    
    if (!$isDisabled) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "ℹ️ *SUDAH ENABLE*\n\nUsername *$username* sudah dalam keadaan enable.");
        return;
    }
    
    // Enable user
    $API->comm("/ppp/secret/set", array(
        ".id" => $userId,
        "disabled" => "no"
    ));
    
    $API->disconnect();
    
    sendWhatsAppMessage($phone, "✅ *PPPoE SECRET BERHASIL ENABLE*\n\nUsername: *$username*");
}

/**
 * Disable Hotspot User
 */
function disableHotspotUser($phone, $username) {
    global $sessionConfig;
    
    $data = $sessionConfig;
    if (empty($data) || !is_array($data)) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nKonfigurasi session tidak ter-load.");
        return;
    }
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nSession MikroTik tidak ditemukan.");
        return;
    }
    
    // Load session config
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    // Connect to MikroTik
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ *GAGAL TERHUBUNG*\n\nTidak dapat terhubung ke MikroTik.");
        return;
    }
    
    // Find user
    $users = $API->comm("/ip/hotspot/user/print", array("?name" => $username));
    if (empty($users)) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "❌ *USERNAME TIDAK DITEMUKAN*\n\nUsername *$username* tidak ada di MikroTik.");
        return;
    }
    
    $userId = $users[0]['.id'];
    $isDisabled = isset($users[0]['disabled']) && $users[0]['disabled'] == 'true';
    
    if ($isDisabled) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "ℹ️ *SUDAH DISABLE*\n\nUsername *$username* sudah dalam keadaan disable.");
        return;
    }
    
    // Disable user
    $API->comm("/ip/hotspot/user/set", array(
        ".id" => $userId,
        "disabled" => "yes"
    ));
    
    $API->disconnect();
    
    sendWhatsAppMessage($phone, "✅ *HOTSPOT USER BERHASIL DISABLE*\n\nUsername: *$username*");
}

/**
 * Enable Hotspot User
 */
function enableHotspotUser($phone, $username) {
    global $sessionConfig;
    
    $data = $sessionConfig;
    if (empty($data) || !is_array($data)) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nKonfigurasi session tidak ter-load.");
        return;
    }
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nSession MikroTik tidak ditemukan.");
        return;
    }
    
    // Load session config
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    // Connect to MikroTik
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ *GAGAL TERHUBUNG*\n\nTidak dapat terhubung ke MikroTik.");
        return;
    }
    
    // Find user
    $users = $API->comm("/ip/hotspot/user/print", array("?name" => $username));
    if (empty($users)) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "❌ *USERNAME TIDAK DITEMUKAN*\n\nUsername *$username* tidak ada di MikroTik.");
        return;
    }
    
    $userId = $users[0]['.id'];
    $isDisabled = isset($users[0]['disabled']) && $users[0]['disabled'] == 'true';
    
    if (!$isDisabled) {
        $API->disconnect();
        sendWhatsAppMessage($phone, "ℹ️ *SUDAH ENABLE*\n\nUsername *$username* sudah dalam keadaan enable.");
        return;
    }
    
    // Enable user
    $API->comm("/ip/hotspot/user/set", array(
        ".id" => $userId,
        "disabled" => "no"
    ));
    
    $API->disconnect();
    
    sendWhatsAppMessage($phone, "✅ *HOTSPOT USER BERHASIL ENABLE*\n\nUsername: *$username*");
}

/**
 * Check PPPoE Offline (not connected)
 */
function checkPPPoEOffline($phone) {
    global $sessionConfig;
    
    $data = $sessionConfig;
    if (empty($data) || !is_array($data)) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nKonfigurasi session tidak ter-load.");
        return;
    }
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ *SISTEM ERROR*\n\nSession MikroTik tidak ditemukan.");
        return;
    }
    
    // Load session config
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    // Connect to MikroTik
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ *GAGAL TERHUBUNG*\n\nTidak dapat terhubung ke MikroTik.");
        return;
    }
    
    // Get all PPPoE secrets
    // Note: Filter by service manually because query might not work as expected
    $allSecrets = $API->comm("/ppp/secret/print");
    
    // Get active PPPoE connections
    $active = $API->comm("/ppp/active/print");
    $activeNames = array();
    foreach ($active as $conn) {
        $name = trim($conn['name'] ?? '');
        if (!empty($name)) {
            $activeNames[] = strtolower($name); // Use lowercase for comparison
        }
    }
    
    // Filter PPPoE secrets and find offline users
    $offlineUsers = array();
    foreach ($allSecrets as $secret) {
        $name = trim($secret['name'] ?? '');
        $service = isset($secret['service']) ? strtolower($secret['service']) : '';
        $disabled = isset($secret['disabled']) && $secret['disabled'] == 'true';
        
        // Skip if empty name
        if (empty($name)) continue;
        
        // Skip if not PPPoE service (should be 'pppoe')
        if ($service != 'pppoe') continue;
        
        // Skip disabled users
        if ($disabled) continue;
        
        // Check if not in active connections (case-insensitive comparison)
        $nameLower = strtolower($name);
        if (!in_array($nameLower, $activeNames)) {
            $profile = $secret['profile'] ?? 'N/A';
            $offlineUsers[] = [
                'name' => $name,
                'profile' => $profile
            ];
        }
    }
    
    $API->disconnect();
    
    $message = "📴 *PPPoE OFFLINE*\n\n";
    $message .= "Total: *" . count($offlineUsers) . " user offline*\n\n";
    
    if (empty($offlineUsers)) {
        $message .= "✅ Semua user PPPoE sedang online.";
    } else {
        $count = 0;
        foreach ($offlineUsers as $user) {
            $count++;
            if ($count > 20) {
                $message .= "\n... dan " . (count($offlineUsers) - 20) . " user lainnya";
                break;
            }
            $message .= "$count. *{$user['name']}*\n";
            $message .= "   Profile: {$user['profile']}\n\n";
        }
    }
    
    sendWhatsAppMessage($phone, $message);
}

/**
 * Send help message
 */
function sendHelp($phone) {
    $message = "*🤖 BANTUAN BOT VOUCHER*\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n\n";
    $message .= "*Perintah yang tersedia:*\n\n";
    $message .= "📋 *HARGA* atau *PAKET*\n";
    $message .= "Melihat daftar paket dan harga\n\n";
    $message .= "🎫 *VOUCHER [USERNAME] <NAMA_PAKET> [NOMER]*\n";
    $message .= "Membeli voucher (Username = Password)\n";
    $message .= "Contoh: VOUCHER 3K\n";
    $message .= "Contoh dengan nomor: VOUCHER 3K 08123456789\n";
    $message .= "Contoh username manual: VOUCHER user123 3K\n";
    $message .= "Contoh lengkap: VOUCHER user123 3K 08123456789\n";
    $message .= "Voucher akan dikirim ke nomor pembeli dan agent\n\n";
    $message .= "⚡ *VCR [USERNAME] <NAMA_PAKET> [NOMER]*\n";
    $message .= "Perintah singkat untuk VOUCHER\n";
    $message .= "Contoh: VCR 3K, VCR user123 3K 08123456789\n\n";
    $message .= "⚙️ *GENERATE [USERNAME] <NAMA_PAKET> [NOMER]*\n";
    $message .= "Alias untuk VOUCHER\n";
    $message .= "Contoh: GENERATE 3K, GENERATE user123 3K 08123456789\n\n";
    $message .= "👤 *MEMBER <NAMA_PAKET>*\n";
    $message .= "Membeli member (Username ≠ Password)\n";
    $message .= "Contoh: MEMBER 3K\n\n";
    $message .= "🛒 *BELI <NAMA_PAKET>*\n";
    $message .= "Membeli voucher (menggunakan setting default)\n";
    $message .= "Contoh: BELI 1JAM\n\n";
    
    // Admin-only commands
    $isAdmin = isAdminNumber($phone);
    if ($isAdmin) {
        $message .= "━━━━━━━━━━━━━━━━━━━━\n";
        $message .= "*🔐 PERINTAH ADMIN*\n\n";
        $message .= "➕ *TAMBAH <username> <password> <profile>*\n";
        $message .= "Tambah PPPoE Secret\n";
        $message .= "Contoh: TAMBAH user123 pass123 profile1\n\n";
        $message .= "✏️ *EDIT <username> <profile_baru>*\n";
        $message .= "Edit profile PPPoE Secret\n";
        $message .= "Contoh: EDIT user123 profile2\n\n";
        $message .= "🗑️ *HAPUS <username>*\n";
        $message .= "Hapus PPPoE Secret\n";
        $message .= "Contoh: HAPUS user123\n\n";
        $message .= "📡 *PING* atau *CEK PING*\n";
        $message .= "Test koneksi ke MikroTik\n\n";
        $message .= "📊 *STATUS* atau *CEK*\n";
        $message .= "Cek status MikroTik (Identity, Version, Uptime)\n\n";
        $message .= "🔌 *PPPOE* atau *PPP*\n";
        $message .= "Cek koneksi PPPoE aktif\n\n";
        $message .= "💻 *RESOURCE* atau *RES*\n";
        $message .= "Cek resource MikroTik (CPU, RAM, Disk)\n\n";
        $message .= "🔒 *DISABLE PPPOE <username>*\n";
        $message .= "Disable PPPoE Secret\n";
        $message .= "Contoh: DISABLE PPPOE user123\n\n";
        $message .= "🔓 *ENABLE PPPOE <username>*\n";
        $message .= "Enable PPPoE Secret\n";
        $message .= "Contoh: ENABLE PPPOE user123\n\n";
        $message .= "🔒 *DISABLE HOTSPOT <username>*\n";
        $message .= "Disable Hotspot User\n";
        $message .= "Contoh: DISABLE HOTSPOT user123\n\n";
        $message .= "🔓 *ENABLE HOTSPOT <username>*\n";
        $message .= "Enable Hotspot User\n";
        $message .= "Contoh: ENABLE HOTSPOT user123\n\n";
        $message .= "📴 *PPPOE OFFLINE* atau *PPP OFFLINE*\n";
        $message .= "Cek PPPoE yang tidak terkoneksi\n\n";
    }
    
    $message .= "❓ *HELP*\n";
    $message .= "Menampilkan bantuan ini\n\n";
    $message .= "━━━━━━━━━━━━━━━━━━━━\n";
    $message .= "_Hubungi admin jika ada kendala_";
    
    sendWhatsAppMessage($phone, $message);
}

/**
 * Log webhook data
 */
function logWebhook($data) {
    $logFile = '../logs/webhook_log.txt';
    $logDir = dirname($logFile);
    
    if (!file_exists($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    $logEntry = date('Y-m-d H:i:s') . " | " . $data . "\n";
    file_put_contents($logFile, $logEntry, FILE_APPEND);
}

/**
 * Log webhook error
 */
function logWebhookError($phone, $command, $error) {
    $logFile = '../logs/webhook_error_log.txt';
    $logDir = dirname($logFile);
    
    if (!file_exists($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    $logEntry = date('Y-m-d H:i:s') . " | Phone: $phone | Command: $command | Error: $error\n";
    file_put_contents($logFile, $logEntry, FILE_APPEND);
}

// Return success response
http_response_code(200);
echo json_encode(['status' => 'success', 'message' => 'Webhook processed']);
