<?php
/**
 * Kavenegar SMS Test Script
 * 
 * This script tests the Kavenegar SMS configuration and allows sending a test SMS.
 * Access via: http://yourdomain.com/test-kavenegar.php
 */

require __DIR__ . '/../vendor/autoload.php';

$app = require_once __DIR__ . '/../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

echo "<!DOCTYPE html>";
echo "<html><head><meta charset='UTF-8'><title>Kavenegar SMS Test</title>";
echo "<style>body{font-family:Arial;padding:20px;max-width:800px;margin:0 auto;}";
echo ".success{color:green;}.error{color:red;}.info{color:blue;}";
echo "input,button{padding:10px;margin:5px;font-size:14px;}";
echo "button{background:#556ee6;color:white;border:none;cursor:pointer;border-radius:4px;}";
echo "button:hover{background:#4a5fc1;}</style></head><body>";

echo "<h1>🔧 Kavenegar SMS Configuration Test</h1>";

// 1. Check DB Setting
$dbKey = \App\Settings::where('name', 'KavehnegarKey')->first();
echo "<h2>1. Database Setting</h2>";
if ($dbKey && !empty($dbKey->value)) {
    echo "<p class='success'>✅ API Key found in database: " . substr($dbKey->value, 0, 10) . "..." . substr($dbKey->value, -5) . "</p>";
} else {
    echo "<p class='error'>❌ API Key NOT found in database. Please set it in Admin Panel → Settings → API Settings → SMS & Notification</p>";
}

// 2. Check Config
$configKey = config('kavenegar.apikey');
echo "<h2>2. Configuration Value</h2>";
if ($configKey && !empty($configKey)) {
    echo "<p class='success'>✅ Config API Key: " . substr($configKey, 0, 10) . "..." . substr($configKey, -5) . "</p>";
} else {
    echo "<p class='error'>❌ Config API Key is empty</p>";
}

// 3. Check Match
echo "<h2>3. Configuration Match</h2>";
if ($dbKey && $configKey && $dbKey->value === $configKey) {
    echo "<p class='success'>✅ Database and Config match perfectly!</p>";
} else {
    echo "<p class='error'>❌ Mismatch detected. The override might not be working.</p>";
}

// 4. Check Kavenegar Class
echo "<h2>4. Kavenegar Package</h2>";
try {
    $kavenegar = app('kavenegar');
    echo "<p class='success'>✅ Kavenegar service is registered and available</p>";
    echo "<p class='info'>Class: " . get_class($kavenegar) . "</p>";
} catch (\Exception $e) {
    echo "<p class='error'>❌ Error: " . $e->getMessage() . "</p>";
}

// 5. Check Sender Number
echo "<h2>5. Sender Number</h2>";
$senderSetting = \App\Settings::where('name', 'KavehnegarSender')->first();
if ($senderSetting && !empty($senderSetting->value)) {
    echo "<p class='success'>✅ Sender found in database: <strong>" . $senderSetting->value . "</strong></p>";
} else {
    echo "<p class='error'>❌ Sender NOT found in database. Using default: <strong>10004346</strong></p>";
    echo "<p class='info'>Please set the sender number in Admin Panel → Settings → API Settings → SMS & Notification</p>";
}

// 6. Test Form
echo "<h2>6. Send Test SMS</h2>";
if (isset($_POST['send_test'])) {
    $mobile = $_POST['mobile'] ?? '';
    $code = rand(10000, 99999);
    
    if (empty($mobile)) {
        echo "<p class='error'>❌ Please enter a mobile number</p>";
    } else {
        try {
            // Use VerifyLookup method (requires template in Kavenegar panel)
            \Kavenegar::VerifyLookup($mobile, $code, null, null, 'VerifyMobile');
            
            echo "<p class='success'>✅ SMS sent successfully to $mobile</p>";
            echo "<p class='info'>Verification code: <strong>$code</strong></p>";
            echo "<p class='info'>Check your phone for the message.</p>";
        } catch (\Exception $e) {
            echo "<p class='error'>❌ SMS Failed: " . $e->getMessage() . "</p>";
            echo "<p class='info'>Common issues:</p>";
            echo "<ul>";
            echo "<li>Invalid API Key</li>";
            echo "<li>Insufficient credit in Kavenegar account</li>";
            echo "<li>Invalid mobile number format (must be 09xxxxxxxxx)</li>";
            echo "<li>Sender number not activated</li>";
            echo "</ul>";
        }
    }
}

echo "<form method='POST'>";
echo "<p><input type='text' name='mobile' placeholder='09xxxxxxxxx' pattern='09[0-9]{9}' required /></p>";
echo "<p><button type='submit' name='send_test'>Send Test SMS</button></p>";
echo "</form>";

echo "<hr>";
echo "<h2>📝 How to Create Template</h2>";
echo "<ol>";
echo "<li>Login to Kavenegar panel: <a href='https://panel.kavenegar.com' target='_blank'>panel.kavenegar.com</a></li>";
echo "<li>Go to <strong>اعتبارسنجی (Verification)</strong> section</li>";
echo "<li>Create a new template with name: <strong>VerifyMobile</strong></li>";
echo "<li>Template text: <code>کد تایید شما: %token%</code></li>";
echo "<li>Parameter: <strong>token</strong></li>";
echo "<li>Wait for template approval (usually takes a few minutes)</li>";
echo "</ol>";

echo "<h2>📝 Notes</h2>";
echo "<ul>";
echo "<li>This uses VerifyLookup method (Kavenegar service lines)</li>";
echo "<li>No custom sender number needed - uses Kavenegar's service lines</li>";
echo "<li>Faster delivery and automatic operator switching</li>";
echo "<li>Supports international SMS</li>";
echo "</ul>";

echo "</body></html>";
