# Use PHP 8.4 with Apache
FROM php:8.4-apache

# Set timezone
ENV TZ=Europe/London
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

# Install system dependencies
RUN apt-get update && apt-get install -y \
    git \
    zip \
    curl \
    sudo \
    unzip \
    wget \
    pkg-config \
    libzip-dev \
    libicu-dev \
    libbz2-dev \
    libpng-dev \
    libjpeg-dev \
    libmcrypt-dev \
    libreadline-dev \
    libfreetype6-dev \
    libmagickwand-dev \
    libmagickcore-dev \
    imagemagick \
    g++ \
    default-mysql-client \
    libgomp1 \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install \
        gd \
        zip \
        bz2 \
        intl \
        soap \
        iconv \
        bcmath \
        gettext \
        opcache \
        calendar \
        pdo_mysql \
        exif

# Ensure ImageMagick config path is correct
ENV PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig/

# Install Imagick with fallback
# Manual build from GitHub (fallback if PECL fails)
RUN git clone https://github.com/Imagick/imagick.git \
    && cd imagick \
    && phpize \
    && ./configure \
    && make \
    && make install \
    && docker-php-ext-enable imagick

# Ensure ImageMagick convert is accessible at /usr/local/bin/convert
RUN ln -s /usr/bin/convert /usr/local/bin/convert

# Enable Apache modules
RUN a2enmod rewrite expires filter mime

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

# Install Node.js 16
RUN curl -sL https://deb.nodesource.com/setup_22.x | bash - \
    && apt-get install -y nodejs

# Set working directory
WORKDIR /var/www/html

# Copy Apache configuration from the project root
COPY .docker/apache/vhost.conf /etc/apache2/sites-available/000-default.conf

# Copy pre-configured PHP settings
COPY .docker/config/php.ini /usr/local/etc/php/conf.d/custom.ini

# Expose Apache port (HTTP only)
EXPOSE 80

CMD ["apache2-foreground"]

# Create an app user with a fixed UID/GID (matches most dev machines)
RUN groupadd -g 1000 appuser && useradd -u 1000 -g 1000 -m appuser

# Optional: ensure the app user owns the web root
RUN chown -R appuser:appuser /var/www/html

# Switch to appuser for all commands (npm, artisan, etc.)
USER appuser
