# Usa a imagem oficial de PHP 8.3-FPM como base
FROM php:8.3.36-fpm

ARG ELASTIC_APM_VERSION=1.15.0
ARG ARCH=linux-x86_64

# Instalar Nginx, procps, dependencias necesarias y php-gd
RUN apt-get update && apt-get install -y --no-install-recommends \
    nginx \
    openssl \
    procps \
    curl \
    nano \
    git \
    unzip \
    wget \
    libpq-dev \
    libjpeg-dev \
    libpng-dev \
    libfreetype6-dev \
    libzip-dev \
    libz-dev \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install gd pdo_pgsql pgsql zip \
    && pecl install redis \
    && docker-php-ext-enable redis \
    && apt-get clean && rm -rf /var/lib/apt/lists/*

# Instala o agente Elastic APM (baixando do GitHub Releases)
WORKDIR /tmp
RUN wget https://github.com/elastic/apm-agent-php/releases/download/v1.15.0/apm-agent-php-linux-x86-64.tar \
    && tar -xvf apm-agent-php-linux-x86-64.tar \
    && cp -r ./opt/elastic /opt/elastic \
    && PHP_API=$(php -i | grep '^PHP API' | awk '{print $4}') \
    && cp ./opt/elastic/apm-agent-php/extensions/elastic_apm-${PHP_API}.so $(php -i | grep "^extension_dir" | awk '{print $3}')/elastic_apm.so \
    && rm -rf /tmp/apm-agent-php-linux-x86-64.tar

# Configurar Nginx
COPY nginx/default /etc/nginx/sites-available/default
# COPY nginx/php.ini /usr/local/etc/php/php.ini
COPY nginx/www.conf /usr/local/etc/php-fpm.d/www.conf

# Copiar arquivos da aplicação
COPY . /var/www/html

# Criar diretórios necessários e configurar permissões
RUN mkdir -p /run/php/ && chown www-data:www-data /run/php/ \
    && mkdir -p mnt/logs_web/web /temp/aex /temp/facturas /temp/archivos /temp/session_php /mnt/cdn_pagopar/datos/archivos/conciliacion \
    && chown -R www-data:www-data mnt/logs_web/web /temp/aex /temp/facturas /temp/archivos /temp/session_php \
    && chmod -R 775 mnt/logs_web/web /temp/aex /temp/facturas /temp/archivos /tmp \
    && chown -R www-data:www-data /var/www/html /tmp /mnt/cdn_pagopar/datos/archivos/conciliacion \
    && chmod 700 /var/www/html


# Expor portas HTTP e HTTPS
EXPOSE 80 443

# Healthcheck básico
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s CMD curl -f http://localhost/ || exit 1

# Comando de inicialização
CMD ["sh", "-c", "php-fpm -D && nginx -g 'daemon off;'"]
