# Use the official PHP image with Apache
FROM php:7.4.33-apache AS build

# Set environment variables for directory consistency
ENV APP_DIR=/var/www/html

# Set the working directory
WORKDIR ${APP_DIR}

# Copy the application code into the container
COPY ./api ${APP_DIR}/api

# Pull the code from GitHub
# RUN apt-get update && apt-get install -y git && \
#     git clone https://github.com/your-repo/backend.git ${APP_DIR}/api

COPY php.ini /usr/local/etc/php/

# Install required PHP extensions for MySQL and other dependencies
RUN apt-get update && apt-get install -y \
    libpq-dev \
    libonig-dev \
    libzip-dev \
    unzip \
    zip \
    && docker-php-ext-install \
    mysqli \
    pdo_mysql \
    && docker-php-ext-enable \
    mysqli \
    pdo_mysql

# Set ownership and permissions for Apache
RUN chown -R www-data:www-data ${APP_DIR} && chmod -R 755 ${APP_DIR}

# Enable Apache modules
RUN a2enmod rewrite headers

RUN printf '\n\
    Alias /dataFiles /var/www/html/api/dataFiles\n\
    <Directory /var/www/html/api/dataFiles>\n\
    Options Indexes FollowSymLinks\n\
    AllowOverride None\n\
    Require all granted\n\
    </Directory>\n' \
    >> /etc/apache2/apache2.conf

# Set the ServerName to suppress the warning about fully qualified domain name
# Enable access to files and grant permissions to read and write 
RUN echo "ServerName backend" >> /etc/apache2/apache2.conf && \ 
    echo 'Header set Access-Control-Allow-Origin "*"' >> /etc/apache2/apache2.conf && \
    echo 'Header set Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS"' >> /etc/apache2/apache2.conf && \
    echo 'Header set Access-Control-Allow-Headers "Content-Type, X-Requested-With, Authorization, Origin, Accept, Caller-Info"' >> /etc/apache2/apache2.conf && \
    echo '<Directory "/var/www/html">' >> /etc/apache2/apache2.conf && \
    echo '    Options Indexes FollowSymLinks' >> /etc/apache2/apache2.conf && \
    echo '    AllowOverride All' >> /etc/apache2/apache2.conf && \
    echo '    Require all granted' >> /etc/apache2/apache2.conf && \
    echo '</Directory>' >> /etc/apache2/apache2.conf

RUN docker-php-ext-install pdo pdo_mysql

# Expose the default Apache port
EXPOSE 80

# Start the Apache server
CMD ["apache2-foreground"]
