FROM php:8.2-apache

# System deps
RUN apt-get update && apt-get install -y --no-install-recommends \
        git unzip libzip-dev libpng-dev libjpeg-dev libfreetype6-dev \
        libonig-dev libxml2-dev default-mysql-client \
        cron supervisor \
    && rm -rf /var/lib/apt/lists/*

# PHP extensions
RUN docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) \
        pdo pdo_mysql mbstring zip gd bcmath opcache intl

# Apache modules + config
RUN a2enmod rewrite headers expires deflate
COPY docker/apache-vhost.conf /etc/apache2/sites-available/000-default.conf

# PHP config overrides
COPY docker/php.ini /usr/local/etc/php/conf.d/99-custom.ini

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

# App
WORKDIR /var/www/html
COPY . /var/www/html

# Permissions for storage
RUN mkdir -p storage/logs storage/cache storage/documents storage/backups \
    && chown -R www-data:www-data storage \
    && chmod -R 0750 storage

# Install deps as www-data
RUN set -e; \
    if [ -f composer.json ]; then \
        composer install --no-interaction --prefer-dist --no-progress --optimize-autoloader || true; \
    fi

# Cron runner
COPY docker/run-crons.sh /usr/local/bin/run-crons.sh
RUN chmod +x /usr/local/bin/run-crons.sh

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

EXPOSE 80
CMD ["apache2-foreground"]