# Multi-stage build for unified backend + frontend container
FROM node:18-alpine AS frontend-build

# 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 + Frontend unified container
FROM php:8.1-apache

# Install system dependencies and PHP extensions
RUN apt-get update && apt-get install -y \
    libzip-dev \
    libpng-dev \
    libjpeg-dev \
    libfreetype6-dev \
    zip \
    unzip \
    curl \
    && 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:latest /usr/bin/composer /usr/bin/composer

# Set working directory for backend
WORKDIR /var/www/html

# Copy backend source code
COPY backend/ ./

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

# Create api directory and copy backend files there
RUN mkdir -p api && cp -r *.php api/ && cp -r models api/ && cp -r vendor api/ && cp composer.json api/ && cp -r config api/ && cp -r middleware api/ && cp -r database api/

# Copy built frontend files directly to root
COPY --from=frontend-build /app/frontend/dist ./

# Create uploads directory and set permissions
RUN mkdir -p uploads && chmod -R 755 uploads

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

# Copy custom Apache configuration for unified setup
COPY docker/apache-unified-simple.conf /etc/apache2/sites-available/unified.conf

# Enable the unified site
RUN a2ensite unified.conf && a2dissite 000-default.conf

# Set environment variables for frontend build
ARG VUE_APP_API_URL=/api
ENV VUE_APP_API_URL=/api

# Expose port 80
EXPOSE 80

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD curl -f http://localhost/api/company.php || exit 1

# Start Apache
CMD ["apache2-foreground"]
