<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Controllers\CurlController;

class QrcodeController
{

    /**
     * GET /get_qrcode
     */
    public function getQrcode(): array
    {
        $errors = [];

        // --- Validação de parâmetros ---
        $id    = $_GET['id'] ?? null;
        $token = $_SESSION['token'] ?? null;

        $missing = [];
        if (!$id)    $missing[] = "'id'";
        if (!$token) $missing[] = "'token'";

        if ($missing) {
            return [
                'success' => false,
                'qrcode' => [],
                'errors' => [
                    'params' => "Parâmetros obrigatórios faltando: " . implode(', ', $missing)
                ],
            ];
        }

        // --- Consulta API ---
        $url = "https://hub.mogiguacu.sp.gov.br/internals/eventos/{$id}/qrcode/jwt";

        $headers = [
            "Authorization: Token $token",
            "Content-Type: application/json"
        ];

        $response = (new CurlController())->curlGet($url, $headers);

        if (!$response) {
            $errors['api'] = 'Erro ao acessar a API';
            return [
                'success' => false,
                'qrcode' => [],
                'errors' => $errors,
            ];
        }
        
        $data = json_decode($response, true);
        if (isset($data['qrcode_base64'])) {
            $qr_base64 = $data['qrcode_base64'];
        } else {
            $errors['qrcode'] = 'Já computado';
            return [
                'success' => false,
                'qrcode' => [],
                'errors' => $errors,
                'message' => $data['message'],
                'data' => $data['data'] ?? null
            ];
        }

        return [
            'success' => true,
            'qrcode' => $qr_base64,
            'errors' => [],
        ];
    }
}