<?php
/**
 * Guardar / eliminar archivos de avatar subidos por admin (logos_sinapsys/profile_<uuid>.*).
 * No borra logo_cliente.* del instalador.
 */

declare(strict_types=1);

/** @return bool True if string looks like AntaraStore UUID v4 */
function antara_user_profile_is_uuid(string $id): bool
{
    return (bool) preg_match(
        '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',
        $id
    );
}

function antara_user_profile_image_dir(): string
{
    $root = defined('ANTARA_ROOT') ? ANTARA_ROOT : dirname(__DIR__, 2);
    return $root . DIRECTORY_SEPARATOR . 'logos_sinapsys';
}

/**
 * @return 'image'|'gif'|'video'|null
 */
function antara_user_profile_media_kind(?string $rel): ?string
{
    if ($rel === null || $rel === '') {
        return null;
    }
    $path = strtolower(parse_url($rel, PHP_URL_PATH) ?: $rel);
    if (preg_match('/\.gif$/i', $path)) {
        return 'gif';
    }
    if (preg_match('/\.(mp4|webm|ogg)$/i', $path)) {
        return 'video';
    }
    if (preg_match('/\.(png|jpe?g|webp)$/i', $path)) {
        return 'image';
    }
    return null;
}

/**
 * @param mixed $frame
 * @return array{panX: float, panY: float, zoomPct: float, frameInsetRatio: float, editorViewport?: float}|null
 */
function antara_user_profile_media_frame_normalize($frame): ?array
{
    if (!is_array($frame)) {
        return null;
    }
    $panX = isset($frame['panX']) ? (float) $frame['panX'] : 0.0;
    $panY = isset($frame['panY']) ? (float) $frame['panY'] : 0.0;
    $zoom = isset($frame['zoomPct']) ? (float) $frame['zoomPct'] : 100.0;
    $inset = isset($frame['frameInsetRatio']) ? (float) $frame['frameInsetRatio'] : 0.1;
    $editorV = isset($frame['editorViewport']) ? (float) $frame['editorViewport'] : 0.0;
    if (!is_finite($panX) || !is_finite($panY) || !is_finite($zoom) || !is_finite($inset)) {
        return null;
    }
    $zoom = max(100.0, min(400.0, $zoom));
    $inset = max(0.0, min(0.45, $inset));
    $out = [
        'panX' => round($panX, 2),
        'panY' => round($panY, 2),
        'zoomPct' => round($zoom, 2),
        'frameInsetRatio' => round($inset, 4),
    ];
    if ($editorV > 0 && is_finite($editorV)) {
        $out['editorViewport'] = round(min(1200.0, max(80.0, $editorV)), 2);
    }
    return $out;
}

/**
 * Borra solo ficheros profile_<userId>.* en logos_sinapsys.
 */
function antara_user_profile_image_delete_uploaded_files(string $userId): void
{
    if (!antara_user_profile_is_uuid($userId)) {
        return;
    }
    $dir = antara_user_profile_image_dir();
    if (!is_dir($dir)) {
        return;
    }
    $prefix = $dir . DIRECTORY_SEPARATOR . 'profile_' . $userId . '.';
    foreach (glob($prefix . '*') ?: [] as $p) {
        if (is_file($p)) {
            @unlink($p);
        }
    }
}

/**
 * @param array $f Un elemento de $_FILES (name/type/tmp_name/error/size)
 * @return array{0: ?string, 1: ?string} [error message or null, public rel path or null]
 */
function antara_user_profile_image_process_upload(string $userId, array $f): array
{
    if (!antara_user_profile_is_uuid($userId)) {
        return ['Identificador de usuario no válido.', null];
    }
    if (($f['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
        return ['No se recibió ningún archivo.', null];
    }
    if (($f['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
        return ['Error al subir el archivo.', null];
    }
    $tmp = (string) ($f['tmp_name'] ?? '');
    if ($tmp === '' || !is_uploaded_file($tmp)) {
        return ['Subida no válida.', null];
    }

    $mime = '';
    if (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 = [
        'image/png' => 'png',
        'image/jpeg' => 'jpg',
        'image/webp' => 'webp',
        'image/gif' => 'gif',
        'video/mp4' => 'mp4',
        'video/webm' => 'webm',
        'video/ogg' => 'ogg',
    ];
    $ext = $extMap[strtolower($mime)] ?? '';
    if ($ext === '') {
        $fn = strtolower((string) ($f['name'] ?? ''));
        $fromName = strtolower((string) pathinfo($fn, PATHINFO_EXTENSION));
        $nameMap = [
            'png' => 'png', 'jpg' => 'jpg', 'jpeg' => 'jpg', 'webp' => 'webp', 'gif' => 'gif',
            'mp4' => 'mp4', 'webm' => 'webm', 'ogg' => 'ogg',
        ];
        $ext = $nameMap[$fromName] ?? '';
    }
    if ($ext === '') {
        return ['Formato no admitido. Usa PNG, JPEG, WebP, GIF, MP4 o WebM.', null];
    }

    $maxBytes = in_array($ext, ['mp4', 'webm', 'ogg'], true) ? (16 * 1024 * 1024) : (8 * 1024 * 1024);
    if (($f['size'] ?? 0) > $maxBytes) {
        $mb = (int) round($maxBytes / (1024 * 1024));
        return ["El archivo supera {$mb} MB.", null];
    }

    $dir = antara_user_profile_image_dir();
    if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
        return ['No se pudo crear la carpeta de imágenes.', null];
    }

    antara_user_profile_image_delete_uploaded_files($userId);

    $dest = $dir . DIRECTORY_SEPARATOR . 'profile_' . $userId . '.' . $ext;
    if (!@move_uploaded_file($tmp, $dest)) {
        if (!@copy($tmp, $dest)) {
            return ['No se pudo guardar la imagen.', null];
        }
        @unlink($tmp);
    }

    return [null, '/logos_sinapsys/profile_' . $userId . '.' . $ext];
}
