<?php
/**
 * Test Coin Deduction After Search
 * This file tests if coins are being properly deducted
 */

session_start();
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/Database.php';
require_once __DIR__ . '/classes/User.php';
require_once __DIR__ . '/classes/Search.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    die('❌ Not logged in. Please login first.');
}

$userId = $_SESSION['user_id'];
$db = Database::getInstance();
$user = new User($db);
$search = new Search($db, $user);

?>
<!DOCTYPE html>
<html>
<head>
    <title>Test Coin Deduction</title>
    <style>
        body { font-family: Arial; background: #f0f0f0; padding: 20px; }
        .container { max-width: 600px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; }
        .test-section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        .success { background: #d4edda; color: #155724; }
        .error { background: #f8d7da; color: #721c24; }
        .info { background: #d1ecf1; color: #0c5460; }
        h2 { color: #333; }
        pre { background: #f4f4f4; padding: 10px; overflow-x: auto; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧪 Coin Deduction Test</h1>
        
        <?php
        // Test 1: Check current balance
        echo '<div class="test-section info">';
        echo '<h2>Current Wallet Balance</h2>';
        $currentBalance = $user->getWalletBalance($userId);
        echo '<p><strong>User ID:</strong> ' . $userId . '</p>';
        echo '<p><strong>Current Balance:</strong> ₹' . number_format($currentBalance, 2) . '</p>';
        echo '</div>';
        
        // Test 2: Check admin settings
        echo '<div class="test-section info">';
        echo '<h2>Search Costs</h2>';
        echo '<p><strong>Mobile Search Cost:</strong> ₹' . MOBILE_SEARCH_COST . '</p>';
        echo '<p><strong>Aadhaar Search Cost:</strong> ₹' . AADHAAR_SEARCH_COST . '</p>';
        echo '</div>';
        
        // Test 3: Manual balance test
        if ($_POST['test_action'] ?? '' == 'test_deduction') {
            $testAmount = 10;
            echo '<div class="test-section">';
            echo '<h2>🧪 Testing Deduction (₹' . $testAmount . ')</h2>';
            echo '<p>Before: ₹' . number_format($currentBalance, 2) . '</p>';
            
            $result = $user->updateWalletBalance($userId, -$testAmount);
            
            $newBalance = $user->getWalletBalance($userId);
            echo '<p>After: ₹' . number_format($newBalance, 2) . '</p>';
            
            if ($result && ($newBalance == ($currentBalance - $testAmount))) {
                echo '<p class="success">✅ <strong>SUCCESS!</strong> Coins deducted properly!</p>';
                
                // Refund for next test
                $user->updateWalletBalance($userId, $testAmount);
            } else {
                echo '<p class="error">❌ <strong>FAILED!</strong> Coins were NOT deducted!</p>';
                echo '<p><strong>Expected:</strong> ₹' . number_format($currentBalance - $testAmount, 2) . '</p>';
                echo '<p><strong>Got:</strong> ₹' . number_format($newBalance, 2) . '</p>';
            }
            echo '</div>';
        }
        
        // Test 4: Check recent searches
        echo '<div class="test-section info">';
        echo '<h2>📊 Recent Searches (Last 5)</h2>';
        $searches = $user->getSearchHistory($userId, 5);
        if ($searches && count($searches) > 0) {
            echo '<table border="1" cellpadding="10" width="100%">';
            echo '<tr><th>Type</th><th>Query</th><th>Cost</th><th>Status</th><th>Date</th></tr>';
            foreach ($searches as $search_log) {
                echo '<tr>';
                echo '<td>' . ucfirst($search_log['type']) . '</td>';
                echo '<td>' . substr($search_log['query'], -4) . '****</td>';
                echo '<td>₹' . number_format($search_log['cost'] ?? 0, 2) . '</td>';
                echo '<td><strong>' . ucfirst($search_log['status']) . '</strong></td>';
                echo '<td>' . date('M d, H:i', strtotime($search_log['created_at'])) . '</td>';
                echo '</tr>';
            }
            echo '</table>';
        } else {
            echo '<p>No search history found.</p>';
        }
        echo '</div>';
        
        // Test form
        echo '<div class="test-section">';
        echo '<form method="POST">';
        echo '<input type="hidden" name="test_action" value="test_deduction">';
        echo '<button type="submit" style="padding: 10px 20px; font-size: 16px; cursor: pointer;">Test Coin Deduction (₹10)</button>';
        echo '</form>';
        echo '</div>';
        
        // Check error log
        echo '<div class="test-section info">';
        echo '<h2>📝 Debug Information</h2>';
        echo '<p><strong>Last Database Updates:</strong></p>';
        echo '<pre>';
        $errorLog = @file_get_contents(__DIR__ . '/../error_log');
        if ($errorLog) {
            $lines = explode("\n", $errorLog);
            $walletLines = array_filter($lines, function($line) {
                return stripos($line, 'WALLET') !== false;
            });
            $recent = array_slice($walletLines, -10);
            echo implode("\n", $recent);
        } else {
            echo 'No error log found.';
        }
        echo '</pre>';
        echo '</div>';
        ?>
    </div>
</body>
</html>
