# This stage uses the 'composer' base image, which already has PHP and Composer installed.
FROM composer:latest AS composer_build

# Define the build argument to receive the cache path from the CI script
# This links to the cache GitLab sets up on the VPS host.
ARG COMPOSER_CACHE_DIR_ARG="/tmp/cache"

WORKDIR /app

# Copy only the files needed for dependency installation first
COPY composer.json composer.lock ./

# Mount the GitLab-provided cache directory during the build
# This command is run inside the Docker build process
RUN --mount=type=cache,target=/root/.composer \
    composer install --no-dev --prefer-dist --optimize-autoloader --no-interaction \
    --working-dir=/app

# Use official PHP with Apache
FROM php:8.2-apache

RUN apt-get update && apt-get install -y \
    # 1. Install system library needed for zip extension
    libzip-dev \
    # 2. Clean up cache (best practice)
    && rm -rf /var/lib/apt/lists/* \
    # 3. Install only the required PHP extension (zip)
    && docker-php-ext-install zip

# Enable Apache rewrite (optional, useful for .htaccess)
RUN a2enmod rewrite

# Copy project files into container
COPY . /var/www/html/

# Set working directory
WORKDIR /var/www/html

# Set permissions (safe defaults)
RUN chown -R www-data:www-data /var/www/html \
    && chmod -R 755 /var/www/html

# Expose port 80
EXPOSE 80