<?php
declare(strict_types=1);

require __DIR__ . '/../app/Config/Config.php';
require __DIR__ . '/../app/Core/Autoloader.php';
\App\Config\Config::init();
\App\Core\Autoloader::register();
\App\Core\DB::init();

use App\Core\DB;

$provider = $_GET['provider'] ?? '';
$secret = $_GET['secret'] ?? '';
$body = file_get_contents('php://input');
$data = json_decode($body, true);

// Mercado Pago
if ($provider === 'mercadopago') {
    $expected = getenv('MP_WEBHOOK_SECRET') ?: '';
    if ($expected && $secret !== $expected) {
        http_response_code(401);
        echo 'unauthorized';
        exit;
    }
    $status = $data['data']['status'] ?? '';
    $externalRef = $data['data']['external_reference'] ?? '';
    $tenantId = (int)($externalRef ? explode(':', $externalRef)[0] : 0);
    if ($tenantId && $status === 'approved') {
        $now = date('Y-m-d H:i:s');
        $stmt = DB::pdo()->prepare("UPDATE tenants SET status = 'ativo', updated_at = ? WHERE id = ?");
        $stmt->execute([$now, $tenantId]);
        $stmt2 = DB::pdo()->prepare("UPDATE plans SET features = CONCAT(features, ',relatorios_avancados') WHERE id = (SELECT plan_id FROM tenants WHERE id = ?)");
        try { $stmt2->execute([$tenantId]); } catch (\Throwable $e) {}
    }
    http_response_code(200);
    echo 'ok';
    exit;
}

// Stripe (exemplo básico)
if ($provider === 'stripe') {
    $status = $data['data']['object']['status'] ?? '';
    $tenantId = (int)($data['data']['object']['metadata']['tenant_id'] ?? 0);
    if ($tenantId && in_array($status, ['succeeded','paid'], true)) {
        $now = date('Y-m-d H:i:s');
        $stmt = DB::pdo()->prepare("UPDATE tenants SET status = 'ativo', updated_at = ? WHERE id = ?");
        $stmt->execute([$now, $tenantId]);
    }
    http_response_code(200);
    echo 'ok';
    exit;
}

// Pix automático (exemplo básico)
if ($provider === 'pix') {
    $status = $data['status'] ?? '';
    $tenantId = (int)($data['tenant_id'] ?? 0);
    if ($tenantId && $status === 'confirmed') {
        $now = date('Y-m-d H:i:s');
        $stmt = DB::pdo()->prepare("UPDATE tenants SET status = 'ativo', updated_at = ? WHERE id = ?");
        $stmt->execute([$now, $tenantId]);
    }
    http_response_code(200);
    echo 'ok';
    exit;
}

http_response_code(400);
echo 'unknown-provider';
