#!/usr/bin/env bash
# ══════════════════════════════════════════════════════════════════
#  AquaAgri Awards — cPanel / Shared Hosting Installer
#  Run this from your project root:  bash install.sh
# ══════════════════════════════════════════════════════════════════
set -e

CYAN='\033[0;36m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
RED='\033[0;31m'; BOLD='\033[1m'; NC='\033[0m'

echo -e "${CYAN}${BOLD}"
echo "╔══════════════════════════════════════════════════════════╗"
echo "║      AquaAgri Awards — Shared Hosting Installer         ║"
echo "║  Aquaculture, Fisheries & Farm Innovation Awards 2026   ║"
echo "╚══════════════════════════════════════════════════════════╝"
echo -e "${NC}"

step() { echo -e "\n${CYAN}▶ $1${NC}"; }
ok()   { echo -e "  ${GREEN}✔ $1${NC}"; }
warn() { echo -e "  ${YELLOW}⚠ $1${NC}"; }
die()  { echo -e "\n${RED}✘ ERROR: $1${NC}\n"; exit 1; }

# ── 1. PHP Version Check ─────────────────────────────────────────
step "Checking PHP version"
PHP_VER=$(php -r "echo PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION;" 2>/dev/null) || die "PHP not found in PATH"
PHP_MAJOR=$(echo "$PHP_VER" | cut -d. -f1)
PHP_MINOR=$(echo "$PHP_VER" | cut -d. -f2)
if [ "$PHP_MAJOR" -lt 8 ] || { [ "$PHP_MAJOR" -eq 8 ] && [ "$PHP_MINOR" -lt 2 ]; }; then
  die "PHP 8.2+ required. Found: $PHP_VER"
fi
ok "PHP $PHP_VER"

# ── 2. Required Extensions ───────────────────────────────────────
step "Checking PHP extensions"
REQUIRED_EXTS="pdo pdo_sqlite pdo_mysql mbstring openssl tokenizer xml ctype fileinfo curl json zip"
MISSING=""
for ext in $REQUIRED_EXTS; do
  if php -r "exit(extension_loaded('$ext') ? 0 : 1);" 2>/dev/null; then
    ok "$ext"
  else
    warn "Missing extension: $ext"
    MISSING="$MISSING $ext"
  fi
done
[ -n "$MISSING" ] && warn "Some extensions missing. Check with your host. Continuing..."

# ── 3. Composer ───────────────────────────────────────────────────
step "Checking Composer"
if ! command -v composer &>/dev/null; then
  warn "Composer not found globally. Downloading locally..."
  EXPECTED_CHECKSUM="$(php -r 'copy("https://composer.github.io/installer.sig", "php://stdout");')"
  php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
  ACTUAL_CHECKSUM="$(php -r "echo hash_file('sha384', 'composer-setup.php');")"
  if [ "$EXPECTED_CHECKSUM" != "$ACTUAL_CHECKSUM" ]; then
    rm composer-setup.php
    die "Composer installer checksum mismatch — aborting for security"
  fi
  php composer-setup.php --quiet --filename=composer
  rm composer-setup.php
  COMPOSER="./composer"
else
  COMPOSER="composer"
fi
ok "Composer ready"

# ── 4. Install PHP Dependencies ───────────────────────────────────
step "Installing PHP dependencies (composer install)"
$COMPOSER install --no-interaction --prefer-dist --optimize-autoloader \
  --no-dev 2>&1 | tail -5
ok "Composer packages installed"

# ── 5. Environment File ───────────────────────────────────────────
step "Setting up .env file"
if [ ! -f ".env" ]; then
  if [ -f ".env.example" ]; then
    cp .env.example .env
    ok ".env created from .env.example"
  else
    cat > .env <<'ENVEOF'
APP_NAME="AquaAgri Awards"
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=https://yourdomain.com

LOG_CHANNEL=stack
LOG_LEVEL=error

DB_CONNECTION=sqlite
# DB_CONNECTION=mysql
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=aquaagri_db
# DB_USERNAME=db_user
# DB_PASSWORD=db_password

PAYSTACK_PUBLIC_KEY=pk_live_xxxxxxxxxxxx
PAYSTACK_SECRET_KEY=sk_live_xxxxxxxxxxxx
VOTE_PRICE=100

SESSION_DRIVER=file
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
ENVEOF
    ok ".env created with defaults — please edit before proceeding"
  fi
else
  ok ".env already exists"
fi

# ── 6. App Key ────────────────────────────────────────────────────
step "Generating application key"
if grep -q "^APP_KEY=$" .env || grep -q "^APP_KEY=\"\"" .env; then
  php artisan key:generate --force
  ok "App key generated"
else
  ok "App key already set"
fi

# ── 7. Collect User Config ────────────────────────────────────────
step "Configuration"
echo ""
read -p "  App URL (e.g. https://aquaagri.yourdomain.com): " APP_URL_INPUT
read -p "  Database type [sqlite/mysql] (default: sqlite): " DB_TYPE
DB_TYPE=${DB_TYPE:-sqlite}
read -p "  Paystack PUBLIC key: " PS_PUB
read -p "  Paystack SECRET key: " PS_SEC
read -p "  Vote price in Naira (default: 100): " VOTE_PRICE
VOTE_PRICE=${VOTE_PRICE:-100}

# Update .env values
sed -i.bak "s|^APP_URL=.*|APP_URL=${APP_URL_INPUT}|" .env
sed -i.bak "s|^PAYSTACK_PUBLIC_KEY=.*|PAYSTACK_PUBLIC_KEY=${PS_PUB}|" .env
sed -i.bak "s|^PAYSTACK_SECRET_KEY=.*|PAYSTACK_SECRET_KEY=${PS_SEC}|" .env
sed -i.bak "s|^VOTE_PRICE=.*|VOTE_PRICE=${VOTE_PRICE}|" .env
sed -i.bak "s|^DB_CONNECTION=.*|DB_CONNECTION=${DB_TYPE}|" .env

if [ "$DB_TYPE" = "mysql" ]; then
  read -p "  MySQL Host (default 127.0.0.1): " DB_H; DB_H=${DB_H:-127.0.0.1}
  read -p "  MySQL Database name: " DB_N
  read -p "  MySQL Username: " DB_U
  read -s -p "  MySQL Password: " DB_P; echo ""
  sed -i.bak "s|^# DB_HOST=.*|DB_HOST=${DB_H}|" .env
  sed -i.bak "s|^# DB_DATABASE=.*|DB_DATABASE=${DB_N}|" .env
  sed -i.bak "s|^# DB_USERNAME=.*|DB_USERNAME=${DB_U}|" .env
  sed -i.bak "s|^# DB_PASSWORD=.*|DB_PASSWORD=${DB_P}|" .env
fi
rm -f .env.bak
ok "Configuration saved to .env"

# ── 8. SQLite DB File ─────────────────────────────────────────────
if [ "$DB_TYPE" = "sqlite" ]; then
  step "Creating SQLite database"
  mkdir -p database
  touch database/database.sqlite
  ok "SQLite database created at database/database.sqlite"
fi

# ── 9. Migrations & Seed ─────────────────────────────────────────
step "Running database migrations"
php artisan migrate --force
ok "Migrations complete"

step "Seeding aquaculture nominees and categories"
php artisan db:seed --force
ok "Database seeded with 24 nominees across 10 award categories"

# ── 10. Storage Link ──────────────────────────────────────────────
step "Creating storage symlink"
if [ -L "public/storage" ]; then
  ok "Storage symlink already exists"
else
  php artisan storage:link 2>/dev/null || warn "Could not create symlink — create manually: ln -s ../storage/app/public public/storage"
fi

# ── 11. Frontend Assets ───────────────────────────────────────────
step "Building frontend assets"
if [ -f "package.json" ]; then
  if command -v npm &>/dev/null; then
    npm install --silent && npm run build
    ok "Frontend assets built"
  else
    warn "npm not found. Upload pre-built assets from /public/build/ manually."
  fi
else
  warn "No package.json found — skipping asset build"
fi

# ── 12. Permissions ───────────────────────────────────────────────
step "Setting permissions"
chmod -R 755 storage bootstrap/cache 2>/dev/null || warn "Could not set permissions — set manually: chmod -R 755 storage bootstrap/cache"
ok "Permissions set"

# ── 13. Caching (production) ─────────────────────────────────────
step "Optimising for production"
php artisan config:cache  2>/dev/null && ok "Config cached"     || warn "Config cache skipped"
php artisan route:cache   2>/dev/null && ok "Routes cached"     || warn "Route cache skipped"
php artisan view:cache    2>/dev/null && ok "Views cached"      || warn "View cache skipped"

# ── DONE ──────────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}${BOLD}"
echo "╔══════════════════════════════════════════════════════════╗"
echo "║        ✅  AquaAgri Awards Installed Successfully!      ║"
echo "╚══════════════════════════════════════════════════════════╝"
echo -e "${NC}"
echo -e "  🌐 Site URL:    ${CYAN}${APP_URL_INPUT}${NC}"
echo -e "  🔑 Admin login: ${CYAN}admin@aquaagri.ng${NC} / ${CYAN}AquaAdmin@2026${NC}"
echo -e "  ⚙  Admin panel: ${CYAN}${APP_URL_INPUT}/admin${NC}"
echo ""
echo -e "  ${YELLOW}IMPORTANT POST-INSTALL STEPS:${NC}"
echo -e "  1. Point your domain's web root to: ${CYAN}public/${NC}"
echo -e "  2. Set up Paystack webhook URL:      ${CYAN}${APP_URL_INPUT}/payment/webhook${NC}"
echo -e "  3. Change admin password in Admin > Users"
echo -e "  4. Add your real Paystack keys if you used test keys above"
echo -e "  5. Delete ${RED}install.sh${NC} from your server for security"
echo ""
