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

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

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

$gen = generate_client_card_png_bytes($client);
if (empty($gen['ok']) || empty($gen['bytes'])) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    exit($gen['message'] ?? 'Erro ao gerar card');
}

$download = isset($_GET['download']);
$filename = $gen['filename'] ?? ('card-tvexpress-' . $id . '.png');

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 . '"');
}

echo $gen['bytes'];
exit;
