## ---------- Stage 1: build the Laravel app + install packages ----------
FROM composer:2 AS build
WORKDIR /var/www

# Create a fresh, real Laravel 11 skeleton (pulled from Packagist/GitHub on YOUR server at build time)
RUN composer create-project --prefer-dist --no-scripts --no-interaction "laravel/laravel:^11.0" .

# Add the packages the CRM needs
RUN composer require --no-interaction \
    livewire/livewire:^3.5 \
    spatie/laravel-permission:^6.9 \
    laravel/sanctum:^4.0 \
    barryvdh/laravel-dompdf:^3.0 \
    maatwebsite/excel:^3.1

# Publish spatie permission config + migration from the real installed package
RUN php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --force

# ---- Overlay our custom CRM application code on top of the fresh skeleton ----
COPY app/ /var/www/app/
COPY database/migrations/ /var/www/database/migrations/
COPY database/seeders/ /var/www/database/seeders/
COPY routes/web.php /var/www/routes/web.php
COPY resources/views/ /var/www/resources/views/
COPY .env.docker /var/www/.env

RUN composer dump-autoload -o

## ---------- Stage 2: runtime image (php-fpm + nginx + supervisor in one container) ----------
FROM php:8.3-fpm

RUN apt-get update && apt-get install -y \
        libpng-dev libonig-dev libxml2-dev libzip-dev zip unzip git nginx supervisor \
    && docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd zip \
    && apt-get clean && rm -rf /var/lib/apt/lists/*

WORKDIR /var/www
COPY --from=build /var/www /var/www
COPY docker/php/local.ini /usr/local/etc/php/conf.d/local.ini
COPY docker/nginx/default.conf /etc/nginx/sites-enabled/default
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
COPY docker/entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh \
    && chown -R www-data:www-data /var/www/storage /var/www/bootstrap/cache

EXPOSE 80
ENTRYPOINT ["/entrypoint.sh"]
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
