<?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');

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

// Log incoming webhook
logWebhook($input);

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

switch ($gateway) {
    case 'fonnte':
        processWebhookFonnte($data);
        break;
    case 'wablas':
        processWebhookWablas($data);
        break;
    case 'woowa':
        processWebhookWoowa($data);
        break;
    default:
        processWebhookCustom($data);
        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 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);
}

/**
 * Process incoming command
 */
function processCommand($phone, $message) {
    // Command: BELI <PROFILE>
    // Example: BELI 1JAM, BELI 3JAM, BELI 1HARI
    
    if (strpos($message, 'beli ') === 0) {
        $profile = trim(str_replace('beli ', '', $message));
        purchaseVoucher($phone, $profile);
    }
    // Command: HARGA or PAKET
    elseif ($message == 'harga' || $message == 'paket' || $message == 'list') {
        sendPriceList($phone);
    }
    // Command: HELP
    elseif ($message == 'help' || $message == 'bantuan') {
        sendHelp($phone);
    }
    // Default response
    else {
        $reply = "Perintah tidak dikenali.\nKetik *HELP* untuk bantuan.";
        sendWhatsAppMessage($phone, $reply);
    }
}

/**
 * Purchase voucher
 */
function purchaseVoucher($phone, $profileName) {
    global $data;
    
    // 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) {
        sendWhatsAppMessage($phone, "Sistem sedang maintenance. Silakan coba lagi nanti.");
        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];
    $dnsname = explode('^', $data[$session][5])[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. Silakan coba lagi nanti.");
        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
    $username = strtolower($profileName) . randNULC(6);
    $password = randNULC(6);
    $comment = "WA-" . substr($phone, -4) . "-" . date("dmy");
    
    // 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
    ];
    
    $result = sendVoucherNotification($phone, $voucherData);
    
    // Log transaction
    logWhatsAppTransaction($phone, $username, $result['success'] ? 'SUCCESS' : 'FAILED', json_encode($result));
    
    // Send payment instruction
    $paymentMsg = "\n\n💳 *INFORMASI PEMBAYARAN*\n";
    $paymentMsg .= "Silakan transfer ke:\n";
    $paymentMsg .= "BCA: 1234567890\n";
    $paymentMsg .= "a.n. Nama Pemilik\n\n";
    $paymentMsg .= "Konfirmasi pembayaran:\n";
    $paymentMsg .= "WA: 08123456789";
    
    sendWhatsAppMessage($phone, $paymentMsg);
}

/**
 * Send price list
 */
function sendPriceList($phone) {
    global $data;
    
    // 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);
}

/**
 * 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 .= "🛒 *BELI <NAMA_PAKET>*\n";
    $message .= "Membeli voucher\n";
    $message .= "Contoh: BELI 1JAM\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);
}

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