# Multi-stage Dockerfile for complete inventory solution
FROM node:18-alpine AS frontend-builder

# Set working directory for frontend build
WORKDIR /app/frontend

# Copy frontend package files
COPY frontend/package*.json ./

# Install frontend dependencies
RUN npm ci --only=production

# Copy frontend source code
COPY frontend/ .

# Build frontend for production
RUN npm run build

# Backend and final stage
FROM php:8.1-apache

# Install system dependencies including Node.js for frontend build tools
RUN apt-get update && apt-get install -y \
    libzip-dev \
    libpng-dev \
    libjpeg-dev \
    libfreetype6-dev \
    zip \
    unzip \
    curl \
    gnupg \
    && curl -fsSL https://deb.nodesource.com/setup_18.x | bash - \
    && apt-get install -y nodejs \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install gd zip pdo_mysql \
    && a2enmod rewrite \
    && a2enmod headers

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

# Set working directory
WORKDIR /var/www/html

# Copy backend files
COPY backend/ .

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

# Copy environment file for PHP application
COPY backend/.env.local ./backend/.env.local

# Copy built frontend from builder stage
COPY --from=frontend-builder /app/frontend/dist ./frontend/dist

# Copy test script for environment testing
COPY test-env.php ./

# Copy image URL fix script
COPY fix_image_urls.php ./

# Create uploads and attachments directories and set permissions
RUN mkdir -p uploads attachments && \
    chown -R www-data:www-data /var/www/html/uploads /var/www/html/attachments && \
    chmod -R 755 /var/www/html/uploads /var/www/html/attachments

# Copy Apache configuration
COPY docker/apache.conf /etc/apache2/sites-available/000-default.conf

# Expose port
EXPOSE 80

# Start Apache
CMD ["apache2-foreground"]
