#!/bin/sh
# ──────────────────────────────────────────────────────────────────────────────
# eCert MBIP — Container Entrypoint
# Jalankan sebelum php-fpm bermula:
#   1. Tunggu MySQL
#   2. Install Composer deps (dev sahaja)
#   3. Generate APP_KEY jika tiada
#   4. Migrate + seed AdminSeeder
#   5. Storage link
#   6. Cache (prod sahaja)
# ──────────────────────────────────────────────────────────────────────────────
set -e

echo ""
echo "╔══════════════════════════════════════╗"
echo "║    eCert MBIP — Container Start      ║"
echo "╚══════════════════════════════════════╝"
echo ""

# ── 1. Pasang Composer dependencies (sebelum tunggu MySQL) ───────────────────
if [ ! -d /var/www/vendor ]; then
    echo "📦 Memasang Composer dependencies..."
    if [ "${APP_ENV}" = "production" ]; then
        composer install \
            --no-interaction \
            --no-dev \
            --no-progress \
            --prefer-dist \
            --optimize-autoloader
    else
        composer install \
            --no-interaction \
            --no-progress \
            --prefer-dist
    fi
fi

# ── 2. Tunggu MySQL bersedia ──────────────────────────────────────────────────
DB_HOST="${DB_HOST:-host.docker.internal}"
DB_PORT="${DB_PORT:-3306}"
DB_DATABASE="${DB_DATABASE:-ecert_mbip}"
DB_USERNAME="${DB_USERNAME:-root}"
DB_PASSWORD="${DB_PASSWORD:-secret}"

echo "⏳ Menunggu MySQL di ${DB_HOST}:${DB_PORT}..."

until php -r "
    try {
        new PDO(
            'mysql:host=${DB_HOST};port=${DB_PORT};dbname=${DB_DATABASE}',
            '${DB_USERNAME}',
            '${DB_PASSWORD}'
        );
        exit(0);
    } catch (Exception \$e) {
        exit(1);
    }
" 2>/dev/null; do
    printf "."
    sleep 2
done
echo ""
echo "✓ MySQL bersedia."

# ── 2b. Fix storage permissions (penting untuk named volume di production) ────
chown -R www-data:www-data /var/www/storage /var/www/bootstrap/cache 2>/dev/null || true
chmod -R 775              /var/www/storage /var/www/bootstrap/cache 2>/dev/null || true

# ── 3. Generate APP_KEY jika kosong ───────────────────────────────────────────
if [ -z "${APP_KEY}" ] || [ "${APP_KEY}" = "" ]; then
    echo "🔑 Menjana APP_KEY..."
    php artisan key:generate --force
fi

# ── 4. Database migration ─────────────────────────────────────────────────────
echo "🗄  Menjalankan migration..."
php artisan migrate --force

# Seed admin account (idempotent — guna firstOrCreate)
echo "👤 Seeding AdminSeeder..."
php artisan db:seed --class=AdminSeeder --force

# ── 5. Storage symbolic link ──────────────────────────────────────────────────
php artisan storage:link 2>/dev/null || true

# ── 6. Cache (production sahaja) ──────────────────────────────────────────────
if [ "${APP_ENV}" = "production" ]; then
    # Pastikan direktori storage wujud (penting bila named volume kosong pada deploy pertama)
    mkdir -p /var/www/storage/framework/views \
             /var/www/storage/framework/cache/data \
             /var/www/storage/framework/sessions \
             /var/www/storage/logs \
             /var/www/storage/app/public
    chown -R www-data:www-data /var/www/storage
    chmod -R 775               /var/www/storage

    echo "⚡ Caching config, routes, views..."
    php artisan config:cache
    php artisan route:cache
    php artisan view:cache
    php artisan event:cache
fi

echo ""
echo "✅ Aplikasi bersedia."
echo ""

exec "$@"
