#!/bin/bash
set -e

echo "========================================="
echo "  THE CLUB ERP — Container Starting"
echo "========================================="

# ── Generate .env from environment variables ──
ENV_FILE="/var/www/html/.env"
cat > "$ENV_FILE" <<'ENDOFENV'
APP_URL=PLACEHOLDER
ENDOFENV

# Write env properly using PHP (no shell escaping issues)
php -r "
file_put_contents('/var/www/html/.env',
    'APP_URL=' . getenv('APP_URL') . \"\n\" .
    'APP_DEBUG=' . getenv('APP_DEBUG') . \"\n\" .
    'APP_ENV=' . getenv('APP_ENV') . \"\n\" .
    'DB_HOST=' . getenv('DB_HOST') . \"\n\" .
    'DB_PORT=' . getenv('DB_PORT') . \"\n\" .
    'DB_NAME=' . getenv('DB_NAME') . \"\n\" .
    'DB_USER=' . getenv('DB_USER') . \"\n\" .
    'DB_PASS=' . getenv('DB_PASS') . \"\n\" .
    'SMS_PROVIDER=' . getenv('SMS_PROVIDER') . \"\n\" .
    'SMS_API_KEY=' . getenv('SMS_API_KEY') . \"\n\" .
    'SMS_SENDER_ID=' . getenv('SMS_SENDER_ID') . \"\n\"
);
echo 'ENV file written!';
"
chown www-data:www-data /var/www/html/.env

# ── Run boot script (MySQL wait + migrations + seeds) ──
php /var/www/html/docker/boot.php

# ── Fix permissions ──
chown -R www-data:www-data /var/www/html/storage 2>/dev/null || true
chmod -R 775 /var/www/html/storage 2>/dev/null || true

# ── Setup Cron (runs every hour) ──
echo "0 * * * * cd /var/www/html && php cli.php cron >> /var/www/html/storage/logs/cron.log 2>&1" > /etc/cron.d/cluberp-cron
chmod 0644 /etc/cron.d/cluberp-cron
crontab /etc/cron.d/cluberp-cron
service cron start
echo "Cron daemon started (hourly: php cli.php cron)"

echo "========================================="
echo "Starting Apache..."
echo "========================================="
exec apache2-foreground