<?php
/**
 * DonyayeGame API Test Script
 * 
 * This script helps test the API endpoints. 
 * Make sure to replace YOUR_API_TOKEN with your actual token.
 * 
 * Usage: Place this file in your plugin directory and access it via browser
 * or run from command line: php test-api.php
 */

// Prevent direct access if not in WordPress context
if (!defined('ABSPATH')) {
    // If running standalone, try to load WordPress
    $wp_load = dirname(__FILE__) . '/../../../wp-load.php';
    if (file_exists($wp_load)) {
        require_once $wp_load;
    } else {
        die('WordPress not found. Please place this file in the correct location.');
    }
}

// Configuration
$api_token = 'YOUR_API_TOKEN'; // Replace with your actual token
$base_url = rest_url('donyaye-game/v1/');

// Test data
$test_customer = array(
    'id' => 1001,
    'name' => 'تست',
    'surname' => 'کاربر',
    'gender' => 1,
    'national_code' => '1234567890',
    'mobile_number' => '09123456789',
    'date_of_birth' => '1990-01-01',
    'image' => '',
    'balance' => 50000,
    'membership_date' => date('Y-m-d'),
    'last_entry_date' => date('c'),
    'is_active' => 1,
    'created_date' => date('c'),
    'modified_date' => date('c')
);

$test_transaction = array(
    'id' => 2001,
    'customer_id' => 1001,
    'amount' => 25000,
    'type' => 1,
    'previous_balance' => 50000,
    'new_balance' => 75000,
    'transaction_date' => date('c'),
    'description' => 'Test transaction sync',
    'card_number' => '1234-5678-9012-3456',
    'transaction_number' => 'TXN_' . time(),
    'track_no' => 'TRK_' . time(),
    'resp_code' => '00',
    'resp_message' => 'Approved',
    'terminal_number' => 'TERM001',
    'reference_number' => 'REF_' . time(),
    'is_online_transaction' => 0,
    'is_successful' => 1,
    'created_by' => 'API_TEST',
    'created_date' => date('c'),
    'modified_date' => date('c')
);

// Helper function to make API requests
function make_api_request($url, $method = 'GET', $data = null) {
    $ch = curl_init();
    
    $headers = array(
        'Content-Type: application/json',
        'X-API-Token: ' . $GLOBALS['api_token']
    );
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
    } elseif ($method === 'PUT') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
    }
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        return array('error' => $error, 'http_code' => 0);
    }
    
    return array(
        'response' => $response,
        'http_code' => $http_code,
        'decoded' => json_decode($response, true)
    );
}

// Test functions
function test_customer_registration() {
    global $base_url, $test_customer;
    
    echo "<h3>Testing Customer Registration</h3>";
    echo "<p><strong>Endpoint:</strong> POST {$base_url}customer/register</p>";
    echo "<p><strong>Data:</strong> " . json_encode($test_customer, JSON_UNESCAPED_UNICODE) . "</p>";
    
    $result = make_api_request($base_url . 'customer/register', 'POST', $test_customer);
    
    if (isset($result['error'])) {
        echo "<p style='color: red;'><strong>Error:</strong> " . $result['error'] . "</p>";
        return false;
    }
    
    echo "<p><strong>HTTP Code:</strong> " . $result['http_code'] . "</p>";
    echo "<p><strong>Response:</strong> " . $result['response'] . "</p>";
    
    if ($result['http_code'] === 201) {
        echo "<p style='color: green;'><strong>✓ Customer registration successful!</strong></p>";
        return true;
    } else {
        echo "<p style='color: red;'><strong>✗ Customer registration failed!</strong></p>";
        return false;
    }
}

function test_transaction_sync() {
    global $base_url, $test_transaction;
    
    echo "<h3>Testing Transaction Sync</h3>";
    echo "<p><strong>Endpoint:</strong> POST {$base_url}transaction/sync</p>";
    echo "<p><strong>Data:</strong> " . json_encode($test_transaction, JSON_UNESCAPED_UNICODE) . "</p>";
    
    $result = make_api_request($base_url . 'transaction/sync', 'POST', $test_transaction);
    
    if (isset($result['error'])) {
        echo "<p style='color: red;'><strong>Error:</strong> " . $result['error'] . "</p>";
        return false;
    }
    
    echo "<p><strong>HTTP Code:</strong> " . $result['http_code'] . "</p>";
    echo "<p><strong>Response:</strong> " . $result['response'] . "</p>";
    
    if ($result['http_code'] === 201) {
        echo "<p style='color: green;'><strong>✓ Transaction sync successful!</strong></p>";
        return true;
    } else {
        echo "<p style='color: red;'><strong>✗ Transaction sync failed!</strong></p>";
        return false;
    }
}

function test_get_users() {
    global $base_url;
    
    echo "<h3>Testing Get Users</h3>";
    echo "<p><strong>Endpoint:</strong> GET {$base_url}users?per_page=5&page=1</p>";
    
    $result = make_api_request($base_url . 'users?per_page=5&page=1');
    
    if (isset($result['error'])) {
        echo "<p style='color: red;'><strong>Error:</strong> " . $result['error'] . "</p>";
        return false;
    }
    
    echo "<p><strong>HTTP Code:</strong> " . $result['http_code'] . "</p>";
    echo "<p><strong>Response:</strong> " . $result['response'] . "</p>";
    
    if ($result['http_code'] === 200) {
        echo "<p style='color: green;'><strong>✓ Get users successful!</strong></p>";
        return true;
    } else {
        echo "<p style='color: red;'><strong>✗ Get users failed!</strong></p>";
        return false;
    }
}

function test_get_user_by_mobile() {
    global $base_url, $test_customer;
    
    echo "<h3>Testing Get User by Mobile</h3>";
    echo "<p><strong>Endpoint:</strong> GET {$base_url}user/{$test_customer['mobile']}</p>";
    
    $result = make_api_request($base_url . 'user/' . $test_customer['mobile']);
    
    if (isset($result['error'])) {
        echo "<p style='color: red;'><strong>Error:</strong> " . $result['error'] . "</p>";
        return false;
    }
    
    echo "<p><strong>HTTP Code:</strong> " . $result['http_code'] . "</p>";
    echo "<p><strong>Response:</strong> " . $result['response'] . "</p>";
    
    if ($result['http_code'] === 200) {
        echo "<p style='color: green;'><strong>✓ Get user successful!</strong></p>";
        return true;
    } else {
        echo "<p style='color: red;'><strong>✗ Get user failed!</strong></p>";
        return false;
    }
}

function test_update_user() {
    global $base_url, $test_customer;
    
    $update_data = array(
        'first_name' => 'تست بروزرسانی',
        'last_name' => 'کاربر بروزرسانی'
    );
    
    echo "<h3>Testing Update User</h3>";
    echo "<p><strong>Endpoint:</strong> PUT {$base_url}user/{$test_customer['mobile']}</p>";
    echo "<p><strong>Data:</strong> " . json_encode($update_data, JSON_UNESCAPED_UNICODE) . "</p>";
    
    $result = make_api_request($base_url . 'user/' . $test_customer['mobile'], 'PUT', $update_data);
    
    if (isset($result['error'])) {
        echo "<p style='color: red;'><strong>Error:</strong> " . $result['error'] . "</p>";
        return false;
    }
    
    echo "<p><strong>HTTP Code:</strong> " . $result['http_code'] . "</p>";
    echo "<p><strong>Response:</strong> " . $result['response'] . "</p>";
    
    if ($result['http_code'] === 200) {
        echo "<p style='color: green;'><strong>✓ Update user successful!</strong></p>";
        return true;
    } else {
        echo "<p style='color: red;'><strong>✗ Update user failed!</strong></p>";
        return false;
    }
}

function test_get_halls() {
    global $base_url;
    
    echo "<h3>Testing Get Game Halls</h3>";
    echo "<p><strong>Endpoint:</strong> GET {$base_url}halls?per_page=5&page=1</p>";
    
    $result = make_api_request($base_url . 'halls?per_page=5&page=1');
    
    if (isset($result['error'])) {
        echo "<p style='color: red;'><strong>Error:</strong> " . $result['error'] . "</p>";
        return false;
    }
    
    echo "<p><strong>HTTP Code:</strong> " . $result['http_code'] . "</p>";
    echo "<p><strong>Response:</strong> " . $result['response'] . "</p>";
    
    if ($result['http_code'] === 200) {
        echo "<p style='color: green;'><strong>✓ Get game halls successful!</strong></p>";
        return true;
    } else {
        echo "<p style='color: red;'><strong>✗ Get game halls failed!</strong></p>";
        return false;
    }
}

function test_get_reservations() {
    global $base_url;
    
    echo "<h3>Testing Get Reservations</h3>";
    echo "<p><strong>Endpoint:</strong> GET {$base_url}reservations?per_page=5&page=1</p>";
    
    $result = make_api_request($base_url . 'reservations?per_page=5&page=1');
    
    if (isset($result['error'])) {
        echo "<p style='color: red;'><strong>Error:</strong> " . $result['error'] . "</p>";
        return false;
    }
    
    echo "<p><strong>HTTP Code:</strong> " . $result['http_code'] . "</p>";
    echo "<p><strong>Response:</strong> " . $result['response'] . "</p>";
    
    if ($result['http_code'] === 200) {
        echo "<p style='color: green;'><strong>✓ Get reservations successful!</strong></p>";
        return true;
    } else {
        echo "<p style='color: red;'><strong>✗ Get reservations failed!</strong></p>";
        return false;
    }
}

// Main test execution
if (php_sapi_name() === 'cli') {
    // Command line execution
    echo "DonyayeGame API Test Script\n";
    echo "===========================\n\n";
    
    if ($api_token === 'YOUR_API_TOKEN') {
        echo "ERROR: Please update the API token in this script before running!\n";
        exit(1);
    }
    
    echo "Testing API endpoints...\n\n";
    
    test_customer_registration();
    echo "\n";
    
    test_transaction_sync();
    echo "\n";
    
    test_get_users();
    echo "\n";
    
    test_get_user_by_mobile();
    echo "\n";
    
    test_update_user();
    echo "\n";
    
    echo "Test completed!\n";
    
} else {
    // Web browser execution
    ?>
    <!DOCTYPE html>
    <html dir="rtl" lang="fa">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>DonyayeGame API Test</title>
        <style>
            body { font-family: Tahoma, Arial, sans-serif; margin: 20px; background: #f5f5f5; }
            .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
            h1 { color: #2c3e50; text-align: center; border-bottom: 3px solid #3498db; padding-bottom: 10px; }
            h3 { color: #34495e; border-right: 4px solid #3498db; padding-right: 10px; }
            p { line-height: 1.6; margin: 10px 0; }
            .warning { background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 5px; margin: 20px 0; }
            .warning strong { color: #856404; }
            .endpoint { background: #f8f9fa; padding: 10px; border-radius: 5px; font-family: monospace; margin: 10px 0; }
            .success { color: #155724; }
            .error { color: #721c24; }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>🧪 DonyayeGame API Test Script</h1>
            
            <div class="warning">
                <strong>⚠️ Important:</strong> 
                Before running tests, make sure to update the <code>$api_token</code> variable in this script with your actual API token!
            </div>
            
            <?php if ($api_token === 'YOUR_API_TOKEN'): ?>
                <div class="warning">
                    <strong>❌ Configuration Error:</strong> 
                    Please update the API token in the script before running tests.
                </div>
            <?php else: ?>
                <p><strong>API Token:</strong> <?php echo substr($api_token, 0, 10) . '...'; ?></p>
                <p><strong>Base URL:</strong> <span class="endpoint"><?php echo $base_url; ?></span></p>
                
                <hr>
                
                <?php
                test_customer_registration();
                echo '<hr>';
                test_transaction_sync();
                echo '<hr>';
                test_get_users();
                echo '<hr>';
                test_get_user_by_mobile();
                echo '<hr>';
                    test_update_user();
    
    // Test new endpoints
    test_get_halls();
    test_get_reservations();
    ?>
    
    <hr>
    <p><strong>Test completed!</strong> Check the results above to verify your API endpoints are working correctly.</p>
            <?php endif; ?>
        </div>
    </body>
    </html>
    <?php
}
?> 