<?php
session_start();
require_once 'includes/database.php';

// Verify Flutterwave payment
if(isset($_GET['transaction_id']) && isset($_GET['tx_ref'])) {
    $transaction_id = $_GET['transaction_id'];
    $tx_ref = $_GET['tx_ref'];
    
    // Verify with Flutterwave
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => "https://api.flutterwave.com/v3/transactions/{$transaction_id}/verify",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer YOUR_FLUTTERWAVE_SECRET_KEY",
            "Content-Type: application/json"
        ]
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    
    if (!$err) {
        $response_data = json_decode($response, true);
        
        if($response_data['status'] === 'success' && $response_data['data']['status'] === 'successful') {
            // Payment successful
            $tx_ref = $response_data['data']['tx_ref'];
            $amount = $response_data['data']['amount'];
            
            // Get transaction details
            $stmt = $pdo->prepare("SELECT * FROM payment_transactions WHERE flutterwave_ref = ?");
            $stmt->execute([$tx_ref]);
            $transaction = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if($transaction && $transaction['status'] === 'pending') {
                $pdo->beginTransaction();
                
                try {
                    // Update transaction status
                    $stmt = $pdo->prepare("UPDATE payment_transactions SET status = 'completed' WHERE id = ?");
                    $stmt->execute([$transaction['id']]);
                    
                    // Add coins to user wallet
                    $stmt = $pdo->prepare("INSERT INTO user_wallets (user_id, balance) VALUES (?, ?) ON DUPLICATE KEY UPDATE balance = balance + ?");
                    $stmt->execute([$transaction['user_id'], $transaction['amount_coins'], $transaction['amount_coins']]);
                    
                    // Record transaction
                    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'purchase', ?, ?)");
                    $stmt->execute([
                        $transaction['user_id'], 
                        $transaction['amount_coins'],
                        "Coin purchase - {$transaction['amount_zmw']} ZMW"
                    ]);
                    
                    $pdo->commit();
                    
                    $_SESSION['success'] = "Payment successful! {$transaction['amount_coins']} ZIT Coins added to your wallet.";
                    header('Location: wallet.php');
                    exit;
                    
                } catch(Exception $e) {
                    $pdo->rollBack();
                    $_SESSION['error'] = "Error processing payment: " . $e->getMessage();
                    header('Location: wallet.php');
                    exit;
                }
            }
        }
    }
    
    $_SESSION['error'] = "Payment verification failed!";
    header('Location: wallet.php');
    exit;
}