FROM php:8.5-fpm AS base

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        git \
        unzip \
        libzip-dev \
        libmemcached-dev \
        zlib1g-dev \
        libssl-dev \
        libjpeg-dev \
        libpng-dev \
        libwebp-dev \
        libldap2-dev \
    && pecl install memcached \
    && docker-php-ext-enable memcached \
    && docker-php-ext-configure gd --with-jpeg --with-webp \
    && docker-php-ext-install pdo_mysql mysqli gd zip ldap \
    && rm -rf /var/lib/apt/lists/*

COPY --from=composer:2 /usr/bin/composer /usr/bin/composer

WORKDIR /var/www

# ── Development profile (default) ────────────────────────────────────
FROM base AS dev

RUN pecl install xdebug \
    && docker-php-ext-enable xdebug

COPY docker/php/php.ini /usr/local/etc/php/conf.d/zzz-minty-dev.ini
COPY docker/php/xdebug.ini /usr/local/etc/php/conf.d/zzz-xdebug.ini

# ── Production profile ───────────────────────────────────────────────
# No xdebug — smaller image, no debug overhead or attack surface.
FROM base AS prod

# Copy entire project into image
COPY . /var/www

# Install composer dependencies (no dev dependencies for production).
# NOTE: php.prod.ini (with open_basedir + disable_functions) is copied AFTER
# this step — composer needs unrestricted access to its own phar at /usr/bin/.
RUN composer install \
    --no-dev \
    --no-interaction \
    --optimize-autoloader \
    && rm -rf /root/.composer/cache

# Apply production PHP hardening AFTER composer is done.
COPY docker/php/php.prod.ini /usr/local/etc/php/conf.d/zzz-minty-prod.ini

# Publish module web assets as real files (not symlinks) so web_init cp works correctly.
# Symlinks from web/modules/<id> → modules/<id>/web are replaced by actual copies,
# because web_init uses "cp -rp" which follows symlinks only to directories, not files.
RUN find /var/www/web/modules -maxdepth 1 -mindepth 1 -type l | while read link; do \
        id=$(basename "$link"); \
        target=$(readlink "$link"); \
        rm "$link"; \
        cp -r "$target" "/var/www/web/modules/$id"; \
    done || true

# Create runtime directories (storage/ and var/ are excluded via .dockerignore;
# they will be mounted as volumes in production — we just ensure the paths exist).
RUN mkdir -p \
        /var/www/storage/logs \
        /var/www/storage/runtime \
        /var/www/storage/users \
        /var/www/var/cache \
        /var/www/var/log \
        /var/www/var/tmp \
    && chown -R www-data:www-data \
        /var/www/storage \
        /var/www/var

# Expose port for PHP-FPM
EXPOSE 9000