### ===============================
### STAGE 1: COMPOSER (PHP 8.3)
### ===============================
FROM dunglas/frankenphp:1-php8.3 AS composer

WORKDIR /app

RUN apt-get update && apt-get install -y \
    libpng-dev libjpeg-dev libfreetype6-dev \
    libzip-dev libicu-dev pkg-config \
 && docker-php-ext-configure gd --with-freetype --with-jpeg \
 && docker-php-ext-install gd zip intl exif \
 && rm -rf /var/lib/apt/lists/*

COPY --from=composer:2 /usr/bin/composer /usr/bin/composer

COPY artisan artisan
COPY bootstrap bootstrap
COPY config config
COPY app app
COPY routes routes
COPY database database
COPY public public

# 🔥 INI YANG KURANG SELAMA INI
RUN mkdir -p \
    storage/framework/cache \
    storage/framework/sessions \
    storage/framework/views \
    bootstrap/cache

COPY composer.json composer.lock ./

RUN composer install --no-dev --optimize-autoloader --no-interaction

### ===============================
### STAGE 2: FRONTEND BUILD
### ===============================
FROM node:20-alpine AS frontend

WORKDIR /app

# Vendor DIBUTUHKAN oleh Filament
COPY --from=composer /app/vendor vendor

COPY package*.json ./
RUN npm install

COPY resources resources
COPY vite.config.* .
COPY tailwind.config.* .
COPY postcss.config.* .

RUN npm run build


### ===============================
### STAGE 3: RUNTIME
### ===============================
FROM dunglas/frankenphp:1-php8.3

ENV SERVER_NAME=":80"
WORKDIR /app

# PHP extensions runtime
RUN apt-get update && apt-get install -y \
    libpng-dev libjpeg-dev libfreetype6-dev \
    libzip-dev libicu-dev pkg-config \
    supervisor \
 && docker-php-ext-configure gd --with-freetype --with-jpeg \
 && docker-php-ext-install gd pdo pdo_mysql zip bcmath intl exif \
 && rm -rf /var/lib/apt/lists/*

# App source
COPY . .

# Vendor & assets
COPY --from=composer /app/vendor vendor
COPY --from=frontend /app/public/build public/build
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf

RUN chown -R www-data:www-data storage bootstrap/cache \
 && chmod -R 775 storage bootstrap/cache

RUN php artisan optimize:clear || true
