#!/bin/bash
# ============================================================
# Famosity ERP v3 — Server Fix Script
# Run this via SSH after uploading
# cd /home/wqftutpg/test-erp.famosity.krenx.in && bash fix_server.sh
# ============================================================

WEBROOT=$(pwd)
PHP=$(which php8.2 2>/dev/null || which php82 2>/dev/null || which php 2>/dev/null)

echo "🔧 Fixing Famosity ERP v3..."
echo "PHP: $PHP"
echo "Dir: $WEBROOT"
echo ""

# Step 1: Clear ALL caches
echo "Step 1: Clearing all caches..."
"$PHP" artisan config:clear 2>/dev/null || true
"$PHP" artisan cache:clear 2>/dev/null || true
"$PHP" artisan view:clear 2>/dev/null || true
"$PHP" artisan route:clear 2>/dev/null || true
"$PHP" artisan event:clear 2>/dev/null || true
"$PHP" artisan optimize:clear 2>/dev/null || true
rm -f bootstrap/cache/config.php bootstrap/cache/routes*.php bootstrap/cache/services.php bootstrap/cache/packages.php 2>/dev/null || true

# Step 2: Fix permissions
echo "Step 2: Setting permissions..."
chmod -R 755 storage/
chmod -R 755 bootstrap/cache/
chmod -R 755 public/uploads/ 2>/dev/null || true
mkdir -p storage/fonts storage/logs public/uploads/tenants
chmod -R 777 storage/
chmod -R 777 bootstrap/cache/

# Step 3: Run composer dump-autoload
echo "Step 3: Autoload..."
"$PHP" composer.phar dump-autoload --optimize 2>/dev/null || true

# Step 4: Apply DB patch
echo "Step 4: Applying database patch..."
if [ -f "db_patch_v3.sql" ]; then
    "$PHP" artisan db:statement "SELECT 1" 2>/dev/null && \
    mysql -u wqftutpg_famosity_basic_erp_user \
          -pMalda@732101 \
          wqftutpg_famosity_basic_erp \
          < db_patch_v3.sql 2>/dev/null && \
    echo "✅ DB patch applied" || \
    echo "⚠ Run db_patch_v3.sql manually in phpMyAdmin"
else
    echo "⚠ db_patch_v3.sql not found - run migrations manually"
fi

# Step 5: Run artisan migrate  
echo "Step 5: Laravel migrations..."
"$PHP" artisan migrate --force 2>/dev/null || echo "Migration issues - check manually"

# Step 6: Seed v3 data
echo "Step 6: Seeding v3 data..."
"$PHP" artisan db:seed --class=Database\\Seeders\\V3Seeder --force 2>/dev/null || echo "Seeder skipped"

# Step 7: Rebuild caches
echo "Step 7: Rebuilding caches..."
"$PHP" artisan config:cache
"$PHP" artisan route:cache
"$PHP" artisan view:cache

# Step 8: Test
echo ""
echo "Step 8: Testing application..."
"$PHP" artisan route:list 2>/dev/null | grep -c "GET" && echo "routes loaded ✅" || echo "route issue ⚠"

echo ""
echo "✅ Fix script complete!"
echo ""
echo "Test URLs:"
echo "  App:        https://test-erp.famosity.krenx.in"
echo "  Super Admin: https://test-erp.famosity.krenx.in/super-admin/login"
echo "  Super Admin Email: superadmin@famosity.in"
echo "  Super Admin Pass:  SuperAdmin@123"
echo ""
echo "Tenant Logins:"
echo "  demo@famosity.in / Demo@12345"
echo "  demo1@famosity.in (Demo Food Court)"
echo ""
