FROM php:8.4-fpm-alpine3.23

ENV APP_ENV=production
ENV APP_DEBUG=false

WORKDIR /var/www

RUN apk update && apk add --no-cache \
    build-base \
    libpng-dev \
    libjpeg-turbo-dev \
    freetype-dev \
    zip \
    jpegoptim optipng pngquant gifsicle \
    vim \
    unzip \
    git \
    curl \
    libzip-dev \
    oniguruma-dev \
    nodejs \
    npm \
    icu-dev \
    sqlite-dev \
    sqlite-libs \
    nginx \
    supervisor \
    su-exec \
    tini 

RUN rm -rf /var/cache/apk/*

RUN docker-php-ext-install mbstring zip exif pcntl intl gd pdo pdo_sqlite bcmath

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# RUN addgroup -g 1000 www
# RUN adduser -u 1000 -G www -s /bin/sh -D www

# # Configure PHP-FPM to run as www user
# RUN sed -i 's/user = www-data/user = www/g' /usr/local/etc/php-fpm.d/www.conf && \
#     sed -i 's/group = www-data/group = www/g' /usr/local/etc/php-fpm.d/www.conf

# Copy application code (includes database/migrations/)
COPY . /var/www


# DEBUG - SHOW ME WHAT WAS COPIED
# RUN echo "===== CONTENTS OF /var/www/database =====" && ls -la /var/www/database/
# RUN echo "===== CONTENTS OF /var/www/database/migrations =====" && ls -la /var/www/database/migrations/



# Install dependencies
RUN composer install --optimize-autoloader --no-dev
RUN npm install
RUN npm run build

# Copy entrypoint script
COPY cmd/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh


# add supervisord config and a log dir (kept before switching to non-root user)
COPY ./docker/supervisord.conf /etc/supervisord.conf
RUN mkdir -p /var/log/supervisor \
    && mkdir -p /run/nginx /var/cache/nginx /var/lib/nginx /var/tmp/nginx \
    && chown -R root:root /run/nginx /var/cache/nginx /var/lib/nginx /var/tmp/nginx 

# Test nginx config at build time
RUN nginx -t

# keep running as root so supervisord starts nginx/php-fpm as root (nginx needs root for master process)
# we will use su-exec in entrypoint to run maintenance steps as www, preserving previous behaviour

EXPOSE 8889

# Keep entrypoint script as before; entrypoint runs startup tasks then supervisord becomes PID 1
# ENTRYPOINT ["docker-entrypoint.sh"]
# CMD ["/usr/bin/supervisord", "-n", "-c", "/etc/supervisord.conf"]

ENTRYPOINT ["/sbin/tini", "--", "/usr/local/bin/docker-entrypoint.sh"]
CMD ["/usr/bin/supervisord", "-n", "-c", "/etc/supervisord.conf"]
