<?php
/**
 * Plantilla HTML de fila de sucursal adicional en el instalador (modo empresa).
 * La matriz es la sección Empresa; aquí solo sucursales extra.
 */

declare(strict_types=1);

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

/**
 * @param array<string, mixed> $row
 */
function antara_install_render_branch_row(int $index, array $row, callable $esc, string $appBase): string
{
    $bid = (string) ($row['id'] ?? '');
    $name = (string) ($row['name'] ?? '');
    $address = (string) ($row['address'] ?? '');
    $location = isset($row['location']) && is_array($row['location'])
        ? antara_install_normalize_location($row['location'])
        : antara_install_empty_location();
    if ($address !== '' && antara_install_location_is_empty($location)) {
        $location['street'] = $address;
    }
    $email = (string) ($row['email'] ?? '');
    $phone = (string) ($row['phone'] ?? '');
    $createUser = !empty($row['createUser']);
    $userUsername = (string) ($row['userUsername'] ?? '');
    $userEmail = (string) ($row['userEmail'] ?? '');
    $userPhone = (string) ($row['userPhone'] ?? '');
    $userRole = (string) ($row['userRole'] ?? 'admin');
    if (!in_array($userRole, ['admin', 'usuario'], true)) {
        $userRole = 'admin';
    }
    $useLogo = !empty($row['usePrimaryLogo']);
    $logoRel = (string) ($row['logoRel'] ?? '');
    $logoUrl = '';
    if ($logoRel !== '' && strpos($logoRel, '..') === false) {
        $logoUrl = rtrim($appBase, '/') . '/' . ltrim($logoRel, '/');
    }
    if ($logoUrl === '' && $bid !== '') {
        require_once dirname(__DIR__) . '/includes/install_branch_logos.php';
        $abs = antara_install_branch_logo_resolved_path($bid);
        if ($abs !== null) {
            $logoUrl = rtrim($appBase, '/') . '/logos_sinapsys/' . rawurlencode(basename($abs));
        }
    }

    $title = 'Sucursal ' . ($index + 1);
    $logoHidden = $useLogo ? ' style="display:none"' : '';
    $previewOn = $logoUrl !== '' ? ' is-on' : '';
    $logoChk = $useLogo ? ' checked' : '';
    $userFieldsHidden = $createUser ? '' : ' hidden';
    $userChk = $createUser ? ' checked' : '';

    $parts = [];
    $parts[] = '<div class="branch-row" data-branch-index="' . (int) $index . '" data-branch-primary="0">';
    $parts[] = '<button type="button" class="btn btn-remove-branch" style="float:right;margin-top:0;padding:.25rem .5rem;font-size:.75rem">Quitar</button>';
    $parts[] = '<input type="hidden" name="branch_id[]" value="' . $esc($bid) . '">';
    $parts[] = '<input type="hidden" name="branch_use_primary_logo[' . (int) $index . ']" value="' . ($useLogo ? '1' : '0') . '" class="branch-use-primary-logo-hidden">';
    $parts[] = '<input type="hidden" name="branch_user_create[' . (int) $index . ']" value="' . ($createUser ? '1' : '0') . '" class="branch-user-create-hidden">';
    $parts[] = '<div class="branch-logo-top" data-branch-logo-top>';
    $parts[] = '<label class="branch-check branch-use-logo-check" style="display:block;margin:0 0 .5rem">';
    $parts[] = '<input type="checkbox" class="branch-use-primary-logo" value="1"' . $logoChk . '> Usar el mismo logo que la empresa</label>';
    $parts[] = '<div class="branch-logo-fields" data-branch-logo-fields' . $logoHidden . '>';
    $parts[] = '<label class="branch-logo-upload-label">Imagen / logo de la sucursal</label>';
    $parts[] = '<div class="logo-box branch-logo-box">';
    $parts[] = '<div class="logo-selected-preview branch-logo-preview' . $previewOn . '" aria-live="polite">';
    $parts[] = '<span class="muted logo-selected-preview__caption">Vista previa (confirmada)</span>';
    $parts[] = '<div class="install-logo-media-wrap" data-install-media-wrap>';
    $parts[] = '<img data-antara-profile-img alt="" class="branch-logo-preview-img"' . ($logoUrl !== '' ? ' src="' . $esc($logoUrl) . '"' : ' hidden') . ' />';
    $parts[] = '<span data-antara-profile-ph aria-hidden="true"' . ($logoUrl !== '' ? ' hidden' : '') . '>S</span>';
    $parts[] = '</div>';
    $parts[] = '</div>';
    $parts[] = '<input type="file" name="branch_logo[]" accept="image/png,image/jpeg,image/webp,image/gif,video/mp4,video/webm" class="branch-logo-file install-file-input">';
    $parts[] = '<input type="hidden" name="branch_logo_source[]" value="original" class="branch-logo-source">';
    $parts[] = '<input type="hidden" name="branch_logo_media_frame[]" value="" class="branch-logo-media-frame">';
    $parts[] = '</div></div>';
    $parts[] = '</div>';
    $parts[] = '<h3 class="install-h3" style="margin:0 0 .65rem;font-size:.95rem">' . $esc($title) . '</h3>';
    $parts[] = '<label>Nombre de la sucursal *</label>';
    $parts[] = '<input type="text" name="branch_name[]" maxlength="120" placeholder="Ej. Sucursal Guadalajara" value="' . $esc($name) . '" required>';
    $parts[] = '<div class="branch-contact-block" data-branch-contact>';
    $parts[] = '<div class="branch-address-block" data-branch-address>';
    $parts[] = '<label>Dirección</label>';
    $parts[] = antara_install_render_location_block($location, [
        'mode' => 'branch',
        'esc' => $esc,
        'readonly' => false,
    ]);
    $parts[] = '</div>';
    $parts[] = '<div class="branch-email-phone-block">';
    $parts[] = '<label>Correo de contacto *</label><input type="email" name="branch_email[]" maxlength="200" placeholder="sucursal@empresa.com" value="' . $esc($email) . '" required>';
    $parts[] = '<label>Teléfono *</label><input type="tel" name="branch_phone[]" maxlength="40" class="branch-phone-input install-phone-input" placeholder="+52…" value="' . $esc($phone) . '" required>';
    $parts[] = '</div>';
    $parts[] = '<fieldset class="branch-user-fieldset" data-branch-user-fieldset>';
    $parts[] = '<legend>Cuenta de acceso (opcional)</legend>';
    $parts[] = '<label class="branch-check branch-create-user-check"><input type="checkbox" class="branch-create-user" value="1"' . $userChk . '> Crear perfil de usuario o administrador para esta sucursal</label>';
    $parts[] = '<div class="branch-user-fields" data-branch-user-fields' . $userFieldsHidden . '>';
    $parts[] = '<label>Nombre completo *</label><input type="text" name="branch_user_username[]" maxlength="120" placeholder="Ej. nombre y apellidos" value="' . $esc($userUsername) . '" autocomplete="name">';
    $parts[] = '<label>Correo de la cuenta *</label><input type="email" name="branch_user_email[]" maxlength="200" placeholder="usuario@sucursal.com" value="' . $esc($userEmail) . '">';
    $parts[] = '<label>Teléfono de la cuenta *</label><input type="tel" name="branch_user_phone[]" maxlength="40" class="branch-user-phone-input install-phone-input" placeholder="+52…" value="' . $esc($userPhone) . '">';
    $parts[] = '<label>Rol</label><select name="branch_user_role[]">';
    $parts[] = '<option value="admin"' . ($userRole === 'admin' ? ' selected' : '') . '>Administrador</option>';
    $parts[] = '<option value="usuario"' . ($userRole === 'usuario' ? ' selected' : '') . '>Usuario</option>';
    $parts[] = '</select>';
    $parts[] = '<label>Contraseña *</label><input type="password" name="branch_user_password[]" minlength="8" autocomplete="new-password" placeholder="Mínimo 8 caracteres; letra y número">';
    $parts[] = '<label>Confirmar contraseña *</label><input type="password" name="branch_user_password_confirm[]" minlength="8" autocomplete="new-password" placeholder="Repite la contraseña">';
    $parts[] = '</div></fieldset></div>';
    $parts[] = '</div>';

    return implode('', $parts);
}
