<?php
/**
 * Logos por sucursal en el instalador (logos_sinapsys/branch_{id}.*).
 */

declare(strict_types=1);

require_once __DIR__ . '/client_logo_ops.php';

function antara_install_branch_logos_dir(): string
{
    return antara_sinapsys_logos_dir();
}

/**
 * @return string Ruta web relativa o vacío
 */
function antara_install_branch_logo_rel(string $branchId): string
{
    $branchId = preg_replace('/[^a-zA-Z0-9_]/', '', $branchId);
    if ($branchId === '') {
        return '';
    }
    $abs = antara_install_branch_logo_resolved_path($branchId);

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

function antara_install_branch_logo_resolved_path(string $branchId): ?string
{
    $branchId = preg_replace('/[^a-zA-Z0-9_]/', '', $branchId);
    if ($branchId === '') {
        return null;
    }
    $dir = antara_install_branch_logos_dir();
    if (!is_dir($dir)) {
        return null;
    }
    $base = 'branch_' . $branchId;
    foreach (['png', 'webp', 'jpg', 'gif', 'mp4', 'webm', 'ogg'] as $ext) {
        $p = $dir . DIRECTORY_SEPARATOR . $base . '.' . $ext;
        if (is_file($p) && is_readable($p)) {
            return $p;
        }
    }
    $glob = glob($dir . DIRECTORY_SEPARATOR . $base . '.*') ?: [];
    foreach ($glob as $p) {
        if (is_file($p) && is_readable($p)) {
            return $p;
        }
    }

    return null;
}

/**
 * Logo de empresa (sucursal primaria) como rel web.
 */
function antara_install_primary_company_logo_rel(): string
{
    require_once dirname(__DIR__) . '/includes/install_company_logo.php';
    $abs = antara_install_company_logo_resolved_path();

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

/**
 * Procesa un archivo de logo de sucursal (índice en branch_logo[]).
 *
 * @return array{errors: list<string>, saved: bool, rel: string}
 */
function antara_install_branch_logo_apply_upload(string $branchId, int $fileIndex): array
{
    $empty = ['errors' => [], 'saved' => false, 'rel' => ''];
    $branchId = preg_replace('/[^a-zA-Z0-9_]/', '', $branchId);
    if ($branchId === '') {
        return $empty;
    }
    if (!isset($_FILES['branch_logo']) || !is_array($_FILES['branch_logo'])) {
        return $empty;
    }
    $files = $_FILES['branch_logo'];
    if (!isset($files['error'][$fileIndex])) {
        return $empty;
    }
    if (($files['error'][$fileIndex] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
        return $empty;
    }
    if (($files['error'][$fileIndex] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
        return ['errors' => ['Error al subir el logo de la sucursal.'], 'saved' => false, 'rel' => ''];
    }
    $tmp = (string) ($files['tmp_name'][$fileIndex] ?? '');
    if ($tmp === '' || !is_uploaded_file($tmp)) {
        return ['errors' => ['Subida de logo de sucursal no válida.'], 'saved' => false, 'rel' => ''];
    }

    $sources = $_POST['branch_logo_source'] ?? [];
    $source = is_array($sources) && isset($sources[$fileIndex]) ? (string) $sources[$fileIndex] : 'original';
    $frames = $_POST['branch_logo_media_frame'] ?? [];
    $frameRaw = is_array($frames) && isset($frames[$fileIndex]) ? (string) $frames[$fileIndex] : '';
    $frame = antara_media_frame_from_request_value($frameRaw);

    $file = [
        'name' => (string) ($files['name'][$fileIndex] ?? ''),
        'type' => (string) ($files['type'][$fileIndex] ?? ''),
        'tmp_name' => $tmp,
        'error' => (int) ($files['error'][$fileIndex] ?? UPLOAD_ERR_OK),
        'size' => (int) ($files['size'][$fileIndex] ?? 0),
    ];
    $result = antara_sinapsys_named_media_upload('branch_' . $branchId, $file, $source, $frame);

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

/**
 * Copia el logo de empresa al archivo de la sucursal primaria si hace falta.
 */
function antara_install_branch_copy_primary_logo_to_branch(string $branchId): string
{
    require_once dirname(__DIR__) . '/includes/install_company_logo.php';
    $companyAbs = antara_install_company_logo_resolved_path();
    if ($companyAbs === null) {
        return '';
    }
    $branchId = preg_replace('/[^a-zA-Z0-9_]/', '', $branchId);
    if ($branchId === '') {
        return '';
    }
    $logoDir = antara_install_branch_logos_dir();
    if (!is_dir($logoDir) && !@mkdir($logoDir, 0755, true)) {
        return '';
    }
    $ext = strtolower((string) pathinfo($companyAbs, PATHINFO_EXTENSION));
    if ($ext === '') {
        $ext = 'png';
    }
    $base = 'branch_' . $branchId;
    foreach (glob($logoDir . DIRECTORY_SEPARATOR . $base . '.*') ?: [] as $old) {
        if (is_file($old)) {
            @unlink($old);
        }
    }
    $dest = $logoDir . DIRECTORY_SEPARATOR . $base . '.' . $ext;
    if (@copy($companyAbs, $dest)) {
        return '/logos_sinapsys/' . basename($dest);
    }

    return antara_install_primary_company_logo_rel();
}
