<?php
/**
 * UPI API Test Script
 * Tests database connection and configuration
 */

session_start();

// Database connection
require_once __DIR__ . '/config/db.php';


echo "2. Checking UPI Tables...\n";
$tables = ['upi_transactions', 'upi_config', 'upi_payment_logs'];
foreach ($tables as $table) {
    $result = $conn->query("SHOW TABLES LIKE '$table'");
    if ($result && $result->num_rows > 0) {
        echo "✅ Table '$table' exists\n";
    } else {
        echo "❌ Table '$table' NOT found\n";
    }
}
echo "\n";

echo "3. Testing getConfigValue Function...\n";
function getConfigValue($key, $default = '') {
    global $conn;
    
    $stmt = $conn->prepare("SELECT value FROM upi_config WHERE `key` = ?");
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    
    $stmt->bind_param("s", $key);
    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }
    
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();
    
    return $row ? $row['value'] : $default;
}

try {
    $merchant_upi = getConfigValue('UPI_ID', '9876543210@okhdfcbank');
    $merchant_name = getConfigValue('MERCHANT_NAME', 'Interior Design Store');
    echo "✅ Merchant UPI: " . $merchant_upi . "\n";
    echo "✅ Merchant Name: " . $merchant_name . "\n\n";
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n\n";
    exit;
}

echo "4. Testing INSERT into upi_transactions...\n";
$user_id = 1; // Test user
$transaction_ref = 'TEST-' . time();
$amount = 100.00;
$upi_string = 'upi://pay?pa=test@okhdfcbank&pn=Test&am=100&tn=Test&tr=REF';
$qr_code_url = 'https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=test';

$stmt = $conn->prepare("
    INSERT INTO upi_transactions (user_id, transaction_ref, amount, upi_string, qr_code_url, status, created_at)
    VALUES (?, ?, ?, ?, ?, 'pending', NOW())
");

if (!$stmt) {
    echo "❌ Prepare failed: " . $conn->error . "\n";
    exit;
}

$stmt->bind_param("isdss", $user_id, $transaction_ref, $amount, $upi_string, $qr_code_url);

if (!$stmt->execute()) {
    echo "❌ Execute failed: " . $stmt->error . "\n";
    exit;
}

$transaction_id = $conn->insert_id;
echo "✅ Transaction inserted with ID: " . $transaction_id . "\n";
echo "✅ Transaction Ref: " . $transaction_ref . "\n\n";

echo "5. Testing SELECT from upi_transactions...\n";
$stmt = $conn->prepare("SELECT * FROM upi_transactions WHERE id = ?");
$stmt->bind_param("i", $transaction_id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if ($row) {
    echo "✅ Transaction found:\n";
    echo "   ID: " . $row['id'] . "\n";
    echo "   Ref: " . $row['transaction_ref'] . "\n";
    echo "   Amount: " . $row['amount'] . "\n";
    echo "   Status: " . $row['status'] . "\n";
} else {
    echo "❌ Transaction not found\n";
}

echo "\n✅ All tests passed!\n";

$conn->close();
?>
