<?php
/**
 * Webhook para receber notificações de pagamento
 * 
 * Processa callbacks dos gateways de pagamento.
 */

header('Content-Type: application/json');

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/Payment/PaymentFactory.php';

use Payment\PaymentFactory;

// Log do webhook
$logFile = __DIR__ . '/../logs/webhook_' . date('Y-m-d') . '.log';
$logDir = dirname($logFile);
if (!is_dir($logDir)) {
    mkdir($logDir, 0755, true);
}

$rawInput = file_get_contents('php://input');
$logEntry = date('Y-m-d H:i:s') . " - " . $_SERVER['REQUEST_METHOD'] . "\n";
$logEntry .= "Headers: " . json_encode(getallheaders()) . "\n";
$logEntry .= "Body: " . $rawInput . "\n";
$logEntry .= "---\n";
file_put_contents($logFile, $logEntry, FILE_APPEND);

try {
    $factory = new PaymentFactory(getDB());
    
    if (!$factory->hasActiveGateway()) {
        throw new \RuntimeException('Nenhum gateway ativo');
    }

    $gateway = $factory->create();
    $activeGatewayInfo = $factory->getActiveGateway();

    // Parse do payload
    $payload = json_decode($rawInput, true);
    if (!$payload) {
        // Tentar GET params (alguns gateways enviam assim)
        $payload = $_GET;
    }

    // Obter signature do header (se aplicável)
    $headers = getallheaders();
    $signature = $headers['X-Signature'] ?? $headers['x-signature'] ?? '';

    // Processar webhook via gateway
    $result = $gateway->processWebhook($payload, $signature);

    if ($result['success'] && isset($result['transaction_id'])) {
        // Atualizar transação no banco
        $status = $result['status'] ?? 'pending';
        
        // Mapear status do gateway para nosso sistema
        $statusMap = [
            'approved' => 'approved',
            'pending' => 'pending',
            'in_process' => 'pending',
            'rejected' => 'rejected',
            'cancelled' => 'cancelled',
            'refunded' => 'refunded'
        ];
        
        $mappedStatus = $statusMap[$status] ?? 'pending';
        $paidAt = ($mappedStatus === 'approved') ? date('Y-m-d H:i:s') : null;

        $stmt = getDB()->prepare("
            UPDATE payment_transactions 
            SET status = ?, 
                paid_at = COALESCE(?, paid_at),
                updated_at = NOW()
            WHERE external_id = ? AND gateway_id = ?
        ");
        $stmt->execute([
            $mappedStatus,
            $paidAt,
            $result['transaction_id'],
            $activeGatewayInfo['id']
        ]);

        // Se aprovado, ativar plano do usuário
        if ($mappedStatus === 'approved') {
            $stmt = getDB()->prepare("
                SELECT user_id, plan_id FROM payment_transactions 
                WHERE external_id = ? AND gateway_id = ?
            ");
            $stmt->execute([$result['transaction_id'], $activeGatewayInfo['id']]);
            $transaction = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($transaction) {
                // Buscar duração do plano
                $stmt = getDB()->prepare("SELECT duration_days FROM plans WHERE id = ?");
                $stmt->execute([$transaction['plan_id']]);
                $plan = $stmt->fetch(PDO::FETCH_ASSOC);
                
                $durationDays = $plan['duration_days'] ?? 30;
                $expiresAt = date('Y-m-d H:i:s', strtotime("+{$durationDays} days"));

                // Atualizar usuário com plano ativo
                $stmt = getDB()->prepare("
                    UPDATE users 
                    SET plan_id = ?, 
                        plan_expires_at = ?,
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([
                    $transaction['plan_id'],
                    $expiresAt,
                    $transaction['user_id']
                ]);

                // Log de sucesso
                $logEntry = date('Y-m-d H:i:s') . " - PAYMENT APPROVED - User: {$transaction['user_id']}, Plan: {$transaction['plan_id']}\n---\n";
                file_put_contents($logFile, $logEntry, FILE_APPEND);
            }
        }
    }

    http_response_code(200);
    echo json_encode(['status' => 'ok']);

} catch (\Exception $e) {
    $logEntry = date('Y-m-d H:i:s') . " - ERROR: " . $e->getMessage() . "\n---\n";
    file_put_contents($logFile, $logEntry, FILE_APPEND);
    
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
