<?php
/**
 * Debug manual approval and rejection system
 */

include_once 'config.php';

header('Content-Type: text/html; charset=UTF-8');

echo "<html dir='rtl'><head><meta charset='UTF-8'><style>
body { font-family: Tahoma; padding: 20px; line-height: 2; background: #f3f4f6; }
.box { background: white; padding: 20px; margin: 15px 0; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
h2 { color: #2563eb; border-bottom: 2px solid #2563eb; padding-bottom: 10px; }
code { background: #1f2937; color: #10b981; padding: 5px 10px; border-radius: 5px; display: inline-block; }
.success { color: #10b981; font-weight: bold; }
.error { color: #ef4444; font-weight: bold; }
table { width: 100%; border-collapse: collapse; margin: 15px 0; }
th, td { padding: 12px; text-align: right; border: 1px solid #e5e7eb; }
th { background: #2563eb; color: white; }
tr:hover { background: #f9fafb; }
</style></head><body>";

echo "<h1>🔍 Debug سیستم تایید و رد</h1>";

// Test 1: Check temp_service_purchases
echo "<div class='box'>";
echo "<h2>1️⃣ بررسی جدول temp_service_purchases</h2>";

$result = $connection->query("SELECT tsp.*, sp.name as plan_name, u.firstname, u.userid 
                               FROM `temp_service_purchases` tsp
                               LEFT JOIN `service_plans` sp ON tsp.plan_id = sp.id
                               LEFT JOIN `users` u ON tsp.user_id = u.userid
                               ORDER BY tsp.created_at DESC LIMIT 5");

if($result && $result->num_rows > 0){
    echo "<p class='success'>✅ یافت شد: {$result->num_rows} رکورد</p>";
    echo "<table>";
    echo "<tr><th>Hash ID</th><th>User ID</th><th>نام کاربر</th><th>پلن</th><th>تاریخ</th></tr>";
    while($row = $result->fetch_assoc()){
        echo "<tr>";
        echo "<td><code>{$row['hash_id']}</code></td>";
        echo "<td>{$row['user_id']}</td>";
        echo "<td>{$row['firstname']}</td>";
        echo "<td>{$row['plan_name']}</td>";
        echo "<td>{$row['created_at']}</td>";
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo "<p class='error'>❌ هیچ رکوردی یافت نشد</p>";
}
echo "</div>";

// Test 2: Check users table structure
echo "<div class='box'>";
echo "<h2>2️⃣ بررسی ساختار جدول users</h2>";

$columns = $connection->query("SHOW COLUMNS FROM `users`");
echo "<table>";
echo "<tr><th>ستون</th><th>نوع</th><th>Null?</th><th>Key</th></tr>";
while($col = $columns->fetch_assoc()){
    echo "<tr>";
    echo "<td><code>{$col['Field']}</code></td>";
    echo "<td>{$col['Type']}</td>";
    echo "<td>{$col['Null']}</td>";
    echo "<td>{$col['Key']}</td>";
    echo "</tr>";
}
echo "</table>";
echo "</div>";

// Test 3: Check service_orders structure  
echo "<div class='box'>";
echo "<h2>3️⃣ بررسی ساختار جدول service_orders</h2>";

$columns = $connection->query("SHOW COLUMNS FROM `service_orders`");
if($columns){
    echo "<table>";
    echo "<tr><th>ستون</th><th>نوع</th><th>Null?</th><th>Key</th></tr>";
    while($col = $columns->fetch_assoc()){
        echo "<tr>";
        echo "<td><code>{$col['Field']}</code></td>";
        echo "<td>{$col['Type']}</td>";
        echo "<td>{$col['Null']}</td>";
        echo "<td>{$col['Key']}</td>";
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo "<p class='error'>❌ جدول وجود ندارد</p>";
}
echo "</div>";

// Test 4: Test user lookup
echo "<div class='box'>";
echo "<h2>4️⃣ تست دریافت اطلاعات کاربر</h2>";

// Get a user from temp_service_purchases
$test_user = $connection->query("SELECT user_id FROM `temp_service_purchases` LIMIT 1");
if($test_user && $test_user->num_rows > 0){
    $user_id = $test_user->fetch_assoc()['user_id'];
    
    echo "<p>تست با user_id: <code>{$user_id}</code></p>";
    
    // Try with userid
    $stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if($user){
        echo "<p class='success'>✅ کاربر با userid یافت شد:</p>";
        echo "<ul>";
        echo "<li>نام: {$user['firstname']}</li>";
        echo "<li>userid: {$user['userid']}</li>";
        if(isset($user['id'])) echo "<li>id: {$user['id']}</li>";
        echo "<li>step: {$user['step']}</li>";
        echo "</ul>";
    } else {
        echo "<p class='error'>❌ کاربر یافت نشد</p>";
    }
} else {
    echo "<p class='error'>❌ هیچ user_id برای تست یافت نشد</p>";
}
echo "</div>";

// Test 5: Test regex patterns
echo "<div class='box'>";
echo "<h2>5️⃣ تست Regex Patterns</h2>";

$test_steps = [
    'waitingManualConfig_abc123_123456_1',
    'waitingRejectReason_abc123_123456',
    'waitingManualConfig_ABC123def_456789_2',
    'none'
];

echo "<table>";
echo "<tr><th>Step</th><th>Manual Pattern</th><th>Reject Pattern</th></tr>";

foreach($test_steps as $step){
    $manual_match = preg_match('/^waitingManualConfig_([a-zA-Z0-9]+)_(\d+)_(\d+)$/', $step, $manual_matches);
    $reject_match = preg_match('/^waitingRejectReason_([a-zA-Z0-9]+)_(\d+)$/', $step, $reject_matches);
    
    echo "<tr>";
    echo "<td><code>{$step}</code></td>";
    echo "<td>" . ($manual_match ? "<span class='success'>✅ Match</span>" : "❌ No match") . "</td>";
    echo "<td>" . ($reject_match ? "<span class='success'>✅ Match</span>" : "❌ No match") . "</td>";
    echo "</tr>";
}
echo "</table>";
echo "</div>";

// Test 6: Simulate handler check
echo "<div class='box'>";
echo "<h2>6️⃣ شبیه‌سازی Handler</h2>";

// Get admin from baseInfo
echo "<p>Admin ID: <code>{$admin}</code></p>";

// Simulate a manual config step
$simulated_step = 'waitingManualConfig_abc123_' . $admin . '_1';
$simulated_text = 'http://test.com/config';
$simulated_from_id = $admin;

echo "<p>Simulated scenario:</p>";
echo "<ul>";
echo "<li>Step: <code>{$simulated_step}</code></li>";
echo "<li>Text: <code>{$simulated_text}</code></li>";
echo "<li>From ID: <code>{$simulated_from_id}</code></li>";
echo "</ul>";

$manual_matches = [];
$will_match = preg_match('/^waitingManualConfig_([a-zA-Z0-9]+)_(\d+)_(\d+)$/', $simulated_step, $manual_matches);
$is_admin = ($simulated_from_id == $admin);
$has_text = !empty($simulated_text);

echo "<p>شرایط handler:</p>";
echo "<ul>";
echo "<li>Regex match: " . ($will_match ? "<span class='success'>✅ True</span>" : "<span class='error'>❌ False</span>") . "</li>";
echo "<li>Is admin: " . ($is_admin ? "<span class='success'>✅ True</span>" : "<span class='error'>❌ False</span>") . "</li>";
echo "<li>Has text: " . ($has_text ? "<span class='success'>✅ True</span>" : "<span class='error'>❌ False</span>") . "</li>";
echo "<li><strong>Handler will run: " . ($will_match && $is_admin && $has_text ? "<span class='success'>✅ YES</span>" : "<span class='error'>❌ NO</span>") . "</strong></li>";
echo "</ul>";

if($will_match){
    echo "<p>Captured groups:</p>";
    echo "<ul>";
    echo "<li>Hash ID: <code>{$manual_matches[1]}</code></li>";
    echo "<li>Customer ID: <code>{$manual_matches[2]}</code></li>";
    echo "<li>Plan ID: <code>{$manual_matches[3]}</code></li>";
    echo "</ul>";
}
echo "</div>";

// Test 7: Check error log
echo "<div class='box'>";
echo "<h2>7️⃣ لاگ‌های اخیر (اگر موجود باشد)</h2>";

$log_file = ini_get('error_log');
if($log_file && file_exists($log_file)){
    echo "<p>فایل لاگ: <code>{$log_file}</code></p>";
    $lines = file($log_file);
    $recent = array_slice($lines, -20);
    echo "<pre style='background: #1f2937; color: #10b981; padding: 15px; border-radius: 10px; overflow-x: auto;'>";
    foreach($recent as $line){
        if(strpos($line, 'Manual Config') !== false || strpos($line, 'Reject Handler') !== false){
            echo htmlspecialchars($line);
        }
    }
    echo "</pre>";
} else {
    echo "<p class='error'>❌ فایل لاگ یافت نشد</p>";
    echo "<p>لاگ‌ها در error_log پیش‌فرض PHP ذخیره می‌شوند</p>";
}
echo "</div>";

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