# Multi-stage build for production optimization
FROM php:8.2-fpm-alpine as base

# Install system dependencies
RUN apk add --no-cache \
    bash \
    curl \
    freetype-dev \
    freetype-dev \
    g++ \
    gcc \
    git \
    gpg \
    icu-dev \
    icu-libs \
    icu-dev \
    libc-dev \
    libjpeg-turbo-dev \
    libpng-dev \
    libzip-dev \
    make \
    mysql-client \
    nginx \
    openldap-dev \
    rsync \
    rsync \
    zlib-dev

# Configure PHP
RUN docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install \
    bcmath \
    gd \
    intl \
    mysqli \
    opcache \
    pdo \
    pdo_mysql \
    zip

# Install Composer
COPY --from=composer:2.5 /usr/bin/composer /usr/bin/composer

# Set working directory
WORKDIR /var/www

# Production stage
FROM base as production

# Copy PHP configuration
COPY docker/php/production.ini /usr/local/etc/php/conf.d/custom.ini
COPY docker/nginx/default.conf /etc/nginx/conf.d/default.conf

# Install PHP dependencies and application
COPY composer.json composer.lock ./
RUN composer install --no-dev --optimize-autoloader --no-interaction

# Copy application code
COPY . .

# Create non-root user
RUN addgroup -g 1000 -S www && \
    adduser -S www -G www && \
    chown -R www:www /var/www && \
    chmod -R 755 /var/www/storage

# Expose ports
EXPOSE 80

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD curl -f http://localhost/health || exit 1

# Start services
CMD ["sh", "-c", "php-fpm && nginx -g 'daemon off;'"]

# Development stage
FROM base as development

# Install development dependencies
RUN apk add --no-cache \
    nodejs \
    npm \
    yarn

# Copy composer files
COPY composer.json composer.lock ./
RUN composer install --dev --no-interaction

# Copy application code
COPY . .

# Set development permissions
RUN chown -R www:www /var/www

# Expose PHP port
EXPOSE 9000

# Start PHP-FPM for development
CMD ["php-fpm"]