<?php
/*
 * WhatsApp Agent Webhook Handler
 * Handle incoming WhatsApp messages for agent commands
 */

session_start();
error_reporting(0);

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

// Load message settings
$messageSettings = loadMessageSettings();

// 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 ?? 'fonnte';

switch ($gateway) {
    case 'fonnte':
        $phone = $data['sender'] ?? '';
        $message = $data['message'] ?? '';
        break;
    case 'wablas':
        $phone = $data['phone'] ?? '';
        $message = $data['message'] ?? '';
        break;
    case 'woowa':
        $phone = $data['from'] ?? '';
        $message = $data['message'] ?? '';
        break;
    default:
        $phone = $data['phone'] ?? $data['sender'] ?? $data['from'] ?? '';
        $message = $data['message'] ?? '';
        break;
}

if (!empty($phone) && !empty($message)) {
    processAgentCommand($phone, trim($message));
}

/**
 * Process agent command
 */
function processAgentCommand($phone, $message) {
    $messageLower = strtolower($message);
    
    // Check if agent exists
    $agent = new Agent();
    $agentData = $agent->getAgentByPhone($phone);
    
    // Check if admin number
    $isAdmin = isAdminNumber($phone);
    
    // Commands available for agents
    if ($agentData || $isAdmin) {
        // GENERATE command
        if (preg_match('/^(gen|generate)\s+(\w+)(\s+(\d+))?$/i', $message, $matches)) {
            $profile = $matches[2];
            $quantity = isset($matches[4]) ? intval($matches[4]) : 1;
            
            if ($isAdmin) {
                generateVoucherAdmin($phone, $profile, $quantity);
            } else {
                generateVoucherAgent($phone, $agentData, $profile, $quantity);
            }
        }
        // SALDO command
        elseif (preg_match('/^(saldo|balance|cek\s*saldo)$/i', $messageLower)) {
            if ($isAdmin) {
                sendAdminInfo($phone);
            } else {
                checkBalance($phone, $agentData);
            }
        }
        // TRANSAKSI command
        elseif (preg_match('/^(transaksi|history|riwayat)(\s+(\d+))?$/i', $message, $matches)) {
            $limit = isset($matches[3]) ? intval($matches[3]) : 10;
            checkTransactions($phone, $agentData, $limit);
        }
        // HARGA command
        elseif (preg_match('/^(harga|price|paket)$/i', $messageLower)) {
            if ($agentData) {
                showAgentPrices($phone, $agentData);
            } else {
                showAllPrices($phone);
            }
        }
        // TOPUP REQUEST command
        elseif (preg_match('/^topup\s+(\d+)$/i', $message, $matches)) {
            if ($agentData) {
                $amount = intval($matches[1]);
                requestTopup($phone, $agentData, $amount);
            }
        }
        // SALES REPORT command
        elseif (preg_match('/^(laporan|report|sales)(\s+(today|week|month))?$/i', $message, $matches)) {
            if ($agentData) {
                $period = isset($matches[3]) ? strtolower($matches[3]) : 'today';
                sendSalesReport($phone, $agentData, $period);
            }
        }
        // BROADCAST command (admin only)
        elseif (preg_match('/^broadcast\s+(.+)$/is', $message, $matches)) {
            if ($agentData) {
                $broadcastMessage = $matches[1];
                broadcastMessage($phone, $agentData, $broadcastMessage);
            }
        }
        // HELP command
        elseif (preg_match('/^(help|bantuan|\?)$/i', $messageLower)) {
            if ($isAdmin) {
                sendAdminHelp($phone);
            } else {
                sendAgentHelp($phone);
            }
        }
        // Unknown command
        else {
            $reply = "❌ Perintah tidak dikenali.\n\n";
            $reply .= "Ketik *HELP* untuk melihat daftar perintah.";
            sendWhatsAppMessage($phone, $reply);
        }
    }
    // Not registered
    else {
        $reply = "❌ Nomor Anda belum terdaftar sebagai agent.\n\n";
        $reply .= "Silakan hubungi admin untuk pendaftaran.";
        sendWhatsAppMessage($phone, $reply);
    }
}

/**
 * Check if admin number
 */
function isAdminNumber($phone) {
    // Get admin numbers from database or config
    $db = getDBConnection();
    $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);
    }
    
    return false;
}

/**
 * Generate voucher for agent
 */
function generateVoucherAgent($phone, $agentData, $profileName, $quantity) {
    global $data;
    
    if ($agentData['status'] != 'active') {
        sendWhatsAppMessage($phone, "❌ Akun agent Anda tidak aktif.\nHubungi admin untuk informasi lebih lanjut.");
        return;
    }
    
    // Get agent price
    $agent = new Agent();
    $priceData = $agent->getAgentPrice($agentData['id'], $profileName);
    
    if (!$priceData) {
        sendWhatsAppMessage($phone, "❌ Harga untuk profile *$profileName* belum diset.\nHubungi admin.");
        return;
    }
    
    $buyPrice = $priceData['buy_price'];
    $totalCost = $buyPrice * $quantity;
    
    // Check balance
    if ($agentData['balance'] < $totalCost) {
        $reply = "❌ *SALDO TIDAK CUKUP*\n\n";
        $reply .= "Saldo Anda: Rp " . number_format($agentData['balance'], 0, ',', '.') . "\n";
        $reply .= "Dibutuhkan: Rp " . number_format($totalCost, 0, ',', '.') . "\n";
        $reply .= "Kurang: Rp " . number_format($totalCost - $agentData['balance'], 0, ',', '.') . "\n\n";
        $reply .= "Silakan topup saldo terlebih dahulu.";
        sendWhatsAppMessage($phone, $reply);
        return;
    }
    
    // Get MikroTik session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ Sistem sedang maintenance. Coba lagi nanti.");
        return;
    }
    
    // Connect to MikroTik
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ Gagal terhubung ke server. Coba lagi nanti.");
        return;
    }
    
    // Generate vouchers
    $voucherGen = new VoucherGenerator();
    $generatedVouchers = [];
    $successCount = 0;
    
    for ($i = 0; $i < $quantity; $i++) {
        $voucher = $voucherGen->generateVoucher();
        $username = $voucher['username'];
        $password = $voucher['password'];
        $comment = 'Agent-' . $agentData['agent_code'] . '-' . date('dmy');
        
        // Add to MikroTik
        $API->comm("/ip/hotspot/user/add", array(
            "server" => "all",
            "name" => $username,
            "password" => $password,
            "profile" => $profileName,
            "comment" => $comment,
        ));
        
        // Deduct balance
        $deductResult = $agent->deductBalance(
            $agentData['id'],
            $buyPrice,
            $profileName,
            $username,
            'Generate via WhatsApp'
        );
        
        if ($deductResult['success']) {
            // Save to agent_vouchers
            $db = getDBConnection();
            $sql = "INSERT INTO agent_vouchers (agent_id, transaction_id, username, password, profile_name, buy_price, sell_price, sent_via) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, 'whatsapp')";
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $agentData['id'],
                $deductResult['transaction_id'],
                $username,
                $password,
                $profileName,
                $buyPrice,
                $priceData['sell_price']
            ]);
            
            $generatedVouchers[] = [
                'username' => $username,
                'password' => $password
            ];
            
            $successCount++;
        }
    }
    
    $API->disconnect();
    
    // Send vouchers
    if ($successCount > 0) {
        $agentData = $agent->getAgentById($agentData['id']); // Refresh balance
        
        $content = "✅ *VOUCHER BERHASIL DI-GENERATE*\n\n";
        $content .= "Profile: *$profileName*\n";
        $content .= "Jumlah: $successCount voucher\n";
        $content .= "Total: Rp " . number_format($totalCost, 0, ',', '.') . "\n\n";
        $content .= "━━━━━━━━━━━━━━━━━━━━\n\n";
        
        foreach ($generatedVouchers as $index => $v) {
            $content .= "*Voucher #" . ($index + 1) . "*\n";
            $content .= "Username: `" . $v['username'] . "`\n";
            $content .= "Password: `" . $v['password'] . "`\n\n";
        }
        
        $content .= "━━━━━━━━━━━━━━━━━━━━\n";
        $content .= "💰 Saldo Anda: Rp " . number_format($agentData['balance'], 0, ',', '.');
        
        $reply = formatMessage($content);
        sendWhatsAppMessage($phone, $reply);
    } else {
        sendWhatsAppMessage($phone, "❌ Gagal generate voucher. Silakan coba lagi.");
    }
}

/**
 * Generate voucher for admin (no balance check)
 */
function generateVoucherAdmin($phone, $profileName, $quantity) {
    global $data;
    
    // Get MikroTik 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;
    }
    
    // Connect to MikroTik
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ Gagal terhubung ke server.");
        return;
    }
    
    // Generate vouchers
    $voucherGen = new VoucherGenerator();
    $generatedVouchers = [];
    
    for ($i = 0; $i < $quantity; $i++) {
        $voucher = $voucherGen->generateVoucher();
        $username = $voucher['username'];
        $password = $voucher['password'];
        $comment = 'Admin-WA-' . date('dmy');
        
        // Add to MikroTik
        $API->comm("/ip/hotspot/user/add", array(
            "server" => "all",
            "name" => $username,
            "password" => $password,
            "profile" => $profileName,
            "comment" => $comment,
        ));
        
        $generatedVouchers[] = [
            'username' => $username,
            'password' => $password
        ];
    }
    
    $API->disconnect();
    
    // Send vouchers
    $content = "✅ *VOUCHER ADMIN*\n\n";
    $content .= "Profile: *$profileName*\n";
    $content .= "Jumlah: $quantity voucher\n\n";
    $content .= "━━━━━━━━━━━━━━━━━━━━\n\n";
    
    foreach ($generatedVouchers as $index => $v) {
        $content .= "*Voucher #" . ($index + 1) . "*\n";
        $content .= "Username: `" . $v['username'] . "`\n";
        $content .= "Password: `" . $v['password'] . "`\n\n";
    }
    
    $content .= "━━━━━━━━━━━━━━━━━━━━\n";
    $content .= "🔑 *ADMIN ACCESS* - No balance deduction";
    
    $reply = formatMessage($content);
    sendWhatsAppMessage($phone, $reply);
}

/**
 * Check agent balance
 */
function checkBalance($phone, $agentData) {
    $agent = new Agent();
    $summary = $agent->getAgentSummary($agentData['id']);
    
    $reply = "💰 *INFORMASI SALDO*\n\n";
    $reply .= "Agent: *" . $agentData['agent_name'] . "*\n";
    $reply .= "Kode: " . $agentData['agent_code'] . "\n";
    $reply .= "Level: " . ucfirst($agentData['level']) . "\n\n";
    $reply .= "━━━━━━━━━━━━━━━━━━━━\n\n";
    $reply .= "💵 Saldo: *Rp " . number_format($agentData['balance'], 0, ',', '.') . "*\n\n";
    
    if ($summary) {
        $reply .= "📊 *Statistik:*\n";
        $reply .= "• Total Voucher: " . $summary['total_vouchers'] . "\n";
        $reply .= "• Voucher Terpakai: " . $summary['used_vouchers'] . "\n";
        $reply .= "• Total Topup: Rp " . number_format($summary['total_topup'], 0, ',', '.') . "\n";
        $reply .= "• Total Pengeluaran: Rp " . number_format($summary['total_spent'], 0, ',', '.') . "\n";
    }
    
    sendWhatsAppMessage($phone, $reply);
}

/**
 * Check transactions
 */
function checkTransactions($phone, $agentData, $limit) {
    $agent = new Agent();
    $transactions = $agent->getTransactions($agentData['id'], $limit);
    
    if (empty($transactions)) {
        sendWhatsAppMessage($phone, "📋 Belum ada transaksi.");
        return;
    }
    
    $reply = "📋 *RIWAYAT TRANSAKSI*\n";
    $reply .= "(" . count($transactions) . " transaksi terakhir)\n\n";
    $reply .= "━━━━━━━━━━━━━━━━━━━━\n\n";
    
    foreach ($transactions as $trx) {
        $date = date('d/m H:i', strtotime($trx['created_at']));
        $type = ucfirst($trx['transaction_type']);
        $amount = number_format($trx['amount'], 0, ',', '.');
        $sign = $trx['transaction_type'] == 'topup' ? '+' : '-';
        
        $reply .= "*$date* | $type\n";
        $reply .= "$sign Rp $amount\n";
        
        if ($trx['profile_name']) {
            $reply .= "Profile: " . $trx['profile_name'] . "\n";
        }
        if ($trx['voucher_username']) {
            $reply .= "User: " . $trx['voucher_username'] . "\n";
        }
        
        $reply .= "\n";
    }
    
    $reply .= "━━━━━━━━━━━━━━━━━━━━\n";
    $reply .= "💰 Saldo: Rp " . number_format($agentData['balance'], 0, ',', '.');
    
    sendWhatsAppMessage($phone, $reply);
}

/**
 * Show agent prices
 */
function showAgentPrices($phone, $agentData) {
    $agent = new Agent();
    $prices = $agent->getAllAgentPrices($agentData['id']);
    
    if (empty($prices)) {
        sendWhatsAppMessage($phone, "❌ Harga belum diset. Hubungi admin.");
        return;
    }
    
    $reply = "💵 *DAFTAR HARGA AGENT*\n\n";
    $reply .= "Agent: " . $agentData['agent_name'] . "\n";
    $reply .= "Kode: " . $agentData['agent_code'] . "\n\n";
    $reply .= "━━━━━━━━━━━━━━━━━━━━\n\n";
    
    foreach ($prices as $price) {
        $profit = $price['sell_price'] - $price['buy_price'];
        
        $reply .= "*" . $price['profile_name'] . "*\n";
        $reply .= "Harga Beli: Rp " . number_format($price['buy_price'], 0, ',', '.') . "\n";
        $reply .= "Harga Jual: Rp " . number_format($price['sell_price'], 0, ',', '.') . "\n";
        $reply .= "Profit: Rp " . number_format($profit, 0, ',', '.') . "\n\n";
    }
    
    $reply .= "━━━━━━━━━━━━━━━━━━━━\n";
    $reply .= "Cara generate:\n";
    $reply .= "*GEN <PROFILE> <QTY>*\n";
    $reply .= "Contoh: GEN 3JAM 5";
    
    sendWhatsAppMessage($phone, $reply);
}

/**
 * Show all prices (for admin)
 */
function showAllPrices($phone) {
    global $data;
    
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if (!$session) {
        sendWhatsAppMessage($phone, "❌ Sistem sedang maintenance.");
        return;
    }
    
    $iphost = explode('!', $data[$session][1])[1];
    $userhost = explode('@|@', $data[$session][2])[1];
    $passwdhost = explode('#|#', $data[$session][3])[1];
    
    $API = new RouterosAPI();
    $API->debug = false;
    
    if (!$API->connect($iphost, $userhost, decrypt($passwdhost))) {
        sendWhatsAppMessage($phone, "❌ Gagal terhubung ke server.");
        return;
    }
    
    $profiles = $API->comm("/ip/hotspot/user/profile/print");
    $API->disconnect();
    
    $reply = "📋 *DAFTAR PROFILE*\n\n";
    
    foreach ($profiles as $profile) {
        if ($profile['name'] == 'default' || $profile['name'] == 'default-encryption') continue;
        $reply .= "• " . $profile['name'] . "\n";
    }
    
    $reply .= "\n━━━━━━━━━━━━━━━━━━━━\n";
    $reply .= "Cara generate:\n";
    $reply .= "*GEN <PROFILE> <QTY>*";
    
    sendWhatsAppMessage($phone, $reply);
}

/**
 * Send agent help
 */
function sendAgentHelp($phone) {
    $reply = "🤖 *BANTUAN AGENT BOT*\n\n";
    $reply .= "━━━━━━━━━━━━━━━━━━━━\n\n";
    $reply .= "*Perintah yang tersedia:*\n\n";
    
    $reply .= "🎫 *GEN <PROFILE> <QTY>*\n";
    $reply .= "Generate voucher\n";
    $reply .= "Contoh: GEN 3JAM 5\n\n";
    
    $reply .= "💰 *SALDO*\n";
    $reply .= "Cek saldo dan statistik\n\n";
    
    $reply .= "📋 *TRANSAKSI <JUMLAH>*\n";
    $reply .= "Lihat riwayat transaksi\n";
    $reply .= "Contoh: TRANSAKSI 20\n\n";
    
    $reply .= "💵 *HARGA*\n";
    $reply .= "Lihat daftar harga\n\n";
    
    $reply .= "💳 *TOPUP <JUMLAH>*\n";
    $reply .= "Request topup saldo\n";
    $reply .= "Contoh: TOPUP 100000\n\n";
    
    $reply .= "📊 *LAPORAN <PERIOD>*\n";
    $reply .= "Lihat laporan penjualan\n";
    $reply .= "Period: TODAY, WEEK, MONTH\n";
    $reply .= "Contoh: LAPORAN WEEK\n\n";
    
    $reply .= "📢 *BROADCAST <PESAN>*\n";
    $reply .= "Kirim pesan ke semua customer\n";
    $reply .= "Contoh: BROADCAST Promo hari ini!\n\n";
    
    $reply .= "❓ *HELP*\n";
    $reply .= "Tampilkan bantuan ini\n\n";
    
    $reply .= "━━━━━━━━━━━━━━━━━━━━\n";
    $reply .= "_Hubungi admin jika ada kendala_";
    
    sendWhatsAppMessage($phone, $reply);
}

/**
 * Send admin help
 */
function sendAdminHelp($phone) {
    $reply = "👑 *BANTUAN ADMIN BOT*\n\n";
    $reply .= "━━━━━━━━━━━━━━━━━━━━\n\n";
    $reply .= "*Perintah Admin:*\n\n";
    
    $reply .= "🎫 *GEN <PROFILE> <QTY>*\n";
    $reply .= "Generate voucher (tanpa potong saldo)\n";
    $reply .= "Contoh: GEN 3JAM 10\n\n";
    
    $reply .= "💰 *SALDO*\n";
    $reply .= "Info admin access\n\n";
    
    $reply .= "💵 *HARGA*\n";
    $reply .= "Lihat semua profile\n\n";
    
    $reply .= "❓ *HELP*\n";
    $reply .= "Tampilkan bantuan ini\n\n";
    
    $reply .= "━━━━━━━━━━━━━━━━━━━━\n";
    $reply .= "🔑 *ADMIN ACCESS ACTIVE*";
    
    sendWhatsAppMessage($phone, $reply);
}

/**
 * Send admin info
 */
function sendAdminInfo($phone) {
    $reply = "👑 *ADMIN ACCESS*\n\n";
    $reply .= "Status: ✅ Active\n";
    $reply .= "Privilege: Unlimited\n\n";
    $reply .= "━━━━━━━━━━━━━━━━━━━━\n\n";
    $reply .= "Anda dapat generate voucher tanpa batas.\n";
    $reply .= "Tidak ada pemotongan saldo.\n\n";
    $reply .= "Ketik *HELP* untuk perintah.";
    
    sendWhatsAppMessage($phone, $reply);
}

/**
 * Request topup
 */
function requestTopup($phone, $agentData, $amount) {
    if ($amount < 10000) {
        sendWhatsAppMessage($phone, "❌ Minimal topup Rp 10,000");
        return;
    }
    
    // Save topup request
    $db = getDBConnection();
    $stmt = $db->prepare("
        INSERT INTO agent_topup_requests (agent_id, amount, payment_method, status, agent_notes) 
        VALUES (?, ?, 'transfer', 'pending', 'Request via WhatsApp')
    ");
    $stmt->execute([$agentData['id'], $amount]);
    
    // Notify agent
    $reply = "✅ *REQUEST TOPUP DIKIRIM*\n\n";
    $reply .= "Jumlah: Rp " . number_format($amount, 0, ',', '.') . "\n\n";
    $reply .= "━━━━━━━━━━━━━━━━━━━━\n\n";
    $reply .= "Silakan transfer ke:\n";
    $reply .= "BCA: 1234567890\n";
    $reply .= "a.n. Nama Pemilik\n\n";
    $reply .= "Setelah transfer, kirim bukti ke admin.\n";
    $reply .= "Request Anda akan diproses segera.";
    
    sendWhatsAppMessage($phone, $reply);
    
    // Notify admin
    include_once('../lib/WhatsAppNotification.class.php');
    $notification = new WhatsAppNotification();
    $notification->notifyTopupRequest($agentData['id'], $amount);
}

/**
 * Send sales report
 */
function sendSalesReport($phone, $agentData, $period) {
    include_once('../lib/WhatsAppNotification.class.php');
    $notification = new WhatsAppNotification();
    $notification->sendSalesReport($agentData['id'], $period);
}

/**
 * Broadcast message
 */
function broadcastMessage($phone, $agentData, $messageContent) {
    include_once('../lib/WhatsAppNotification.class.php');
    $notification = new WhatsAppNotification();
    $result = $notification->broadcastToCustomers($agentData['id'], $messageContent);
    
    if ($result['success']) {
        $reply = "✅ *BROADCAST TERKIRIM*\n\n";
        $reply .= "Total Customer: {$result['total']}\n";
        $reply .= "Terkirim: {$result['sent']}\n";
        $reply .= "Gagal: " . ($result['total'] - $result['sent']);
    } else {
        $reply = "❌ " . $result['message'];
    }
    
    sendWhatsAppMessage($phone, $reply);
}

/**
 * Load message settings from database
 */
function loadMessageSettings() {
    $db = getDBConnection();
    $stmt = $db->query("SELECT setting_key, setting_value FROM agent_settings WHERE setting_key LIKE 'wa_%'");
    
    $settings = [
        'header' => '',
        'footer' => '',
        'business_name' => 'WiFi Hotspot',
        'business_phone' => '08123456789',
        'business_address' => 'Jl. Contoh No. 123',
        'enable_emoji' => true,
        'enable_formatting' => true
    ];
    
    while ($row = $stmt->fetch()) {
        switch ($row['setting_key']) {
            case 'wa_message_header':
                $settings['header'] = $row['setting_value'];
                break;
            case 'wa_message_footer':
                $settings['footer'] = $row['setting_value'];
                break;
            case 'wa_business_name':
                $settings['business_name'] = $row['setting_value'];
                break;
            case 'wa_business_phone':
                $settings['business_phone'] = $row['setting_value'];
                break;
            case 'wa_business_address':
                $settings['business_address'] = $row['setting_value'];
                break;
            case 'wa_enable_emoji':
                $settings['enable_emoji'] = $row['setting_value'] == '1';
                break;
            case 'wa_enable_formatting':
                $settings['enable_formatting'] = $row['setting_value'] == '1';
                break;
        }
    }
    
    return $settings;
}

/**
 * Format message with header and footer
 */
function formatMessage($content) {
    global $messageSettings;
    
    $header = $messageSettings['header'];
    $footer = $messageSettings['footer'];
    
    // Replace variables in footer
    $footer = str_replace('{business_name}', $messageSettings['business_name'], $footer);
    $footer = str_replace('{business_phone}', $messageSettings['business_phone'], $footer);
    $footer = str_replace('{business_address}', $messageSettings['business_address'], $footer);
    
    // Build message
    $message = '';
    if (!empty($header)) {
        $message .= $header . "\n\n";
    }
    $message .= $content;
    if (!empty($footer)) {
        $message .= "\n" . $footer;
    }
    
    return $message;
}

/**
 * Log webhook
 */
function logWebhook($data) {
    $logFile = '../logs/agent_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' => 'Agent webhook processed']);
