#!/bin/bash
# =====================================================
# ZLO Platform - Deployment Script
# =====================================================

set -e

echo "=========================================="
echo "ZLO Platform - Deployment Script"
echo "=========================================="
echo ""

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

# Check if running as root
if [ "$EUID" -eq 0 ]; then 
   echo -e "${RED}Please do not run as root${NC}"
   exit 1
fi

# Get script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR"

echo "Step 1: Checking requirements..."

# Check PHP
if ! command -v php &> /dev/null; then
    echo -e "${RED}PHP is not installed${NC}"
    exit 1
fi

PHP_VERSION=$(php -v | head -n 1 | cut -d " " -f 2 | cut -d "." -f 1,2)
echo "  ✓ PHP version: $PHP_VERSION"

# Check MySQL
if ! command -v mysql &> /dev/null; then
    echo -e "${RED}MySQL is not installed${NC}"
    exit 1
fi
echo "  ✓ MySQL is installed"

echo ""
echo "Step 2: Setting up database..."

# Database configuration
read -p "Database host [localhost]: " DB_HOST
DB_HOST=${DB_HOST:-localhost}

read -p "Database port [3306]: " DB_PORT
DB_PORT=${DB_PORT:-3306}

read -p "Database name [zlo_platform]: " DB_NAME
DB_NAME=${DB_NAME:-zlo_platform}

read -p "Database user: " DB_USER
read -s -p "Database password: " DB_PASSWORD
echo ""

# Create database
echo "  Creating database..."
mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASSWORD" -e "CREATE DATABASE IF NOT EXISTS $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 2>/dev/null || {
    echo -e "${RED}Failed to create database. Please check your credentials.${NC}"
    exit 1
}

# Import schema
echo "  Importing database schema..."
mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" < database/schema.sql

echo -e "${GREEN}  ✓ Database setup complete${NC}"

echo ""
echo "Step 3: Creating environment file..."

# Create .env file
if [ ! -f ".env" ]; then
    cp .env.example .env
    
    # Update database credentials
    sed -i "s/DB_HOST=localhost/DB_HOST=$DB_HOST/" .env
    sed -i "s/DB_PORT=3306/DB_PORT=$DB_PORT/" .env
    sed -i "s/DB_NAME=zlo_platform/DB_NAME=$DB_NAME/" .env
    sed -i "s/DB_USER=your_db_username/DB_USER=$DB_USER/" .env
    sed -i "s/DB_PASSWORD=your_db_password/DB_PASSWORD=$DB_PASSWORD/" .env
    
    # Generate JWT secret
    JWT_SECRET=$(openssl rand -base64 32)
    sed -i "s/JWT_SECRET=your-super-secret-jwt-key-change-this-in-production/JWT_SECRET=$JWT_SECRET/" .env
    
    echo -e "${GREEN}  ✓ Environment file created${NC}"
else
    echo -e "${YELLOW}  ! .env file already exists, skipping${NC}"
fi

echo ""
echo "Step 4: Setting up directories..."

# Create directories
mkdir -p uploads logs
chmod -R 755 uploads logs
touch uploads/.gitkeep logs/.gitkeep

echo -e "${GREEN}  ✓ Directories created${NC}"

echo ""
echo "Step 5: Checking Apache configuration..."

# Check if .htaccess will work
if [ -f "/etc/apache2/apache2.conf" ]; then
    echo "  Apache detected"
    
    # Check if mod_rewrite is enabled
    if apache2ctl -M 2>/dev/null | grep -q "rewrite_module"; then
        echo -e "${GREEN}  ✓ mod_rewrite is enabled${NC}"
    else
        echo -e "${YELLOW}  ! mod_rewrite may not be enabled${NC}"
        echo "    Run: sudo a2enmod rewrite && sudo service apache2 restart"
    fi
else
    echo -e "${YELLOW}  ! Apache not detected, skipping check${NC}"
fi

echo ""
echo "=========================================="
echo -e "${GREEN}Deployment complete!${NC}"
echo "=========================================="
echo ""
echo "Default admin credentials:"
echo "  Email: admin@zlotech.net"
echo "  Password: admin123"
echo ""
echo -e "${YELLOW}⚠️  IMPORTANT: Change the default password immediately!${NC}"
echo ""
echo "Next steps:"
echo "  1. Update APP_URL in .env file"
echo "  2. Configure email settings (optional)"
echo "  3. Set up SSL certificate"
echo "  4. Configure backup system"
echo ""
echo "Access your site at:"
echo "  Frontend: http://your-domain.com/"
echo "  Admin: http://your-domain.com/admin/"
echo "  API: http://your-domain.com/api/health"
echo ""
