FROM php:8.2-apache

# ── System deps ──────────────────────────────────────────────────────────────
RUN apt-get update && apt-get install -y \
    libpng-dev libjpeg-dev libfreetype6-dev \
    libzip-dev libonig-dev libxml2-dev \
    zip unzip curl \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install pdo pdo_mysql mbstring zip gd xml opcache \
    && apt-get clean && rm -rf /var/lib/apt/lists/*

# ── Apache config ────────────────────────────────────────────────────────────
ENV APACHE_DOCUMENT_ROOT=/var/www/html/public

RUN sed -i 's|DocumentRoot /var/www/html|DocumentRoot /var/www/html/public|g' \
    /etc/apache2/sites-available/000-default.conf \
    && sed -i '/<Directory \/var\/www\/>/,/<\/Directory>/ s/AllowOverride None/AllowOverride All/' \
    /etc/apache2/apache2.conf \
    && echo '<Directory /var/www/html/public>\n    AllowOverride All\n    Require all granted\n</Directory>' \
    >> /etc/apache2/apache2.conf \
    && a2enmod rewrite

# ── PHP settings (errors ON for now so we can debug) ─────────────────────────
RUN echo "display_errors = On\n\
    error_reporting = E_ALL\n\
    log_errors = On\n\
    error_log = /proc/self/fd/2\n\
    upload_max_filesize = 20M\n\
    post_max_size = 22M\n\
    memory_limit = 256M\n\
    max_execution_time = 60\n\
    opcache.enable = 1\n\
    opcache.memory_consumption = 128\n\
    opcache.validate_timestamps = 1" > /usr/local/etc/php/conf.d/app.ini

WORKDIR /var/www/html
COPY . .

# ── Make sure public/.htaccess exists for routing ────────────────────────────
RUN if [ ! -f public/.htaccess ]; then \
    echo '<IfModule mod_rewrite.c>\n\
    RewriteEngine On\n\
    RewriteCond %{REQUEST_FILENAME} !-f\n\
    RewriteCond %{REQUEST_FILENAME} !-d\n\
    RewriteRule ^(.*)$ index.php [QSA,L]\n\
    </IfModule>' > public/.htaccess; \
    fi

# ── Directories & permissions ────────────────────────────────────────────────
RUN mkdir -p storage/logs storage/uploads \
    && chown -R www-data:www-data /var/www/html \
    && chmod -R 775 storage

EXPOSE 80

CMD ["apache2-foreground"]