# Multi-stage Dockerfile for tbi-acc-package-cron
# PHP 7.3 + Apache + Oracle Instant Client

# Stage 1: Builder
FROM php:7.3-apache AS builder

# Install build dependencies
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
        libaio-dev \
        mc \
        unzip \
        zlib1g-dev \
        libmemcached-dev \
        curl \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Install Oracle Instant Client
ENV ORA_CLIENT=instantclient-basic-linux.x64-21.1.0.0.0.zip
ENV ORA_CLIENT_SDK=instantclient-sdk-linux.x64-21.1.0.0.0.zip
ENV ORA_URL_PART=https://download.oracle.com/otn_software/linux/instantclient/211000

WORKDIR /opt
RUN curl -O ${ORA_URL_PART}/${ORA_CLIENT} && \
    curl -O ${ORA_URL_PART}/${ORA_CLIENT_SDK} && \
    unzip /opt/${ORA_CLIENT} && \
    unzip /opt/${ORA_CLIENT_SDK} && \
    rm /opt/${ORA_CLIENT} ${ORA_CLIENT_SDK}

# Configure Oracle library path
RUN ldconfig /opt/instantclient_21_1
ENV LD_LIBRARY_PATH=/opt/instantclient_21_1

# Enable opcache
RUN docker-php-ext-enable opcache

# Install and enable OCI8
RUN pecl install --onlyreqdeps --nobuild oci8-2.2.0 && \
    cd "$(pecl config-get temp_dir)/oci8" && \
    phpize && \
    ./configure --with-oci8=instantclient,/opt/instantclient_21_1 && \
    make && \
    make install && \
    docker-php-ext-enable oci8

# Install mysqli
RUN docker-php-ext-install mysqli

# Stage 2: Runtime
FROM php:7.3-apache

# Install runtime dependencies
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
        libaio1 \
        libmemcached11 \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Copy Oracle Instant Client from builder
COPY --from=builder /opt/instantclient_21_1 /opt/instantclient_21_1

# Configure Oracle library path
RUN echo "/opt/instantclient_21_1" > /etc/ld.so.conf.d/oracle.conf && \
    ldconfig
ENV LD_LIBRARY_PATH=/opt/instantclient_21_1

# Copy PHP extensions from builder
COPY --from=builder /usr/local/lib/php/extensions/ /usr/local/lib/php/extensions/
COPY --from=builder /usr/local/etc/php/conf.d/ /usr/local/etc/php/conf.d/

# Enable Apache modules
RUN a2enmod rewrite

# Set working directory
WORKDIR /var/www/html

# Copy application code
COPY . /var/www/html/

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

# Configure PHP
RUN echo "date.timezone = America/Toronto" > /usr/local/etc/php/conf.d/timezone.ini && \
    echo "memory_limit = 256M" > /usr/local/etc/php/conf.d/memory.ini && \
    echo "max_execution_time = 300" > /usr/local/etc/php/conf.d/execution.ini

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

# Expose port
EXPOSE 80

# Start Apache
CMD ["apache2-foreground"]
