<?php
require_once __DIR__ . '/auth.php';
require_login();

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    http_response_code(400);
    exit('ID inválido');
}

$client = get_client_by_id($id);
if (!$client) {
    http_response_code(404);
    exit('Cliente não encontrado');
}

$formatted = format_activation_code($client['activation_code'] ?? '');
$plan = normalize_card_plan($client['card_plan'] ?? 'mensal');
$gen = generate_and_store_client_card($id, $formatted, $plan);
if (empty($gen['ok'])) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    exit($gen['message'] ?? 'Erro ao gerar card');
}
$path = $gen['path'];

$download = isset($_GET['download']);
$filename = $gen['filename'] ?? card_download_filename($formatted, $plan);

header('Content-Type: image/png');
header('Cache-Control: private, max-age=3600');
if ($download) {
    header('Content-Disposition: attachment; filename="' . $filename . '"');
} else {
    header('Content-Disposition: inline; filename="' . $filename . '"');
}

readfile($path);
exit;
