<?php
header('Content-Type: application/json');
session_start();
require_once '../configs.php';
require_once 'KamiPayAPI.php';

// Verificar que sea una petición POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit();
}

// Obtener datos JSON
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['operation_id']) || !isset($input['external_ref'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing required parameters']);
    exit();
}

$operation_id = $input['operation_id'];
$external_ref = $input['external_ref'];

try {
    // Obtener transacción de la base de datos
    $stmt = $pdo->prepare("SELECT * FROM kamipay_transactions WHERE operation_id = ? AND external_reference = ? LIMIT 1");
    $stmt->execute([$operation_id, $external_ref]);
    $transaction = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$transaction) {
        http_response_code(404);
        echo json_encode(['error' => 'Transaction not found']);
        exit();
    }
    
    // Si la transacción ya está completada o falló, devolver el estado actual
    if (in_array($transaction['status'], ['completed', 'failed', 'expired'])) {
        echo json_encode([
            'status' => $transaction['status'],
            'message' => getStatusMessage($transaction['status']),
            'updated_at' => $transaction['updated_at']
        ]);
        exit();
    }
    
    // Verificar si la transacción ha expirado
    if (strtotime($transaction['expires_at']) < time()) {
        // Actualizar estado a expirado
        $stmt = $pdo->prepare("UPDATE kamipay_transactions SET status = 'expired', updated_at = NOW() WHERE id = ?");
        $stmt->execute([$transaction['id']]);
        
        echo json_encode([
            'status' => 'expired',
            'message' => 'Transacción expirada',
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        exit();
    }
    
    // Consultar estado en KamiPay API
    $kamiPay = new KamiPayAPI($kamipay_mode == 0);
    $statusData = $kamiPay->getTransactionStatus($operation_id, 'charge');
    
    if (!$statusData) {
        echo json_encode([
            'status' => $transaction['status'],
            'message' => 'Error al consultar estado',
            'updated_at' => $transaction['updated_at']
        ]);
        exit();
    }
    
    $newStatus = $transaction['status'];
    $txid = null;
    $bank_txid = null;
    $processed_at = null;
    
    // Interpretar respuesta de KamiPay
    if ($statusData['status'] === 'ok' && isset($statusData['data'])) {
        $data = $statusData['data'];
        
        switch ($data['status']) {
            case 'done':
                $newStatus = 'completed';
                $txid = $data['txid'] ?? null;
                $bank_txid = $data['bank_txid'] ?? null;
                $processed_at = date('Y-m-d H:i:s');
                
                // Procesar donación (agregar JC al personaje)
                processSuccessfulPayment($transaction, $pdo);
                break;
                
            case 'processing':
                $newStatus = 'processing';
                break;
                
            case 'failed':
                $newStatus = 'failed';
                break;
        }
    } elseif ($statusData['status'] === 'failed') {
        // Transacción no encontrada o falló
        if ($transaction['status'] === 'pending') {
            // Mantener como pending si es muy reciente
            $newStatus = 'pending';
        }
    }
    
    // Actualizar estado en base de datos si cambió
    if ($newStatus !== $transaction['status']) {
        $updateSql = "UPDATE kamipay_transactions SET status = ?, updated_at = NOW()";
        $updateParams = [$newStatus];
        
        if ($txid) {
            $updateSql .= ", txid = ?";
            $updateParams[] = $txid;
        }
        
        if ($bank_txid) {
            $updateSql .= ", bank_txid = ?";
            $updateParams[] = $bank_txid;
        }
        
        if ($processed_at) {
            $updateSql .= ", processed_at = ?";
            $updateParams[] = $processed_at;
        }
        
        $updateSql .= " WHERE id = ?";
        $updateParams[] = $transaction['id'];
        
        $stmt = $pdo->prepare($updateSql);
        $stmt->execute($updateParams);
    }
    
    echo json_encode([
        'status' => $newStatus,
        'message' => getStatusMessage($newStatus),
        'updated_at' => date('Y-m-d H:i:s'),
        'txid' => $txid,
        'bank_txid' => $bank_txid
    ]);
    
} catch (PDOException $e) {
    error_log("Error checking KamiPay status: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Database error']);
} catch (Exception $e) {
    error_log("Error checking KamiPay status: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Internal error']);
}

/**
 * Procesar pago exitoso - agregar JC al personaje
 */
function processSuccessfulPayment($transaction, $pdo) {
    try {
        // Verificar que el personaje aún existe
        $stmt = $pdo->prepare("SELECT obj_id, char_name FROM characters WHERE char_name = ? LIMIT 1");
        $stmt->execute([$transaction['character_name']]);
        $character = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$character) {
            error_log("Character not found for KamiPay payment: " . $transaction['character_name']);
            return false;
        }
        
        // Calcular JC con bonus (mismo cálculo que en donaciones.php)
        $base_jc = $transaction['amount_jc'];
        $bonus_jc = calculateBonus($base_jc);
        $total_jc = $base_jc + $bonus_jc;
        
        // Agregar JC al inventario del personaje
        $stmt = $pdo->prepare("
            INSERT INTO items (owner_id, object_id, count, loc, loc_data) 
            VALUES (?, 9623, ?, 'INVENTORY', 0)
            ON DUPLICATE KEY UPDATE count = count + VALUES(count)
        ");
        $stmt->execute([$character['obj_id'], $total_jc]);
        
        // Log de la transacción exitosa
        error_log("KamiPay payment processed: Character={$transaction['character_name']}, JC={$total_jc}, Operation={$transaction['operation_id']}");
        
        return true;
        
    } catch (PDOException $e) {
        error_log("Error processing KamiPay payment: " . $e->getMessage());
        return false;
    }
}

/**
 * Calcular bonus JC basado en la cantidad
 */
function calculateBonus($amount) {
    $bonus = 0;
    
    if ($amount >= 0 && $amount <= 99) {
        $bonus = floor($amount * 0.10);
    } elseif ($amount >= 100 && $amount <= 499) {
        $bonus = floor($amount * 0.15);
    } elseif ($amount >= 500 && $amount <= 999) {
        $bonus = floor($amount * 0.20);
    } elseif ($amount >= 1000 && $amount <= 2999) {
        $bonus = floor($amount * 0.25);
    } elseif ($amount >= 3000 && $amount <= 7499) {
        $bonus = floor($amount * 0.30);
    } elseif ($amount >= 7500) {
        $bonus = floor($amount * 0.35);
    }
    
    return $bonus;
}

/**
 * Obtener mensaje de estado amigable
 */
function getStatusMessage($status) {
    $messages = [
        'pending' => 'Aguardando pagamento',
        'processing' => 'Processando pagamento',
        'completed' => 'Pagamento confirmado!',
        'failed' => 'Pagamento falhou',
        'expired' => 'Transação expirada'
    ];
    
    return $messages[$status] ?? 'Status desconhecido';
}
?>
