<?php
/**
 * Imagen de perfil del primer super administrador (paso 2 del instalador).
 * Archivos: logos_sinapsys/first_admin_profile.*
 */

declare(strict_types=1);

require_once __DIR__ . '/client_logo_ops.php';

/**
 * Procesa $_FILES['firstAdminProfileImage'] opcional (misma semántica que companyLogo).
 *
 * @return array{errors: list<string>, saved: bool, mediaFrame: array|null}
 */
function antara_install_first_admin_profile_apply_upload(): array
{
    if (!isset($_FILES['firstAdminProfileImage']) || !is_array($_FILES['firstAdminProfileImage'])) {
        return ['errors' => [], 'saved' => false, 'mediaFrame' => null];
    }
    $source = isset($_POST['first_admin_logo_source']) ? (string) $_POST['first_admin_logo_source'] : 'original';
    $frame = antara_media_frame_from_post('first_admin_media_frame');
    $result = antara_sinapsys_named_media_upload('first_admin_profile', $_FILES['firstAdminProfileImage'], $source, $frame);
    if ($result['saved']) {
        $_SESSION['install_first_admin_media_frame'] = $result['mediaFrame'];
    }

    return [
        'errors' => $result['errors'],
        'saved' => $result['saved'],
        'mediaFrame' => $result['mediaFrame'],
    ];
}

/**
 * Ruta absoluta de la foto del primer admin (first_admin_profile.*), o null.
 */
function antara_install_first_admin_profile_resolved_path(): ?string
{
    $dir = antara_sinapsys_logos_dir();
    if (!is_dir($dir)) {
        return null;
    }
    $png = $dir . DIRECTORY_SEPARATOR . 'first_admin_profile.png';
    if (is_file($png) && is_readable($png)) {
        return $png;
    }
    foreach (['webp', 'jpg', 'gif', 'mp4', 'webm', 'ogg'] as $ext) {
        $p = $dir . DIRECTORY_SEPARATOR . 'first_admin_profile.' . $ext;
        if (is_file($p) && is_readable($p)) {
            return $p;
        }
    }
    foreach (glob($dir . DIRECTORY_SEPARATOR . 'first_admin_profile.*') ?: [] as $p) {
        if (is_file($p) && is_readable($p)) {
            return $p;
        }
    }

    return null;
}

/**
 * @return array|null
 */
function antara_install_first_admin_profile_media_frame(): ?array
{
    $raw = $_SESSION['install_first_admin_media_frame'] ?? null;
    if (!is_array($raw)) {
        return null;
    }

    return antara_user_profile_media_frame_normalize($raw);
}
