# Multi-stage build for BLXChat
# Stage 1: Build frontend
FROM node:20-alpine AS frontend-builder

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm ci

# Copy source files
COPY . .

# Build the application
RUN npm run build

# Stage 2: Production with PHP
FROM php:8.2-apache

# Install PHP extensions
RUN apt-get update && apt-get install -y \
    libzip-dev \
    zip \
    curl \
    && docker-php-ext-install zip \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Enable Apache mod_rewrite
RUN a2enmod rewrite

# Set working directory
WORKDIR /var/www/html

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

# Copy PHP admin panel
COPY admin ./admin

# Copy public files (JSON, logos, etc.)
COPY public ./public

# Copy JSON files to root for easy access (inbox-settings.json, companies.json, users.json)
RUN cp public/inbox-settings.json ./inbox-settings.json 2>/dev/null || true && \
    cp public/companies.json ./companies.json 2>/dev/null || true && \
    cp public/users.json ./users.json 2>/dev/null || true && \
    cp public/admin-config.json ./admin-config.json 2>/dev/null || true

# Copy .htaccess for SPA routing (if exists)
COPY .htaccess* ./

# Create necessary directories
RUN mkdir -p public/logos && \
    chown -R www-data:www-data /var/www/html && \
    chmod -R 755 /var/www/html

# Configure Apache
RUN echo '<VirtualHost *:80>\n\
    DocumentRoot /var/www/html\n\
    <Directory /var/www/html>\n\
        Options -Indexes +FollowSymLinks\n\
        AllowOverride All\n\
        Require all granted\n\
    </Directory>\n\
    ErrorLog ${APACHE_LOG_DIR}/error.log\n\
    CustomLog ${APACHE_LOG_DIR}/access.log combined\n\
</VirtualHost>' > /etc/apache2/sites-available/000-default.conf

# Expose port 80
EXPOSE 80

# Start Apache
CMD ["apache2-foreground"]
