# syntax=docker/dockerfile:1

FROM php:8.3-fpm-alpine AS php_deps

ENV COMPOSER_ALLOW_SUPERUSER=1

RUN set -eux; \
    apk add --no-cache \
        icu-libs \
        libpng \
        libjpeg-turbo \
        freetype \
        libzip \
        imagemagick \
        bash \
        shadow \
        curl \
        git; \
    apk add --no-cache --virtual .build-deps \
        $PHPIZE_DEPS \
        icu-dev \
        libpng-dev \
        libjpeg-turbo-dev \
        freetype-dev \
        libzip-dev \
        imagemagick-dev; \
    docker-php-ext-configure gd --with-freetype --with-jpeg; \
    docker-php-ext-install -j"$(nproc)" \
        bcmath \
        gd \
        intl \
        pcntl \
        pdo_mysql \
        zip \
        opcache; \
    pecl install redis; \
    pecl install imagick; \
    docker-php-ext-enable redis imagick; \
    apk del .build-deps

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

WORKDIR /var/www/html

# Copy full application so artisan is available for composer scripts when desired.
COPY . .

RUN set -eux; \
    composer install --no-dev --prefer-dist --optimize-autoloader --no-interaction --no-progress --no-scripts

FROM node:20-alpine AS frontend_build

WORKDIR /var/www/html

COPY package*.json ./
RUN npm ci --ignore-scripts

COPY resources resources
COPY postcss.config.js tailwind.config.js vite.config.mjs jsconfig.json ./
COPY --from=php_deps /var/www/html/vendor/filament/filament/resources /var/www/html/vendor/filament/filament/resources
COPY --from=php_deps /var/www/html/vendor/filament/support/resources /var/www/html/vendor/filament/support/resources

RUN npm run build

FROM php_deps AS php_build

COPY --from=frontend_build /var/www/html/public/build /var/www/html/public/build

RUN set -eux; \
    mkdir -p storage/app/public storage/logs bootstrap/cache; \
    chown -R www-data:www-data storage bootstrap/cache; \
    ln -snf /var/www/html/storage/app/public /var/www/html/public/storage

FROM php_build AS php_app

EXPOSE 9000

CMD ["php-fpm"]

FROM nginx:alpine AS nginx

WORKDIR /var/www/html

COPY --from=php_app /var/www/html/public /var/www/html/public
COPY --from=php_app /var/www/html/storage/app/public /var/www/html/storage/app/public

COPY docker/nginx/default.conf /etc/nginx/conf.d/default.conf

EXPOSE 80
