# Simple and stable Dockerfile for Laravel + Vue
FROM php:8.2-fpm

# Set working directory
WORKDIR /var/www/html

# Install system dependencies (include build deps for PHP extensions)
RUN set -eux; \
    apt-get update; \
    # build tools and image processing libs
    apt-get install -y --no-install-recommends \
        ca-certificates \
        gnupg \
        git \
        curl \
        unzip \
        zip \
        nginx \
        supervisor \
        build-essential \
        autoconf \
        pkg-config \
        libpng-dev \
        libjpeg-dev \
        libfreetype6-dev \
        libonig-dev \
        libxml2-dev \
        libzip-dev \
        libsqlite3-dev \
    ; \
    rm -rf /var/lib/apt/lists/*

# Install Node.js 22 (needed for Vite build)
RUN set -eux; \
    curl -fsSL https://deb.nodesource.com/setup_22.x | bash -; \
    apt-get update; \
    apt-get install -y --no-install-recommends nodejs; \
    rm -rf /var/lib/apt/lists/*

# Install PHP extensions (gd/sqlite are commonly needed)
RUN set -eux; \
    # configure gd to use system libs
    docker-php-ext-configure gd --with-freetype --with-jpeg || docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/; \
    docker-php-ext-install -j"$(nproc)" \
        bcmath \
        exif \
        gd \
        mbstring \
        opcache \
        pcntl \
        pdo_mysql \
        pdo_sqlite \
        sqlite3 \
        zip; \
    # remove build deps to keep image small
    apt-get purge -y --auto-remove build-essential autoconf pkg-config; \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

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

# Copy composer files first for better caching
COPY composer.json composer.lock ./

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

# Copy package.json for npm dependencies
COPY package.json package-lock.json* ./

# Install Node dependencies required for build (Vite lives in devDependencies)
RUN npm ci

# Copy application code
COPY . .

# Set proper permissions
RUN chown -R www-data:www-data /var/www/html \
    && chmod -R 755 /var/www/html/storage \
    && chmod -R 755 /var/www/html/bootstrap/cache

# Generate optimized autoloader
RUN composer dump-autoload --optimize

# Build frontend assets
RUN npm run build \
    && npm prune --omit=dev \
    && npm cache clean --force

# Copy configuration files
COPY docker/nginx.conf /etc/nginx/sites-available/default
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
COPY docker/php.ini /usr/local/etc/php/conf.d/99-custom.ini

# Create necessary directories
RUN mkdir -p /var/log/supervisor /run/nginx

# Expose port
EXPOSE 80

# Start supervisor
CMD ["/usr/bin/supervisord", "-n", "-c", "/etc/supervisor/conf.d/supervisord.conf"]