<?php
/*
 * Test Agent Generate Voucher
 * Debug tool untuk cek kenapa generate voucher error
 */

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

echo "<h1>Agent Generate Voucher - Debug Test</h1>";
echo "<hr>";

// Test 1: Check Database Connection
echo "<h2>Test 1: Database Connection</h2>";
try {
    include('include/db_config.php');
    $conn = getDBConnection();
    if ($conn) {
        echo "✅ Database connected<br>";
    } else {
        echo "❌ Database connection failed<br>";
    }
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "<br>";
}

echo "<hr>";

// Test 2: Check Agent Class
echo "<h2>Test 2: Agent Class</h2>";
try {
    include('lib/Agent.class.php');
    $agent = new Agent();
    echo "✅ Agent class loaded<br>";
    
    // Get first agent
    $agents = $agent->getAllAgents();
    if (!empty($agents)) {
        $testAgent = $agents[0];
        echo "✅ Test Agent: " . $testAgent['agent_name'] . " (ID: " . $testAgent['id'] . ")<br>";
        echo "✅ Balance: Rp " . number_format($testAgent['balance'], 0, ',', '.') . "<br>";
        echo "✅ Status: " . $testAgent['status'] . "<br>";
    } else {
        echo "❌ No agents found. Create agent first!<br>";
    }
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "<br>";
}

echo "<hr>";

// Test 3: Check MikroTik Connection
echo "<h2>Test 3: MikroTik Connection</h2>";
try {
    include('include/config.php');
    include('lib/routeros_api.class.php');
    
    // Get first session
    $sessions = array_keys($data);
    $session = null;
    foreach ($sessions as $s) {
        if ($s != 'mikhmon') {
            $session = $s;
            break;
        }
    }
    
    if ($session) {
        echo "✅ Session found: $session<br>";
        
        $iphost = explode('!', $data[$session][1])[1];
        $userhost = explode('@|@', $data[$session][2])[1];
        $passwdhost = explode('#|#', $data[$session][3])[1];
        
        echo "✅ MikroTik IP: $iphost<br>";
        echo "✅ MikroTik User: $userhost<br>";
        
        $API = new RouterosAPI();
        $API->debug = false;
        
        if ($API->connect($iphost, $userhost, decrypt($passwdhost))) {
            echo "✅ Connected to MikroTik!<br>";
            
            // Get profiles
            $profiles = $API->comm("/ip/hotspot/user/profile/print");
            echo "✅ Profiles found: " . count($profiles) . "<br>";
            
            if (!empty($profiles)) {
                echo "<ul>";
                foreach ($profiles as $profile) {
                    if (isset($profile['name']) && $profile['name'] != 'default' && $profile['name'] != 'default-encryption') {
                        echo "<li>" . $profile['name'] . "</li>";
                    }
                }
                echo "</ul>";
            }
            
            $API->disconnect();
        } else {
            echo "❌ Failed to connect to MikroTik<br>";
        }
    } else {
        echo "❌ No MikroTik session found<br>";
        echo "<strong>Solution:</strong> Login to MikhMon admin and select a session first<br>";
    }
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "<br>";
}

echo "<hr>";

// Test 4: Check Agent Prices
echo "<h2>Test 4: Agent Prices</h2>";
if (isset($testAgent)) {
    try {
        $prices = $agent->getAllAgentPrices($testAgent['id']);
        if (!empty($prices)) {
            echo "✅ Prices configured: " . count($prices) . "<br>";
            echo "<table border='1' cellpadding='5'>";
            echo "<tr><th>Profile</th><th>Buy Price</th><th>Sell Price</th></tr>";
            foreach ($prices as $price) {
                echo "<tr>";
                echo "<td>" . $price['profile_name'] . "</td>";
                echo "<td>Rp " . number_format($price['buy_price'], 0, ',', '.') . "</td>";
                echo "<td>Rp " . number_format($price['sell_price'], 0, ',', '.') . "</td>";
                echo "</tr>";
            }
            echo "</table>";
        } else {
            echo "❌ No prices configured<br>";
            echo "<strong>Solution:</strong> Set prices in admin panel: Settings → Agent/Reseller → Kelola Harga<br>";
        }
    } catch (Exception $e) {
        echo "❌ Error: " . $e->getMessage() . "<br>";
    }
}

echo "<hr>";

// Test 5: Simulate Generate
echo "<h2>Test 5: Simulate Generate Voucher</h2>";
if (isset($testAgent) && !empty($prices) && $session) {
    echo "<form method='POST' action='api/agent_generate_voucher.php' target='_blank'>";
    echo "<input type='hidden' name='agent_id' value='" . $testAgent['id'] . "'>";
    echo "<input type='hidden' name='agent_token' value='" . md5($testAgent['id'] . $testAgent['phone']) . "'>";
    
    echo "<label>Profile:</label><br>";
    echo "<select name='profile' required>";
    foreach ($prices as $price) {
        echo "<option value='" . $price['profile_name'] . "'>" . $price['profile_name'] . " (Rp " . number_format($price['buy_price'], 0, ',', '.') . ")</option>";
    }
    echo "</select><br><br>";
    
    echo "<label>Quantity:</label><br>";
    echo "<input type='number' name='quantity' value='1' min='1' max='10'><br><br>";
    
    echo "<label>Customer Phone (optional):</label><br>";
    echo "<input type='text' name='customer_phone' placeholder='08123456789'><br><br>";
    
    echo "<label>Customer Name (optional):</label><br>";
    echo "<input type='text' name='customer_name' placeholder='Customer Name'><br><br>";
    
    echo "<button type='submit' style='padding: 10px 20px; background: #667eea; color: white; border: none; border-radius: 5px; cursor: pointer;'>Test Generate Voucher</button>";
    echo "</form>";
} else {
    echo "❌ Cannot simulate. Fix issues above first.<br>";
}

echo "<hr>";

// Summary
echo "<h2>Summary & Solutions</h2>";
echo "<div style='background: #f0f9ff; padding: 15px; border-left: 4px solid #3b82f6; margin: 10px 0;'>";
echo "<strong>Common Issues:</strong><br><br>";
echo "1. <strong>No agents found</strong><br>";
echo "   → Create agent: Settings → Agent/Reseller → Tambah Agent<br><br>";
echo "2. <strong>No prices configured</strong><br>";
echo "   → Set prices: Settings → Agent/Reseller → Kelola Harga<br><br>";
echo "3. <strong>MikroTik not connected</strong><br>";
echo "   → Login to MikhMon admin and select session<br><br>";
echo "4. <strong>Balance insufficient</strong><br>";
echo "   → Topup agent: Settings → Agent/Reseller → Topup Saldo<br><br>";
echo "5. <strong>Session not found</strong><br>";
echo "   → Login to MikhMon admin first<br><br>";
echo "</div>";

echo "<div style='margin-top: 20px;'>";
echo "<a href='agent/dashboard.php' style='padding: 10px 20px; background: #10b981; color: white; text-decoration: none; border-radius: 5px; margin-right: 10px;'>Open Agent Panel</a>";
echo "<a href='index.php' style='padding: 10px 20px; background: #667eea; color: white; text-decoration: none; border-radius: 5px;'>Open MikhMon Admin</a>";
echo "</div>";
?>
