# Base image: PHP 8.2 with FPM
FROM php:8.2-fpm

# Install necessary system dependencies
RUN apt-get update && apt-get install -y \
    git \
    unzip \
    libonig-dev \
    libpq-dev \
    libzip-dev \
    libcurl4-openssl-dev \
    libpng-dev \
    libjpeg62-turbo-dev \
    libfreetype6-dev \
    libxml2-dev \
    default-mysql-client \
    redis-server \
    nginx \
    && docker-php-ext-install \
    mysqli \
    pdo \
    pdo_mysql \
    zip \
    bcmath \
    sockets

# Build and enable common extensions required by Composer dependencies
RUN docker-php-ext-configure gd --with-freetype --with-jpeg \
 && docker-php-ext-install -j$(nproc) gd mbstring dom simplexml

# Install and enable PHP Redis extension for session storage
RUN pecl install redis \
    && docker-php-ext-enable redis

# Set working directory
WORKDIR /var/www/html

# Copy application code
COPY . /var/www/html

# Copy Nginx configuration file
COPY nginx.conf /etc/nginx/nginx.conf

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

# Runtime bootstrap: lightweight entrypoint to ensure Composer deps exist when app is bind-mounted
COPY services/php/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN sed -i 's/\r$//' /usr/local/bin/docker-entrypoint.sh \
    && chmod +x /usr/local/bin/docker-entrypoint.sh

# Install PHP dependencies through Composer (only where composer.json exists)
# Main app dependencies
RUN set -e \
 && if [ -f /var/www/html/services/nginx/app/composer.json ]; then \
      COMPOSER_ALLOW_SUPERUSER=1 composer install --no-dev --optimize-autoloader -d /var/www/html/services/nginx/app; \
    else \
      echo "No composer.json in /var/www/html/services/nginx/app — skipping"; \
    fi \
 && if [ -f /var/www/html/services/nginx/app/modules/washcertificates/composer.json ]; then \
      COMPOSER_ALLOW_SUPERUSER=1 composer install --no-dev --optimize-autoloader -d /var/www/html/services/nginx/app/modules/washcertificates; \
    else \
      echo "No composer.json in washcertificates module — skipping"; \
    fi

# Set permissions for the web server
RUN chown -R www-data:www-data /var/www/html && chmod -R 755 /var/www/html

# Expose port 80 (HTTP) and 443 (HTTPS)
EXPOSE 80 443

# Default entrypoint ensures vendor/autoload.php exists, then executes the given command (overridden by docker-compose)
ENTRYPOINT ["docker-entrypoint.sh"]

# Start services when no command is provided (docker-compose overrides this with ["php-fpm"]) 
CMD ["php-fpm"]
