#!/bin/bash

# EP Application Deployment Script
# This script helps deploy changes from GitHub to your live server

set -e  # Exit on any error

echo "🚀 Starting EP Application Deployment..."

# Configuration
REPO_URL="https://github.com/yourusername/ep-golf-management.git"
DEPLOY_PATH="/var/www/html"
BACKUP_PATH="/var/backups/ep-backup-$(date +%Y%m%d-%H%M%S)"

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

# Functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if we're in the right directory
if [ ! -f "event-login.php" ]; then
    log_error "Not in EP application directory!"
    exit 1
fi

# Create backup
log_info "Creating backup..."
sudo mkdir -p $(dirname $BACKUP_PATH)
sudo cp -r $DEPLOY_PATH $BACKUP_PATH
log_info "Backup created at: $BACKUP_PATH"

# Pull latest changes
log_info "Pulling latest changes from GitHub..."
git fetch origin
git reset --hard origin/main

# Install/update dependencies
if [ -f "composer.json" ]; then
    log_info "Installing PHP dependencies..."
    composer install --no-dev --optimize-autoloader
fi

# Set proper permissions
log_info "Setting file permissions..."
sudo chown -R www-data:www-data .
sudo chmod 755 *.php
sudo chmod -R 755 uploads/ board/ 2>/dev/null || true

# Check critical files
log_info "Checking configuration files..."
if [ ! -f "event-server.php" ]; then
    log_warn "event-server.php not found! Copy from event-server.php.example and configure."
fi

if [ ! -f "ar-config.php" ]; then
    log_warn "ar-config.php not found! AR module may not work."
fi

# Test database connection (optional)
if command -v php &> /dev/null; then
    log_info "Testing database connection..."
    php -r "
    if (file_exists('event-server.php')) {
        include 'event-server.php';
        if (\$conn->connect_error) {
            echo 'Database connection failed!';
            exit(1);
        } else {
            echo 'Database connection successful!';
        }
    } else {
        echo 'No database config found - skipping test';
    }
    "
fi

log_info "✅ Deployment completed successfully!"
log_info "Application URL: https://dev.scala4.com/event-login.php"
log_info "Database Admin: https://dev.scala4.com/phpmyadmin/"

echo ""
log_warn "Remember to:"
log_warn "1. Test the application at dev.scala4.com/event-login.php"
log_warn "2. Check error logs if anything isn't working"
log_warn "3. Backup is available at: $BACKUP_PATH"
