<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/includes/branding.php';

function logo_db(bool $ensureSchema = true): PDO {
    $db = new PDO('sqlite:' . dirname(__DIR__) . '/api/db.db', null, null, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
    $db->exec('PRAGMA busy_timeout = 30000');
    if ($ensureSchema) branding_ensure_schema($db);
    return $db;
}

// Endpoint público de leitura usado pelos apps e pelo próprio painel.
if (isset($_GET['app_image'])) {
    try {
        $dbPublic = logo_db(false);
        $ownerId = max(0, (int)($_GET['owner_id'] ?? $_GET['revendedor_id'] ?? 0));
        $ownerType = strtolower(trim((string)($_GET['owner_type'] ?? '')));
        // Compatibilidade: alguns builds antigos enviam apenas revendedor_id.
        if ($ownerId > 0) $ownerType = 'revendedor';
        $record = branding_direct_record($dbPublic, $ownerType, $ownerId, false);
        $path = media_absolute_path((string)($record['path'] ?? ''));
        media_output_image_file($path, (int)($record['updated_at'] ?? 0));
    } catch (Throwable $e) {
        error_log('[branding_read] ' . $e->getMessage());
        http_response_code(404);
        header('Cache-Control: no-store');
        exit;
    }
}

require_once dirname(__DIR__) . '/includes/auth.php';
branding_ensure_schema($db);

function logo_h(string $value): string { return htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); }

$targetRevendaId = 0;
$targetTitle = 'Logo global do aplicativo';
if ($isRev) {
    $targetRevendaId = (int)($_SESSION['revendedor_id'] ?? 0);
    $targetTitle = 'Minha logo da revenda';
} elseif ($isAdmin && isset($_GET['revendedor_id'])) {
    $candidateId = max(0, (int)$_GET['revendedor_id']);
    if ($candidateId > 0) {
        $st = $db->prepare('SELECT id,nome,username FROM revendedores WHERE id=? LIMIT 1');
        $st->execute([$candidateId]);
        $rev = $st->fetch(PDO::FETCH_ASSOC) ?: [];
        if ($rev) {
            $targetRevendaId = $candidateId;
            $targetTitle = 'Logo da revenda: ' . (trim((string)($rev['nome'] ?? '')) ?: (string)$rev['username']);
        }
    }
}
$ownerType = $targetRevendaId > 0 ? 'revendedor' : 'admin';
$ownerId = $targetRevendaId;

if (empty($_SESSION['branding_csrf'])) {
    $_SESSION['branding_csrf'] = bin2hex(random_bytes(24));
}
$csrf = (string)$_SESSION['branding_csrf'];
$alert = '';
$alertType = 'success';
$newPathForCleanup = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $postedToken = (string)($_POST['csrf_token'] ?? '');
        if ($postedToken === '' || !hash_equals($csrf, $postedToken)) throw new RuntimeException('Sessão expirada. Recarregue a página e tente novamente.');

        $action = (string)($_POST['branding_action'] ?? 'save');
        if ($action === 'delete') {
            branding_delete_logo($db, $ownerType, $ownerId);
            $alert = $ownerType === 'revendedor'
                ? 'Logo própria removida. Esta revenda voltará a usar a logo global.'
                : 'Logo personalizada removida.';
        } else {
            $stored = [];
            $hasFile = isset($_FILES['logo_file'])
                && is_array($_FILES['logo_file'])
                && (int)($_FILES['logo_file']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE;
            if ($hasFile) {
                $folder = $ownerType === 'revendedor'
                    ? 'api/uploads/branding/revendas/' . $ownerId
                    : 'api/uploads/branding/global';
                $stored = media_store_uploaded_image($_FILES['logo_file'], $folder, 'logo', 5 * 1024 * 1024, true);
            } else {
                $url = trim((string)($_POST['logo_url'] ?? ''));
                if ($url !== '') {
                    $bytes = media_fetch_remote_image($url, 5 * 1024 * 1024);
                    $folder = $ownerType === 'revendedor'
                        ? 'api/uploads/branding/revendas/' . $ownerId
                        : 'api/uploads/branding/global';
                    $stored = media_store_bytes_image($bytes, $folder, 'logo', 5 * 1024 * 1024, true);
                }
            }
            $newPathForCleanup = (string)($stored['path'] ?? '');
            if (!$stored) throw new RuntimeException('Selecione uma imagem ou informe uma URL válida.');
            branding_save_logo($db, $ownerType, $ownerId, $stored);
            $newPathForCleanup = '';
            $alert = $ownerType === 'revendedor' ? 'Logo exclusiva da revenda salva com sucesso.' : 'Logo global salva com sucesso.';
        }
    } catch (Throwable $e) {
        if ($newPathForCleanup !== '') media_delete_relative_file($newPathForCleanup);
        $alert = $e->getMessage() ?: 'Erro ao salvar a logo.';
        $alertType = 'danger';
        error_log('[branding_save] ' . $alert);
    }
}

$currentRecord = branding_direct_record($db, $ownerType, $ownerId);
$currentUrl = branding_logo_url($db, $ownerType, $ownerId);
$isFallback = !empty($currentRecord['is_fallback']);
$currentPath = (string)($currentRecord['path'] ?? '');
$currentSize = $currentPath !== '' && is_file(media_absolute_path($currentPath)) ? (int)filesize(media_absolute_path($currentPath)) : 0;
$storageChecks = [];
foreach ([
    'Logos' => ($ownerType === 'revendedor' ? 'api/uploads/branding/revendas/' . $ownerId : 'api/uploads/branding/global'),
    'Fotos de perfil' => 'api/uploads/profiles',
] as $label => $relativeDir) {
    try {
        $absoluteDir = media_ensure_upload_directory($relativeDir);
        $storageChecks[$label] = ['ok' => is_writable($absoluteDir), 'path' => $relativeDir];
    } catch (Throwable $e) {
        $storageChecks[$label] = ['ok' => false, 'path' => $relativeDir, 'error' => $e->getMessage()];
    }
}

require_once __DIR__ . '/../includes/header.php';
?>
<div class="card branding-card">
    <div class="card-body p-4">
        <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4">
            <div>
                <h4 class="mb-1"><?= logo_h($targetTitle) ?></h4>
                <p class="text-muted mb-0">Cada revenda possui um arquivo independente. TV e celular recebem automaticamente a logo do responsável pelo MAC.</p>
            </div>
            <?php if ($currentUrl !== ''): ?>
                <img src="<?= logo_h($currentUrl) ?>" alt="Logo atual" class="branding-preview" data-image-error="hide">
            <?php endif; ?>
        </div>

        <?php if ($alert !== ''): ?><div class="alert alert-<?= logo_h($alertType) ?>"><?= logo_h($alert) ?></div><?php endif; ?>
        <?php if ($isFallback && $ownerType === 'revendedor'): ?><div class="branding-note mb-3"><strong>Usando logo global.</strong> Envie uma imagem para esta revenda ter identidade própria.</div><?php endif; ?>

        <form method="post" enctype="multipart/form-data" class="row g-3" autocomplete="off">
            <input type="hidden" name="csrf_token" value="<?= logo_h($csrf) ?>">
            <input type="hidden" name="branding_action" value="save">
            <div class="col-12 col-lg-6">
                <label class="form-label fw-bold">Enviar arquivo</label>
                <input type="file" name="logo_file" class="form-control" accept="image/png,image/jpeg,image/webp,image/gif">
                <small class="text-muted">JPG, PNG, WEBP ou GIF; máximo 5 MB e 40 megapixels.</small>
            </div>
            <div class="col-12 col-lg-6">
                <label class="form-label fw-bold">Ou importar por URL</label>
                <input type="url" name="logo_url" class="form-control" placeholder="https://servidor-publico/logo.png">
                <small class="text-muted">Endereços privados e arquivos que não sejam imagens são bloqueados.</small>
            </div>
            <div class="col-12 d-flex flex-wrap gap-2">
                <button type="submit" class="btn btn-primary"><i class="bx bx-cloud-upload"></i> Salvar logo</button>
                <?php if ($ownerType === 'revendedor' && !$isFallback): ?>
                    <button type="submit" class="btn btn-outline-danger" name="branding_action" value="delete" data-confirm="Remover a logo própria desta revenda?"><i class="bx bx-trash"></i> Remover logo própria</button>
                <?php endif; ?>
                <?php if ($isAdmin && $targetRevendaId > 0): ?><a class="btn btn-outline-secondary" href="revendas.php">Voltar para revendas</a><?php endif; ?>
            </div>
        </form>

        <hr class="my-4">
        <div class="row g-3 mb-3">
            <?php foreach ($storageChecks as $label => $check): ?>
                <div class="col-md-6">
                    <div class="branding-note h-100">
                        <strong><?= logo_h($label) ?>:</strong>
                        <span class="badge <?= !empty($check['ok']) ? 'bg-success' : 'bg-danger' ?> ms-1"><?= !empty($check['ok']) ? 'Pronto' : 'Sem permissão' ?></span><br>
                        <small><?= logo_h((string)$check['path']) ?><?php if (!empty($check['error'])): ?> — <?= logo_h((string)$check['error']) ?><?php endif; ?></small>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <div class="row g-3 small text-muted">
            <div class="col-md-4"><strong>Armazenamento:</strong><br><?= logo_h($currentPath !== '' ? $currentPath : 'Sem arquivo') ?></div>
            <div class="col-md-4"><strong>Tamanho atual:</strong><br><?= $currentSize > 0 ? number_format($currentSize / 1024, 1, ',', '.') . ' KB' : '—' ?></div>
            <div class="col-md-4"><strong>Cache:</strong><br>Versionado com ETag e atualização automática nos apps</div>
        </div>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
