#!/usr/bin/env bash
# ONINA · post-upload server installer
# Run once from the project root via cPanel Terminal (or SSH):
#   bash install-on-server.sh

set -e
cd "$(dirname "$0")"

echo "» Onina installer"

if [ ! -f .env ]; then
    if [ -f .env.production.example ]; then
        cp .env.production.example .env
        echo "✓ copied .env.production.example → .env (fill DB + APP_URL before continuing)"
        exit 1
    fi
    echo "✗ .env not found" && exit 1
fi

# 1. Application key (only if missing)
if ! grep -q '^APP_KEY=base64:' .env; then
    php artisan key:generate --force
fi

# 2. Storage symlink (public/storage → ../storage/app/public)
php artisan storage:link || true

# 3. Migrate + seed baseline (currencies, settings, pages, demo customer if present)
php artisan migrate --force
php artisan db:seed --class=CurrencySeeder --force
php artisan db:seed --class=SettingsSeeder --force
php artisan db:seed --class=PagesSeeder --force

# 4. Permissions
chmod -R 775 storage bootstrap/cache || true

# 5. Production caches
php artisan optimize:clear
php artisan optimize
php artisan filament:cache-components

# 6. Create the first admin if none exists
php artisan tinker --execute='
if (App\Models\User::count() === 0) {
    App\Models\User::create([
        "name" => "Onina Admin",
        "email" => "admin@onina.om",
        "password" => bcrypt("CHANGE-ME-NOW"),
    ]);
    echo "✓ created admin: admin@onina.om / CHANGE-ME-NOW (change immediately from Profile)\n";
} else {
    echo "✓ admin already exists\n";
}'

echo "» Done. Visit / to see the storefront and /login to sign in."
echo "» Reminder: change the seeded admin password immediately."
