<?php
// Test script to simulate PhonePe webhook and create test transactions
// URL: https://astro.siddharthnahar.in/astro_admin/test_payment_webhook.php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(0);

require_once '../config/database.php';

// Function to create test payment record
function createTestPayment($transactionId, $amount, $status = 'SUCCESS') {
    try {
        $pdo = getDBConnection();
        
        // Create test payment record
        $stmt = $pdo->prepare("
            INSERT INTO payments (
                transaction_id, 
                amount, 
                status, 
                payment_method, 
                phonepe_response,
                created_at
            ) VALUES (?, ?, ?, 'PHONEPE', ?, NOW())
            ON DUPLICATE KEY UPDATE
                status = VALUES(status),
                phonepe_response = VALUES(phonepe_response),
                updated_at = NOW()
        ");
        
        $phonepeResponse = json_encode([
            'test' => true,
            'transactionId' => $transactionId,
            'amount' => $amount,
            'status' => $status,
            'timestamp' => time()
        ]);
        
        $result = $stmt->execute([
            $transactionId,
            $amount,
            $status,
            $phonepeResponse
        ]);
        
        return $result;
    } catch (Exception $e) {
        error_log("Test payment creation error: " . $e->getMessage());
        return false;
    }
}

// Function to simulate webhook call
function simulateWebhook($transactionId, $amount, $status = 'SUCCESS') {
    $webhookUrl = 'https://astro.siddharthnahar.in/astro_admin/api/phonepe_v2_backend.php/webhook';
    
    $webhookData = [
        'code' => $status === 'SUCCESS' ? 'PAYMENT_SUCCESS' : 'PAYMENT_ERROR',
        'state' => $status === 'SUCCESS' ? 'COMPLETED' : 'FAILED',
        'data' => [
            'merchantOrderId' => $transactionId,
            'transactionId' => $transactionId,
            'amount' => $amount
        ]
    ];
    
    $ch = curl_init($webhookUrl);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS => json_encode($webhookData),
        CURLOPT_TIMEOUT => 30
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    return [
        'success' => $httpCode === 200,
        'httpCode' => $httpCode,
        'response' => $response,
        'error' => $error
    ];
}

// Handle different actions
$action = $_GET['action'] ?? 'create';

switch ($action) {
    case 'create':
        // Create test transactions
        $testTransactions = [
            ['id' => 'TEST-SUCCESS-001', 'amount' => 100, 'status' => 'SUCCESS'],
            ['id' => 'TEST-SUCCESS-002', 'amount' => 200, 'status' => 'SUCCESS'],
            ['id' => 'TEST-FAILED-001', 'amount' => 150, 'status' => 'FAILED'],
            ['id' => 'TEST-PENDING-001', 'amount' => 300, 'status' => 'PENDING'],
        ];
        
        $results = [];
        foreach ($testTransactions as $txn) {
            $result = createTestPayment($txn['id'], $txn['amount'], $txn['status']);
            $results[] = [
                'transactionId' => $txn['id'],
                'amount' => $txn['amount'],
                'status' => $txn['status'],
                'created' => $result
            ];
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Test transactions created',
            'transactions' => $results,
            'total' => count($results)
        ]);
        break;
        
    case 'webhook':
        // Simulate webhook calls
        $testTransactions = [
            ['id' => 'WEBHOOK-SUCCESS-001', 'amount' => 500, 'status' => 'SUCCESS'],
            ['id' => 'WEBHOOK-SUCCESS-002', 'amount' => 750, 'status' => 'SUCCESS'],
        ];
        
        $results = [];
        foreach ($testTransactions as $txn) {
            $result = simulateWebhook($txn['id'], $txn['amount'], $txn['status']);
            $results[] = [
                'transactionId' => $txn['id'],
                'amount' => $txn['amount'],
                'status' => $txn['status'],
                'webhookResult' => $result
            ];
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Webhook simulation completed',
            'webhookResults' => $results
        ]);
        break;
        
    case 'list':
        // List all payments
        try {
            $pdo = getDBConnection();
            $stmt = $pdo->prepare("
                SELECT 
                    transaction_id,
                    amount,
                    status,
                    payment_method,
                    created_at,
                    updated_at
                FROM payments 
                ORDER BY created_at DESC 
                LIMIT 20
            ");
            $stmt->execute();
            $payments = $stmt->fetchAll();
            
            echo json_encode([
                'success' => true,
                'message' => 'Payments retrieved',
                'payments' => $payments,
                'count' => count($payments)
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
        break;
        
    case 'clear':
        // Clear test transactions
        try {
            $pdo = getDBConnection();
            $stmt = $pdo->prepare("DELETE FROM payments WHERE transaction_id LIKE 'TEST-%' OR transaction_id LIKE 'WEBHOOK-%'");
            $stmt->execute();
            $deleted = $stmt->rowCount();
            
            echo json_encode([
                'success' => true,
                'message' => 'Test transactions cleared',
                'deleted' => $deleted
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
        break;
        
    case 'recent':
        // Get recent successful payments
        try {
            $pdo = getDBConnection();
            $stmt = $pdo->prepare("
                SELECT 
                    transaction_id,
                    amount,
                    status,
                    created_at
                FROM payments 
                WHERE status = 'SUCCESS' 
                AND created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
                ORDER BY created_at DESC
            ");
            $stmt->execute();
            $recentPayments = $stmt->fetchAll();
            
            echo json_encode([
                'success' => true,
                'message' => 'Recent successful payments',
                'payments' => $recentPayments,
                'count' => count($recentPayments)
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
        break;
        
    default:
        echo json_encode([
            'success' => true,
            'message' => 'PhonePe Test Script',
            'actions' => [
                'create' => 'Create test transactions',
                'webhook' => 'Simulate webhook calls',
                'list' => 'List all payments',
                'clear' => 'Clear test transactions',
                'recent' => 'Get recent successful payments'
            ],
            'usage' => [
                'Create test transactions: ?action=create',
                'Simulate webhook: ?action=webhook',
                'List payments: ?action=list',
                'Clear test data: ?action=clear',
                'Recent payments: ?action=recent'
            ]
        ]);
        break;
}
?>
