#!/usr/bin/env bash
# One-click Laravel setup for cPanel (run after upload + .env ready)
# Usage: cd ~/your-project && bash setup.sh

set -e

ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT"

echo "=========================================="
echo "  Master Ecommerce — One-Click Setup"
echo "  Folder: $ROOT"
echo "=========================================="

if [ ! -f artisan ]; then
    echo "ERROR: artisan not found. Run this from Laravel project root."
    exit 1
fi

if [ ! -f .env ]; then
    echo "ERROR: .env missing. Copy .env.example to .env and fill DB details first."
    exit 1
fi

if ! grep -q '^APP_KEY=base64:' .env 2>/dev/null; then
    echo "==> APP_KEY missing — generating..."
    php artisan key:generate --force
fi

echo ""
echo "==> 1/7 Fix permissions (vendor, storage, bootstrap/cache)..."
if [ -f "$ROOT/fix-permissions.sh" ]; then
    bash "$ROOT/fix-permissions.sh" "$ROOT"
elif [ -f "$ROOT/scripts/fix-cpanel-permissions.sh" ]; then
    bash "$ROOT/scripts/fix-cpanel-permissions.sh" "$ROOT"
else
    find vendor -type d -exec chmod 755 {} \; 2>/dev/null || true
    find vendor -type f -exec chmod 644 {} \; 2>/dev/null || true
    mkdir -p storage/logs storage/framework/cache/data storage/framework/sessions storage/framework/views bootstrap/cache
    touch storage/logs/laravel.log 2>/dev/null || true
    chmod -R 775 storage bootstrap/cache 2>/dev/null || true
    chmod 755 artisan 2>/dev/null || true
fi

echo ""
echo "==> 2/7 Clear old cache..."
php artisan optimize:clear

echo ""
echo "==> 3/7 Storage link..."
php artisan storage:link --force 2>/dev/null || php artisan storage:link

echo ""
echo "==> 4/7 Database migrate..."
php artisan migrate --force

echo ""
echo "==> 5/7 Production cache..."
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache 2>/dev/null || true
php artisan optimize

echo ""
echo "==> 6/7 Final permissions..."
if [ -f "$ROOT/fix-permissions.sh" ]; then
    bash "$ROOT/fix-permissions.sh" "$ROOT"
elif [ -f "$ROOT/scripts/fix-cpanel-permissions.sh" ]; then
    bash "$ROOT/scripts/fix-cpanel-permissions.sh" "$ROOT"
else
    chmod -R 775 storage bootstrap/cache 2>/dev/null || true
fi

APP_URL="$(grep '^APP_URL=' .env | cut -d= -f2- | tr -d '"' | tr -d "'")"

echo ""
echo "==> 7/7 Done."
echo ""
echo "=========================================="
echo "  DONE! Site ready."
echo "  Home:  ${APP_URL:-https://yourdomain.com}"
echo "  Admin: ${APP_URL:-https://yourdomain.com}/admin/login"
echo "=========================================="
