# ==========================================
# STAGE 1: Build Stage (Optional Dependency Prefetching)
# ==========================================
FROM composer:latest AS builder
# If you don't have production app assets to copy yet, this stage can remain idle.

# ==========================================
# STAGE 2: Final PHP Environment
# ==========================================
FROM php:8.5-fpm-bookworm

RUN usermod -u 1000 www-data && groupmod -g 1000 www-data

# Set work directory matching standard web server setups
WORKDIR /var/www/test-fhr

# Install Linux system dependencies needed for common PHP extensions
RUN apt-get update && apt-get install -y --no-install-recommends \
    libpng-dev \
    libjpeg-dev \
    libfreetype6-dev \
    libzip-dev \
    unzip \
    git \
    && rm -rf /var/lib/apt/lists/*

# Configure and install PHP extensions
RUN docker-php-ext-configure gd --with-freetype --with-jpeg
RUN docker-php-ext-install -j$(nproc) gd bcmath pdo_mysql zip
RUN pecl install redis && docker-php-ext-enable redis

# Recommended production PHP configurations
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
COPY ./opcache.ini $PHP_INI_DIR/conf.d/opcache.ini

# ----------------------------------------------------
# COMPOSER & LARAVEL INSTALLER (Safe Direct Method)
# ----------------------------------------------------
# 1. Pull the official global Composer executable binary
COPY --from=builder /usr/bin/composer /usr/local/bin/composer

# 2. Configure user bash profile and aliases
COPY --chown=www-data:www-data ./.bash_aliases /var/www/.bash_aliases
RUN echo "source /var/www/.bash_aliases" >> /var/www/.bashrc

# 3. FIX: Ensure BOTH the home directory and the project directory are owned by www-data
RUN mkdir -p /var/www/.composer /var/www/test-fhr && chown -R www-data:www-data /var/www

# 4. Register the Composer global binaries directory path into the container system
ENV PATH="/var/www/.composer/vendor/bin:${PATH}"

# 5. Switch context to non-root user so paths and permissions map correctly
USER www-data

# 6. Download and unpack the Laravel installer directly into www-data's profile folder
RUN composer global require laravel/installer --no-interaction

# Expose PHP-FPM default communication port
EXPOSE 9000

CMD ["php-fpm"]
