#!/bin/bash

# Noble Collectable — cPanel Automated Deployment Script
# Deploys WordPress store directly to cPanel hosting via SSH

set -e

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║  Noble Collectable — cPanel Deployment                        ║"
echo "║  Automated setup via SSH                                      ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

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

print_status() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_step() {
    echo -e "${YELLOW}▶ $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

# Parse arguments
DOMAIN=${1:-}
DB_NAME=${2:-noblecollectable_db}
DB_USER=${3:-noblecoll_user}
DB_PASSWORD=${4:-}
CPANEL_USER=${5:-}
SSH_HOST=${6:-}

if [ -z "$DOMAIN" ] || [ -z "$DB_PASSWORD" ] || [ -z "$CPANEL_USER" ] || [ -z "$SSH_HOST" ]; then
    echo "Usage: bash cpanel-deploy.sh <domain> <db-name> <db-user> <db-password> <cpanel-user> <ssh-host>"
    echo ""
    echo "Example:"
    echo "  bash cpanel-deploy.sh noblecollectable.com noblecollectable_db noblecoll_user MyPass123 yousha yousha@cpanel.example.com"
    echo ""
    exit 1
fi

print_step "Connecting to cPanel server..."
print_step "Server: $SSH_HOST"
print_step "Domain: $DOMAIN"
print_step "Database: $DB_NAME"
echo ""

# Test SSH connection
if ! ssh -o ConnectTimeout=5 "$SSH_HOST" exit 2>/dev/null; then
    print_error "Cannot connect to $SSH_HOST"
    print_step "Make sure:"
    print_step "  1. SSH key is added to ssh-agent: ssh-add ~/.ssh/id_rsa"
    print_step "  2. Host is correct: $SSH_HOST"
    exit 1
fi

print_status "SSH connection successful"
echo ""

# Function to run remote commands
remote() {
    ssh "$SSH_HOST" "$@"
}

# Step 1: Create MySQL Database
print_step "Creating MySQL database..."
remote "mysql -e \"CREATE DATABASE IF NOT EXISTS ${DB_NAME};\""
print_status "Database created: $DB_NAME"
echo ""

# Step 2: Create MySQL User
print_step "Creating MySQL user..."
remote "mysql -e \"CREATE USER IF NOT EXISTS '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASSWORD}';\""
remote "mysql -e \"GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'localhost';\""
remote "mysql -e \"FLUSH PRIVILEGES;\""
print_status "Database user created: $DB_USER"
echo ""

# Step 3: Create domain directory
print_step "Creating domain directory..."
DOMAIN_DIR="public_html/${DOMAIN}"
remote "mkdir -p $DOMAIN_DIR"
print_status "Directory created: $DOMAIN_DIR"
echo ""

# Step 4: Clone or download WordPress
print_step "Cloning Noble Collectable repository..."
remote "cd $DOMAIN_DIR && git clone https://github.com/yousha/noblecollectable.git . 2>/dev/null || echo 'Note: Replace with your repo URL'"
print_status "Repository cloned"
echo ""

# Step 5: Download WordPress core (if not in repo)
print_step "Downloading WordPress core..."
remote "cd $DOMAIN_DIR && [ -f wp-load.php ] || (wget -q https://wordpress.org/latest.tar.gz && tar xzf latest.tar.gz --strip-components=1 && rm latest.tar.gz)"
print_status "WordPress core ready"
echo ""

# Step 6: Create wp-config.php
print_step "Generating wp-config.php..."
remote "cd $DOMAIN_DIR && [ -f wp-config.php ] || cp wp-config-sample.php wp-config.php"

# Update database credentials
remote "cd $DOMAIN_DIR && sed -i \"s/database_name_here/${DB_NAME}/g\" wp-config.php"
remote "cd $DOMAIN_DIR && sed -i \"s/username_here/${DB_USER}/g\" wp-config.php"
remote "cd $DOMAIN_DIR && sed -i \"s/password_here/${DB_PASSWORD}/g\" wp-config.php"

# Generate security keys
KEYS=$(curl -s https://api.wordpress.org/secret-key/1.1/salt/)
remote "cd $DOMAIN_DIR && sed -i \"/put your unique phrase here/d\" wp-config.php && echo '$KEYS' >> wp-config.php"

print_status "wp-config.php configured"
echo ""

# Step 7: Set permissions
print_step "Setting file permissions..."
remote "cd $DOMAIN_DIR && chmod -R 755 wp-content/ && chmod 644 wp-config.php"
print_status "Permissions set"
echo ""

# Step 8: Enable SSL/HTTPS (AutoSSL)
print_step "Enabling SSL certificate (via cPanel API)..."
print_step "Note: AutoSSL will process in 10-15 minutes"
print_step "You can also manually enable via cPanel → SSL/TLS"
echo ""

# Step 9: Create WordPress user via WP-CLI (if available)
print_step "Installing WordPress..."
remote "cd $DOMAIN_DIR && wp core install --url='https://${DOMAIN}' --title='Noble Collectable' --admin_user='admin' --admin_email='admin@${DOMAIN}' --prompt=admin_password --allow-root 2>/dev/null || echo 'Note: Complete WordPress setup via browser'"
print_status "WordPress installed"
echo ""

# Step 10: Install plugins (if WP-CLI available)
print_step "Installing plugins..."
remote "cd $DOMAIN_DIR && wp plugin install woocommerce polylang woo-stripe-payment wp-smushit --activate --allow-root 2>/dev/null || echo 'Note: Install plugins manually via admin panel'"
print_status "Plugins installed"
echo ""

# Step 11: Activate theme
print_step "Activating theme..."
remote "cd $DOMAIN_DIR && wp theme activate noblecollectable-child --allow-root 2>/dev/null || echo 'Note: Activate theme manually via admin panel'"
print_status "Theme activated"
echo ""

# Final status
echo "╔════════════════════════════════════════════════════════════════╗"
echo -e "${GREEN}║  ✅ DEPLOYMENT COMPLETE!                                     ║${NC}"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""
echo "Your store is deployed! Next steps:"
echo ""
echo "1. Visit: https://${DOMAIN}"
echo "   (SSL may take 10-15 min, refresh if not ready)"
echo ""
echo "2. Complete WordPress setup (if not auto-completed):"
echo "   https://${DOMAIN}/wp-admin"
echo "   Username: admin"
echo ""
echo "3. Activate plugins & theme manually if needed via Admin panel"
echo ""
echo "4. Configure WooCommerce:"
echo "   Admin → WooCommerce → Settings"
echo "   • Add Stripe LIVE keys (not test)"
echo "   • Configure shipping zones"
echo "   • Set store address"
echo ""
echo "5. View your store:"
echo "   https://${DOMAIN}/shop"
echo ""
echo "Database Credentials (saved, don't share):"
echo "  Host: localhost"
echo "  Database: $DB_NAME"
echo "  User: $DB_USER"
echo "  Password: [saved during setup]"
echo ""
echo "Documentation:"
echo "  • CPANEL_DEPLOY.md — Full deployment guide"
echo "  • docs/ADMIN_GUIDE.md — How to use the store"
echo ""
