# --- Stage 1: compile Tailwind CSS --------------------------------------
# Runs the Tailwind JIT over views/, src/, and our JS so only classes that
# are actually referenced end up in the output. No runtime <style> injection,
# which lets the CSP drop 'unsafe-inline' for style-src.
FROM node:20-alpine AS css-builder

WORKDIR /build
COPY package.json package-lock.json* ./
RUN npm ci --no-audit --no-fund

# Only the files that contribute to class discovery / the entry stylesheet.
COPY tailwind.config.js ./
COPY assets/css/input.css ./assets/css/input.css
COPY views/ ./views/
COPY src/ ./src/
COPY public/assets/js/ ./public/assets/js/

RUN npx tailwindcss -i ./assets/css/input.css -o /build/app.css --minify

# --- Stage 2: the actual PHP runtime ------------------------------------
FROM php:8.3-apache

RUN apt-get update && apt-get install -y --no-install-recommends \
        libsqlite3-dev unzip git \
    && docker-php-ext-install pdo pdo_sqlite \
    && a2enmod rewrite \
    && rm -rf /var/lib/apt/lists/*

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

WORKDIR /var/www/html

COPY composer.json composer.lock* ./
RUN composer install --no-dev --no-interaction --prefer-dist --no-progress

COPY . .

# Place the compiled CSS where Apache can serve it.
COPY --from=css-builder /build/app.css /var/www/html/public/assets/css/app.css

# Write a clean Apache site config pointing at public/ and routing every
# unmatched URL to the front controller via FallbackResource. That replaces
# the need for .htaccess rewrites (the .htaccess is kept as defense-in-depth
# for deployments that don't use this image).
RUN mkdir -p /var/www/data /var/www/data/sessions \
    && chown -R www-data:www-data /var/www/data \
    && printf '%s\n' \
        '<VirtualHost *:80>' \
        '    DocumentRoot /var/www/html/public' \
        '    <Directory /var/www/html/public>' \
        '        Options -Indexes +FollowSymLinks' \
        '        AllowOverride All' \
        '        Require all granted' \
        '        FallbackResource /index.php' \
        '    </Directory>' \
        '    ErrorLog ${APACHE_LOG_DIR}/error.log' \
        '    CustomLog ${APACHE_LOG_DIR}/access.log combined' \
        '</VirtualHost>' \
        > /etc/apache2/sites-available/000-default.conf

EXPOSE 80
CMD ["apache2-foreground"]
