<?php
/**
 * Logo de empresa (logos_sinapsys/logo_cliente.*) y helpers de media compartidos.
 */

declare(strict_types=1);

require_once __DIR__ . '/../core/auth/profile_image_ops.php';

function antara_sinapsys_logos_dir(): string
{
    return (defined('GRID_ROOT') ? GRID_ROOT : dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'logos_sinapsys';
}

/**
 * @return array<string, string>
 */
function antara_sinapsys_media_ext_map(): array
{
    return [
        'image/png' => 'png',
        'image/jpeg' => 'jpg',
        'image/webp' => 'webp',
        'image/gif' => 'gif',
        'video/mp4' => 'mp4',
        'video/webm' => 'webm',
        'video/ogg' => 'ogg',
    ];
}

/**
 * @return array<string, string>
 */
function antara_sinapsys_media_name_ext_map(): array
{
    return [
        'png' => 'png',
        'jpg' => 'jpg',
        'jpeg' => 'jpg',
        'webp' => 'webp',
        'gif' => 'gif',
        'mp4' => 'mp4',
        'webm' => 'webm',
        'ogg' => 'ogg',
    ];
}

function antara_media_frame_from_post(string $field): ?array
{
    if (!isset($_POST[$field]) || !is_string($_POST[$field])) {
        return null;
    }
    $raw = trim($_POST[$field]);
    if ($raw === '') {
        return null;
    }
    $decoded = json_decode($raw, true);

    return antara_user_profile_media_frame_normalize($decoded);
}

function antara_media_frame_from_request_value($raw): ?array
{
    if (!is_string($raw) || trim($raw) === '') {
        return null;
    }
    $decoded = json_decode($raw, true);

    return antara_user_profile_media_frame_normalize($decoded);
}

/**
 * @param array $f Elemento de $_FILES
 */
function antara_sinapsys_detect_upload_ext(array $f): string
{
    $tmp = (string) ($f['tmp_name'] ?? '');
    $mime = '';
    if ($tmp !== '' && function_exists('finfo_open')) {
        $fi = @finfo_open(FILEINFO_MIME_TYPE);
        if ($fi) {
            $mime = (string) @finfo_file($fi, $tmp);
            finfo_close($fi);
        }
    }
    if ($mime === '') {
        $mime = (string) ($f['type'] ?? '');
    }
    $extMap = antara_sinapsys_media_ext_map();
    $ext = $extMap[strtolower($mime)] ?? '';
    if ($ext !== '') {
        return $ext;
    }
    $fn = strtolower((string) ($f['name'] ?? ''));
    $fromName = strtolower((string) pathinfo($fn, PATHINFO_EXTENSION));
    $nameMap = antara_sinapsys_media_name_ext_map();

    return $nameMap[$fromName] ?? '';
}

/**
 * @param array $f Elemento de $_FILES
 * @return array{errors: list<string>, saved: bool, rel: string, mediaFrame: array|null}
 */
function antara_sinapsys_named_media_upload(string $baseName, array $f, string $source, ?array $mediaFrame): array
{
    $empty = ['errors' => [], 'saved' => false, 'rel' => '', 'mediaFrame' => null];
    $baseName = preg_replace('/[^a-zA-Z0-9_]/', '', $baseName);
    if ($baseName === '') {
        return ['errors' => ['Nombre de archivo no válido.'], 'saved' => false, 'rel' => '', 'mediaFrame' => null];
    }
    if (($f['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
        return $empty;
    }
    if (($f['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
        return ['errors' => ['Error al subir el archivo.'], 'saved' => false, 'rel' => '', 'mediaFrame' => null];
    }
    $tmp = (string) ($f['tmp_name'] ?? '');
    if ($tmp === '' || !is_uploaded_file($tmp)) {
        return ['errors' => ['Subida no válida.'], 'saved' => false, 'rel' => '', 'mediaFrame' => null];
    }

    $logoDir = antara_sinapsys_logos_dir();
    if (!is_dir($logoDir) && !@mkdir($logoDir, 0755, true)) {
        return ['errors' => ['No se pudo crear la carpeta logos_sinapsys.'], 'saved' => false, 'rel' => '', 'mediaFrame' => null];
    }

    foreach (glob($logoDir . DIRECTORY_SEPARATOR . $baseName . '.*') ?: [] as $old) {
        if (is_file($old)) {
            @unlink($old);
        }
    }

    $isCroppedPng = ($source === 'crop_png');
    $isFrame = ($source === 'frame');
    $frameToStore = null;

    if ($isCroppedPng) {
        $maxBytes = 3 * 1024 * 1024;
        if (($f['size'] ?? 0) > $maxBytes) {
            return ['errors' => ['La imagen recortada supera el tamaño máximo (3 MB).'], 'saved' => false, 'rel' => '', 'mediaFrame' => null];
        }
        $info = @getimagesize($tmp);
        if ($info === false || ($info[2] ?? 0) !== IMAGETYPE_PNG) {
            return ['errors' => ['El recorte debe enviarse como PNG.'], 'saved' => false, 'rel' => '', 'mediaFrame' => null];
        }
        $dest = $logoDir . DIRECTORY_SEPARATOR . $baseName . '.png';
        if (!@copy($tmp, $dest)) {
            return ['errors' => ['No se pudo guardar el recorte.'], 'saved' => false, 'rel' => '', 'mediaFrame' => null];
        }

        return ['errors' => [], 'saved' => true, 'rel' => '/logos_sinapsys/' . basename($dest), 'mediaFrame' => null];
    }

    $ext = antara_sinapsys_detect_upload_ext($f);
    if ($ext === '') {
        return ['errors' => ['Formato no admitido. Usa PNG, JPEG, WebP, GIF, MP4 o WebM.'], 'saved' => false, 'rel' => '', 'mediaFrame' => null];
    }

    $maxBytes = in_array($ext, ['mp4', 'webm', 'ogg'], true) ? (40 * 1024 * 1024) : (40 * 1024 * 1024);
    if (($f['size'] ?? 0) > $maxBytes) {
        return ['errors' => ['El archivo supera el tamaño máximo permitido.'], 'saved' => false, 'rel' => '', 'mediaFrame' => null];
    }

    $kind = antara_user_profile_media_kind('/x.' . $ext);
    if ($isFrame) {
        if (!in_array($kind, ['gif', 'video'], true)) {
            return ['errors' => ['El encuadre circular solo aplica a GIF o vídeo.'], 'saved' => false, 'rel' => '', 'mediaFrame' => null];
        }
        $frameToStore = $mediaFrame;
    } elseif (in_array($kind, ['gif', 'video'], true)) {
        $frameToStore = $mediaFrame;
    } else {
        $frameToStore = null;
    }

    $dest = $logoDir . DIRECTORY_SEPARATOR . $baseName . '.' . $ext;
    if (!@copy($tmp, $dest)) {
        return ['errors' => ['No se pudo guardar el archivo.'], 'saved' => false, 'rel' => '', 'mediaFrame' => null];
    }

    return [
        'errors' => [],
        'saved' => true,
        'rel' => '/logos_sinapsys/' . basename($dest),
        'mediaFrame' => $frameToStore,
    ];
}

function antara_client_logo_resolved_path(): ?string
{
    $dir = antara_sinapsys_logos_dir();
    if (!is_dir($dir)) {
        return null;
    }
    $png = $dir . DIRECTORY_SEPARATOR . 'logo_cliente.png';
    if (is_file($png) && is_readable($png)) {
        return $png;
    }
    foreach (['webp', 'jpg', 'gif', 'mp4', 'webm', 'ogg'] as $ext) {
        $p = $dir . DIRECTORY_SEPARATOR . 'logo_cliente.' . $ext;
        if (is_file($p) && is_readable($p)) {
            return $p;
        }
    }
    foreach (glob($dir . DIRECTORY_SEPARATOR . 'logo_cliente.*') ?: [] as $p) {
        if (is_file($p) && is_readable($p)) {
            return $p;
        }
    }

    return null;
}

function antara_client_logo_rel(): string
{
    $abs = antara_client_logo_resolved_path();

    return $abs !== null ? 'logos_sinapsys/' . basename($abs) : '';
}

/**
 * @return array{errors: list<string>, saved: bool, rel: string, mediaFrame: array|null}
 */
function antara_client_logo_process_upload(array $file, string $source, ?array $mediaFrame): array
{
    return antara_sinapsys_named_media_upload('logo_cliente', $file, $source, $mediaFrame);
}

function antara_client_logo_sync_settings(string $settingsFile, string $backupFile, array $defaultSettings, ?array $mediaFrame): bool
{
    require_once __DIR__ . '/settings_helpers.php';
    require_once __DIR__ . '/grid_default_settings.php';

    $cur = grid_read_settings_for_api($settingsFile, $backupFile, $defaultSettings);
    $rel = antara_client_logo_rel();
    if ($rel !== '') {
        $cur['clientLogoRel'] = $rel;
    }
    $kind = $rel !== '' ? antara_user_profile_media_kind('/' . $rel) : null;
    if ($kind !== null && in_array($kind, ['gif', 'video'], true) && $mediaFrame !== null) {
        $cur['clientLogoMediaFrame'] = $mediaFrame;
    } else {
        $cur['clientLogoMediaFrame'] = null;
    }

    return grid_persist_settings($settingsFile, $backupFile, $cur);
}
