#!/bin/bash
# ================================================================
#  FakturaFlow — cPanel Deployment Script
#  boktech.se | PHP >=8.2 | public_html/public
# ================================================================

BLUE='\033[0;34m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; NC='\033[0m'

echo -e "${BLUE}"
echo "╔══════════════════════════════════════════╗"
echo "║  FakturaFlow — boktech.se Deployment     ║"
echo "╚══════════════════════════════════════════╝"
echo -e "${NC}"

# Detect PHP binary (suppress cPanel EA4 warning)
if [ -f /usr/local/bin/php ]; then
    PHP=/usr/local/bin/php
elif command -v php &> /dev/null; then
    PHP=php
else
    echo -e "${RED}✗ PHP not found${NC}"
    exit 1
fi

PHP_VER=$($PHP -r "echo PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION;" 2>/dev/null)
echo -e "PHP: ${GREEN}$PHP_VER${NC}"

$PHP -r "
\$v = PHP_VERSION;
if (version_compare(\$v, '8.2.0', '<')) {
    fwrite(STDERR, 'ERROR: PHP 8.2+ required. Have: '.\$v.PHP_EOL);
    exit(1);
}
echo 'OK';
" 2>&1 | grep -v "Unsuccessful stat" | grep -v "newline"

echo ""
echo "Checking PHP extensions..."
for EXT in pdo_mysql mbstring openssl tokenizer xml json bcmath curl gd zip fileinfo; do
    if $PHP -r "exit(extension_loaded('$EXT') ? 0 : 1);" 2>/dev/null; then
        echo -e "  ${GREEN}✓${NC} $EXT"
    else
        echo -e "  ${YELLOW}⚠${NC} $EXT (missing — enable in cPanel PHP Extensions)"
    fi
done

# Composer
echo ""
if ! command -v composer &> /dev/null; then
    echo "Installing Composer..."
    $PHP -r "copy('https://getcomposer.org/installer', 'cs.php');" 2>/dev/null
    mkdir -p "$HOME/bin"
    $PHP cs.php --quiet --install-dir="$HOME/bin" --filename=composer 2>/dev/null
    $PHP -r "unlink('cs.php');" 2>/dev/null
    export PATH="$HOME/bin:$PATH"
    echo -e "${GREEN}✓ Composer installed${NC}"
else
    COMPOSER_VER=$(composer --version --no-ansi 2>/dev/null | head -1)
    echo -e "${GREEN}✓ $COMPOSER_VER${NC}"
fi

# .env check
echo ""
if [ ! -f .env ]; then
    cp .env.example .env
    echo -e "${YELLOW}"
    echo "┌─────────────────────────────────────────────┐"
    echo "│  .env created! Fill in these values:        │"
    echo "│                                             │"
    echo "│  DB_PASSWORD=your_database_password         │"
    echo "│  MAIL_PASSWORD=your_email_password          │"
    echo "│  STRIPE_KEY=pk_live_...                     │"
    echo "│  STRIPE_SECRET=sk_live_...                  │"
    echo "│  ANTHROPIC_API_KEY=sk-ant-...               │"
    echo "│                                             │"
    echo "│  Then run:  bash deploy.sh  again           │"
    echo "└─────────────────────────────────────────────┘"
    echo -e "${NC}"
    exit 0
fi

if grep -q "YOUR_DB_PASSWORD_HERE" .env 2>/dev/null; then
    echo -e "${RED}✗ DB_PASSWORD not set in .env!${NC}"
    exit 1
fi
echo -e "${GREEN}✓ .env configured${NC}"

# Install dependencies
echo ""
echo "Installing PHP packages (2-4 minutes)..."
composer install \
    --optimize-autoloader \
    --no-dev \
    --no-interaction \
    --no-progress \
    2>&1 | grep -v "^$" | grep -v "Unsuccessful stat" | tail -5

if [ $? -ne 0 ]; then
    echo -e "${RED}✗ Composer install failed. Check errors above.${NC}"
    exit 1
fi
echo -e "${GREEN}✓ Packages installed${NC}"

# App key
$PHP artisan key:generate --force --quiet 2>/dev/null
echo -e "${GREEN}✓ App key generated${NC}"

# Database
echo ""
echo "Running database migrations..."
$PHP artisan migrate --force 2>&1 | tail -3
echo -e "${GREEN}✓ Database ready${NC}"

echo "Seeding demo data..."
$PHP artisan db:seed --class=DatabaseSeeder --force --quiet 2>/dev/null
echo -e "${GREEN}✓ Demo data inserted${NC}"

# Storage symlink
$PHP artisan storage:link --force --quiet 2>/dev/null || true
echo -e "${GREEN}✓ Storage linked${NC}"

# Cache
$PHP artisan config:cache --quiet 2>/dev/null
$PHP artisan route:cache  --quiet 2>/dev/null
$PHP artisan view:cache   --quiet 2>/dev/null
echo -e "${GREEN}✓ Production caches built${NC}"

# Permissions
chmod -R 755 storage bootstrap/cache 2>/dev/null || true
chmod 644 .env 2>/dev/null || true
chmod 755 artisan 2>/dev/null || true
echo -e "${GREEN}✓ File permissions set${NC}"

echo -e "${GREEN}"
echo "╔══════════════════════════════════════════╗"
echo "║       ✅  Deployment Complete!            ║"
echo "╚══════════════════════════════════════════╝"
echo -e "${NC}"
echo ""
echo "📌 Next steps:"
echo "   1. Add cron job in cPanel (see DEPLOYMENT_GUIDE.md)"
echo "   2. Set up Stripe webhook"
echo "   3. Visit https://boktech.se"
echo ""
echo "🔑 Demo login:  anna@demo.se / password"
echo ""
