# Use the official PHP image with Apache (PHP 8.2 for compatibility)
FROM php:8.2-apache

# Update the package manager and install required system dependencies
RUN apt-get update && apt-get install -y \
    libpng-dev \
    libjpeg-dev \
    libfreetype6-dev \
    libonig-dev \
    libzip-dev \
    zip \
    unzip \
    git \
    curl && \
    docker-php-ext-configure gd --with-freetype --with-jpeg && \
    docker-php-ext-install gd mbstring zip pdo pdo_mysql && \
    apt-get clean && rm -rf /var/lib/apt/lists/*

# Enable mod_rewrite for Laravel
RUN a2enmod rewrite

# Install Composer globally and update to version 2
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN composer self-update --2

# Set the working directory to /var/www/html (Apache's default root directory)
WORKDIR /var/www/html

# Copy the Laravel application into the container
COPY . .

# Mark /var/www/html as safe for Git
RUN git config --global --add safe.directory /var/www/html

# Ensure required directories exist and set permissions for storage and cache
RUN mkdir -p /var/www/html/storage /var/www/html/bootstrap/cache && \
    chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache && \
    chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache

# Clear Composer cache (Optional but helpful)
RUN composer clear-cache

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

# Generate the application key (optional, required for Laravel projects)
RUN php artisan key:generate || true

# Set permissions for the entire Laravel project (optional)
RUN chown -R www-data:www-data /var/www/html && \
    chmod -R 775 /var/www/html

# Expose port 80 to allow access to the application
EXPOSE 80

# Set the default command to run Apache
CMD ["apache2-foreground"]
