# 1. Composer Builder Stage
FROM php:8.4-cli-alpine AS composer-builder
RUN apk add --no-cache unzip
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
WORKDIR /app
COPY composer.json composer.lock ./
# Note: ignoring platform requirements since mongo/redis aren't natively in this alpine CLI image
RUN composer install --no-dev --no-scripts --no-autoloader --prefer-dist --ignore-platform-reqs
COPY ./ ./
RUN composer dump-autoload --optimize --no-dev

# 2. Node Builder Stage
FROM node:22-alpine AS node-builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY ./ ./
# Copy vendor from composer-builder because Vite needs to process CSS from packages (e.g. livewire/flux)
COPY --from=composer-builder /app/vendor ./vendor
RUN npm run build

# 3. Production Stage
FROM php:8.4-fpm-alpine
WORKDIR /var/www/html

# Install mlocati/php-extension-installer
COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/

# Install system dependencies
RUN apk add --no-cache \
    nginx \
    supervisor \
    git

# Install PHP extensions (handles all build deps automatically)
RUN install-php-extensions \
    pdo_mysql \
    gd \
    zip \
    intl \
    bcmath \
    pcntl \
    opcache \
    sockets \
    mongodb \
    redis

# Copy source code and vendor dependencies
COPY . .
COPY --from=composer-builder /app/vendor ./vendor
COPY --from=node-builder /app/public/build ./public/build

# Copy configuration files
COPY docker/nginx.conf /etc/nginx/http.d/default.conf
COPY docker/php-fpm.conf /usr/local/etc/php-fpm.d/www.conf
COPY docker/php.ini /usr/local/etc/php/conf.d/production.ini
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
COPY docker/entrypoint.sh /usr/local/bin/entrypoint.sh

# Make entrypoint executable
RUN chmod +x /usr/local/bin/entrypoint.sh

EXPOSE 80

ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
