FROM php:8.3-apache

# Install system dependencies
RUN apt-get update && apt-get install -y \
    git \
    curl \
    libsqlite3-dev \
    libssl-dev \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    zip \
    unzip

# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Recompile PHP with larger FD_SETSIZE
RUN docker-php-source extract \
    && cd /usr/src/php \
    && ./configure \
        --enable-fd-setsize=8192 \
        --with-config-file-path=/usr/local/etc/php \
        --with-config-file-scan-dir=/usr/local/etc/php/conf.d \
        --enable-option-checking=fatal \
        --with-pdo-mysql \
        --enable-mysqlnd \
        --with-sqlite3 \
        --enable-bcmath \
        --enable-sockets \
        --with-openssl \
        --enable-mbstring \
        --enable-exif \
        --enable-pcntl \
    && make \
    && make install \
    && docker-php-source delete

# Copy PHP configuration
COPY docker/php/custom.ini /usr/local/etc/php/conf.d/

# Enable Apache modules
RUN a2enmod rewrite

# Install Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Set working directory
WORKDIR /var/www/html

# Set Composer configuration
ENV COMPOSER_ALLOW_SUPERUSER=1

# Copy composer files and lib directory first
COPY composer.json ./
COPY lib/ ./lib/

# Install composer dependencies
RUN composer install --no-interaction --no-scripts

# Copy Apache configuration
COPY docker/apache/000-default.conf /etc/apache2/sites-available/000-default.conf

# Copy application files
COPY . /var/www/html/

# Set permissions
RUN chown -R www-data:www-data /var/www/html \
    && chmod -R 755 /var/www/html

# Remove default SSL configuration to avoid conflicts
RUN rm -f /etc/apache2/sites-enabled/default-ssl.conf

# Expose port
EXPOSE 80

# Start Apache
CMD ["apache2-foreground"]
