# ----------------------
# Stage 1: PHP (Laravel + Vite Build)
# ----------------------
FROM php:8.2-fpm AS app

# Install PHP extensions
RUN apt-get update && apt-get install -y \
    libpng-dev libonig-dev libxml2-dev zip unzip git curl nodejs npm \
    && docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd

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

# Set working directory
WORKDIR /var/www

# Copy Laravel source
COPY . .

# Install PHP dependencies
RUN composer install --no-dev --optimize-autoloader

RUN composer require spatie/laravel-permission

RUN php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"

# Build frontend (Vite)
RUN npm install && npm run build

# Set permissions
RUN chown -R www-data:www-data storage bootstrap/cache

# Create storage symlink (idempotent)
# RUN php artisan storage:link || true

CMD ["php-fpm"]

# ----------------------
# Stage 2: Nginx
# ----------------------
FROM nginx:alpine AS nginx

WORKDIR /var/www

# Copy Laravel app with built assets
COPY --from=app /var/www /var/www

# Copy custom Nginx config
COPY ./nginx.conf /etc/nginx/conf.d/default.conf
