FROM php:8.2-apache-bookworm

# ── System dependencies ──
RUN apt-get update && apt-get install -y \
    libpng-dev \
    libjpeg-dev \
    libfreetype6-dev \
    libicu-dev \
    libzip-dev \
    libonig-dev \
    zip \
    unzip \
    default-mysql-client \
    dos2unix \
    git \
    wget \
    cron \
    xvfb \
    libxrender1 \
    libfontconfig1 \
    libx11-6 \
    libxext6 \
    libssl3 \
    fonts-noto \
    fonts-noto-core \
    fonts-noto-extra \
    fonts-arabeyes \
    fontconfig \
    && wget -q https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6.1-3/wkhtmltox_0.12.6.1-3.bookworm_amd64.deb -O /tmp/wkhtmltox.deb \
    && dpkg -i /tmp/wkhtmltox.deb || apt-get install -f -y \
    && rm /tmp/wkhtmltox.deb \
    && fc-cache -fv \
    && rm -rf /var/lib/apt/lists/*

# ── Install Composer ──
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer

# ── PHP extensions ──
RUN docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) \
        pdo_mysql \
        bcmath \
        mbstring \
        gd \
        intl \
        zip \
        opcache \
        fileinfo

# ── Apache modules ──
RUN a2enmod rewrite headers

# ── PHP configuration ──
COPY docker/php.ini /usr/local/etc/php/conf.d/99-club-erp.ini

# ── Apache vhost ──
COPY docker/000-default.conf /etc/apache2/sites-available/000-default.conf

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

# ── Install PHP dependencies (production only, no dev) ──
WORKDIR /var/www/html
RUN composer install --no-dev --optimize-autoloader --no-interaction --no-scripts

# ── Create storage directories ──
RUN mkdir -p \
    /var/www/html/storage/logs \
    /var/www/html/storage/uploads/documents \
    /var/www/html/storage/uploads/photos \
    /var/www/html/storage/uploads/forms \
    /var/www/html/storage/cache \
    /var/www/html/storage/sessions

# ── Permissions ──
RUN chown -R www-data:www-data /var/www/html/storage \
    && chmod -R 775 /var/www/html/storage \
    && chown -R www-data:www-data /var/www/html/public \
    && chmod -R 755 /var/www/html/public

# ── Environment defaults (overridden by CapRover env vars) ──
ENV APP_URL=http://localhost
ENV APP_DEBUG=true
ENV APP_ENV=local
ENV DB_HOST=srv-captain--mysql-db
ENV DB_PORT=3306
ENV DB_NAME=the_club_erp
ENV DB_USER=root
ENV DB_PASS=Alarcade123#
ENV SMS_PROVIDER=
ENV SMS_API_KEY=
ENV SMS_SENDER_ID=

# ── Entrypoint — fix line endings ──
COPY docker/entrypoint.sh /usr/local/bin/entrypoint.sh
RUN dos2unix /usr/local/bin/entrypoint.sh && chmod +x /usr/local/bin/entrypoint.sh

EXPOSE 80

ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]