<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\DB;

class PaymentController extends Controller
{
    public function webhook(): void
    {
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        $id = $data['data']['id'] ?? '';
        $type = $_GET['type'] ?? '';
        $secret = $_GET['secret'] ?? '';
        $expected = getenv('MP_WEBHOOK_SECRET') ?: '';
        try {
            $log = DB::pdo()->prepare("INSERT INTO webhook_logs (provider, payload, status_code, created_at) VALUES (?, ?, ?, ?)");
            $log->execute(['mercadopago', $input ?: '', 0, date('Y-m-d H:i:s')]);
        } catch (\Throwable $e) {
        }
        if ($expected && $secret !== $expected) {
            http_response_code(401);
            echo 'unauthorized';
            return;
        }
        if ($type === 'payment') {
            $status = $data['data']['status'] ?? '';
            $externalRef = $data['data']['external_reference'] ?? '';
            $tenantId = (int)($externalRef ? explode(':', $externalRef)[0] : 0);
            if ($tenantId) {
                $stmt = DB::pdo()->prepare("UPDATE tenants SET status = ? WHERE id = ?");
                $stmt->execute([$status === 'approved' ? 'ativo' : 'inativo', $tenantId]);
            }
        }
        http_response_code(200);
        echo 'ok';
    }
}
