# ==========================================
# STAGE 1: Composer (Install PHP Packages)
# ==========================================
FROM php:8.4-cli-alpine AS composer-builder
WORKDIR /app

# Install git, zip, and unzip (required by Composer to fetch packages)
RUN apk add --no-cache git unzip zip

# Copy Composer binary from the official image
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer

# Copy Composer files and install production dependencies
COPY composer.json composer.lock* ./
RUN composer install --no-dev --no-scripts --no-autoloader --prefer-dist --no-interaction

# Copy the rest of the application files and generate optimized autoload
COPY . .
RUN composer dump-autoload --no-dev --optimize --no-interaction

# ==========================================
# STAGE 2: Node.js (Build Frontend Assets)
# ==========================================
FROM node:20-alpine AS node-builder
WORKDIR /app

# Copy dependency files and install packages
COPY package*.json ./
RUN npm ci

# Copy all files
COPY . .

# Copy vendor directory from Composer stage so TypeScript/Vite can find Ziggy
COPY --from=composer-builder /app/vendor /app/vendor

# Compile assets via Vite
RUN npm run build

# ==========================================
# STAGE 3: Final Production Image (PHP-FPM)
# ==========================================
FROM php:8.4-fpm-alpine
WORKDIR /var/www/html

# Install mlocati PHP extension installer to easily set up production modules
COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/

# Install required PHP extensions for Laravel, Vite, and Redis
RUN chmod +x /usr/local/bin/install-php-extensions && \
    install-php-extensions pdo_mysql bcmath gd zip opcache redis

# Set up production PHP configuration
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
COPY docker/opcache.ini /usr/local/etc/php/conf.d/opcache.ini

# Copy Laravel codebase and Vendor dependencies from Stage 1 (Composer)
COPY --from=composer-builder --chown=www-data:www-data /app /var/www/html

# Copy compiled CSS/JS assets from Stage 2 (Node)
COPY --from=node-builder --chown=www-data:www-data /app/public/build /var/www/html/public/build

# Set permissions for storage & bootstrap cache directories
RUN chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache && \
    chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache

# Run container as non-root user for security
USER www-data

EXPOSE 9000
CMD ["php-fpm"]
