# Backend - Laravel with PHP-FPM multi-stage build
FROM php:8.4-fpm-alpine AS builder

# Install system dependencies
RUN apk add --no-cache \
    git \
    unzip \
    libzip-dev \
    libxml2-dev \
    oniguruma-dev \
    $PHPIZE_DEPS

# Install PHP extensions
RUN docker-php-ext-install \
    pdo_mysql \
    mbstring \
    exif \
    pcntl \
    bcmath \
    xml \
    zip

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

WORKDIR /app

# Copy application files
COPY . .

# Install PHP dependencies
RUN composer install \
    --no-interaction \
    --prefer-dist \
    --optimize-autoloader \
    --no-dev

# Production stage
FROM php:8.4-fpm-alpine

# Install runtime dependencies only (su-exec untuk drop privilege di entrypoint)
RUN apk add --no-cache \
    libzip \
    oniguruma \
    libxml2 \
    su-exec

# Install only required PHP extensions
RUN apk add --no-cache --virtual .build-deps \
    oniguruma-dev \
    libxml2-dev \
    && docker-php-ext-install \
    pdo_mysql \
    mbstring \
    exif \
    pcntl \
    bcmath \
    xml \
    && apk del .build-deps

# Note: www-data user already exists in php-fpm-alpine image

WORKDIR /app

# Copy app from builder
COPY --from=builder --chown=www-data:www-data /app /app

# Create storage and cache directories
RUN mkdir -p storage/logs storage/framework/sessions storage/framework/cache bootstrap/cache && \
    chown -R www-data:www-data /app

# Copy PHP-FPM config
COPY --chown=www-data:www-data php-fpm.conf /usr/local/etc/php-fpm.d/www.conf

# Copy entrypoint (jalankan migrasi/seed lalu start php-fpm)
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

# Catatan: container start sebagai root agar entrypoint dapat memperbaiki izin
# named volume, lalu menurunkan hak akses ke www-data via su-exec.

EXPOSE 9000

HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=5 \
  CMD php -r "exit(extension_loaded('pdo_mysql') ? 0 : 1);" || exit 1

ENTRYPOINT ["docker-entrypoint.sh"]
