#!/bin/bash
#
# sync-projects.sh - Sincronizar melhorias do P4 para outros projetos
#
# Uso:
#   ./sync-projects.sh              # Sincroniza todos os projetos
#   ./sync-projects.sh p1 p3        # Sincroniza apenas p1 e p3
#   ./sync-projects.sh --status     # Mostra status de cada projeto
#   ./sync-projects.sh --diff p1    # Mostra diferenças entre P4 e p1
#
# O P4 é o projeto de DESENVOLVIMENTO (master).
# As alterações feitas no P4 são propagadas para p1, p2, p3, p5, p6.
#
# Arquivos PRESERVADOS em cada projeto (nunca sobrescritos):
#   - application/config/app-config.php (credenciais DB, base URL)
#   - uploads/ (arquivos de usuários)
#   - application/logs/ (logs)
#   - vendor/ e node_modules/ (dependências)
#

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CORE_REPO="$SCRIPT_DIR/perfex-core.git"
DEV_PROJECT="$SCRIPT_DIR/p4"
ALL_TARGETS="p1 p2 p3 p5 p6"
LOG_FILE="$SCRIPT_DIR/sync-projects.log"

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

log() {
    echo -e "$1"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $(echo -e "$1" | sed 's/\x1b\[[0-9;]*m//g')" >> "$LOG_FILE"
}

# ============================================================
# STEP 1: Commit changes in P4 to central repo
# ============================================================
commit_p4() {
    log "${BLUE}[P4] Verificando mudanças no projeto de desenvolvimento...${NC}"
    cd "$DEV_PROJECT"

    # Check for changes
    if git diff --quiet && git diff --cached --quiet && [ -z "$(git ls-files --others --exclude-standard)" ]; then
        log "${GREEN}[P4] Sem mudanças novas para sincronizar.${NC}"
        return 0
    fi

    # Show summary of changes
    changed=$(git diff --stat 2>/dev/null | tail -1)
    new_files=$(git ls-files --others --exclude-standard | wc -l)
    log "${YELLOW}[P4] Mudanças encontradas: $changed | Novos arquivos: $new_files${NC}"

    # Stage and commit
    git add -A
    local msg="Sync $(date '+%Y-%m-%d %H:%M') - $(git diff --cached --stat | tail -1)"
    git commit -m "$msg" > /dev/null 2>&1
    git push origin master > /dev/null 2>&1

    log "${GREEN}[P4] Commit e push: $msg${NC}"
    return 1
}

# ============================================================
# STEP 2: Sync target project from central repo
# ============================================================
sync_project() {
    local project=$1
    local project_dir="$SCRIPT_DIR/$project"

    if [ ! -d "$project_dir" ]; then
        log "${RED}[$project] Diretório não encontrado: $project_dir${NC}"
        return 1
    fi

    log "${BLUE}[$project] Sincronizando...${NC}"

    cd "$project_dir"

    # Initialize git if needed
    if [ ! -d ".git" ]; then
        log "${YELLOW}[$project] Inicializando git...${NC}"
        cp "$DEV_PROJECT/.gitignore" "$project_dir/.gitignore" 2>/dev/null
        git init > /dev/null 2>&1
        git config user.email "dev@ominicrm.com.br"
        git config user.name "OmniCRM Dev"
        git remote add origin "$CORE_REPO" 2>/dev/null
        # Initial add to track local state
        git add -A > /dev/null 2>&1
        git commit -m "Local state before sync" > /dev/null 2>&1
    fi

    # Backup app-config.php
    local config_backup="/tmp/${project}_app-config.php.bak"
    cp "$project_dir/application/config/app-config.php" "$config_backup" 2>/dev/null

    # Fetch latest from central repo
    git fetch origin master > /dev/null 2>&1

    # Use rsync approach (more reliable for non-git managed projects)
    rsync -av --delete \
        --exclude='application/config/app-config.php' \
        --exclude='.git/' \
        --exclude='uploads/' \
        --exclude='vendor/' \
        --exclude='node_modules/' \
        --exclude='application/logs/' \
        --exclude='application/cache/' \
        --exclude='application/sessions/' \
        --exclude='assets/builds/' \
        "$DEV_PROJECT/" "$project_dir/" > /tmp/sync_${project}.log 2>&1

    # Restore config
    cp "$config_backup" "$project_dir/application/config/app-config.php" 2>/dev/null

    # Fix permissions
    find "$project_dir/application" -name "*.php" -exec chmod 644 {} \; 2>/dev/null
    find "$project_dir/modules" -name "*.php" -exec chmod 644 {} \; 2>/dev/null

    # Count changes
    local changes=$(grep -c "^[^.]" /tmp/sync_${project}.log 2>/dev/null || echo 0)
    log "${GREEN}[$project] Sincronizado ($changes arquivos atualizados)${NC}"

    return 0
}

# ============================================================
# STEP 3: Run new migrations
# ============================================================
run_migrations() {
    local project=$1
    local project_dir="$SCRIPT_DIR/$project"

    # Get DB credentials
    local config="$project_dir/application/config/app-config.php"
    local db_host=$(grep "APP_DB_HOST" "$config" | grep -oP "'[^']+'" | tail -1 | tr -d "'")
    local db_user=$(grep "APP_DB_USER" "$config" | grep -oP "'[^']+'" | tail -1 | tr -d "'")
    local db_pass=$(grep "APP_DB_PASS" "$config" | grep -oP "'[^']+'" | tail -1 | tr -d "'")
    local db_name=$(grep "APP_DB_NAME" "$config" | grep -oP "'[^']+'" | tail -1 | tr -d "'")

    # Get current DB migration version
    local db_version=$(mysql -h"$db_host" -u"$db_user" -p"$db_pass" "$db_name" -N -e "SELECT version FROM tblmigrations;" 2>/dev/null)

    # Get target version from config
    local config_version=$(grep "migration_version" "$project_dir/application/config/migration.php" | grep -oP '[0-9]+' | head -1)

    if [ "$db_version" = "$config_version" ]; then
        log "${GREEN}[$project] Migrations OK (v$db_version)${NC}"
    else
        log "${YELLOW}[$project] Migration: DB v$db_version -> Config v$config_version${NC}"
        log "${YELLOW}[$project] ATENÇÃO: Rode as migrations manualmente ou acesse o admin para aplicar.${NC}"
    fi
}

# ============================================================
# STATUS: Show sync status
# ============================================================
show_status() {
    log "${BLUE}=== Status dos Projetos ===${NC}"
    echo

    cd "$DEV_PROJECT"
    local p4_commit=$(git log --oneline -1 2>/dev/null)
    log "P4 (dev): $p4_commit"

    local p4_changes=""
    if ! git diff --quiet 2>/dev/null || [ -n "$(git ls-files --others --exclude-standard 2>/dev/null)" ]; then
        p4_changes=" ${YELLOW}[mudanças não commitadas]${NC}"
    fi
    log "  Status:$p4_changes${GREEN} OK${NC}"
    echo

    for project in $ALL_TARGETS; do
        local project_dir="$SCRIPT_DIR/$project"
        local url=$(grep "APP_BASE_URL" "$project_dir/application/config/app-config.php" 2>/dev/null | grep -oP "'https?://[^']+'" | tr -d "'")
        local db_name=$(grep "APP_DB_NAME" "$project_dir/application/config/app-config.php" 2>/dev/null | grep -oP "'[^']+'" | tail -1 | tr -d "'")

        # HTTP check
        local http_code=$(curl -sk -o /dev/null -w "%{http_code}" "${url}admin" --max-time 5 2>/dev/null)
        local http_status="${GREEN}OK ($http_code)${NC}"
        if [ "$http_code" = "500" ] || [ "$http_code" = "000" ]; then
            http_status="${RED}ERRO ($http_code)${NC}"
        fi

        log "$project ($url)"
        log "  HTTP: $http_status | DB: $db_name"
    done
}

# ============================================================
# DIFF: Show differences
# ============================================================
show_diff() {
    local project=$1
    local project_dir="$SCRIPT_DIR/$project"

    log "${BLUE}=== Diferenças P4 vs $project ===${NC}"

    diff -rq \
        --exclude='.git' \
        --exclude='app-config.php' \
        --exclude='uploads' \
        --exclude='vendor' \
        --exclude='node_modules' \
        --exclude='logs' \
        --exclude='cache' \
        --exclude='sessions' \
        --exclude='builds' \
        "$DEV_PROJECT/" "$project_dir/" 2>/dev/null | head -50
}

# ============================================================
# MAIN
# ============================================================

echo "======================================"
echo "  Perfex CRM - Sync Projects"
echo "  Dev: P4 -> Targets: $ALL_TARGETS"
echo "======================================"
echo

case "$1" in
    --status)
        show_status
        ;;
    --diff)
        if [ -z "$2" ]; then
            echo "Uso: $0 --diff <projeto>"
            exit 1
        fi
        show_diff "$2"
        ;;
    --help)
        echo "Uso:"
        echo "  $0                    # Sincroniza todos os projetos"
        echo "  $0 p1 p3              # Sincroniza apenas p1 e p3"
        echo "  $0 --status           # Mostra status de cada projeto"
        echo "  $0 --diff p1          # Mostra diferenças entre P4 e p1"
        echo "  $0 --help             # Este help"
        ;;
    *)
        # Determine targets
        targets="$ALL_TARGETS"
        if [ -n "$1" ]; then
            targets="$@"
        fi

        # Step 1: Commit P4 changes
        commit_p4

        # Step 2: Sync each target
        for project in $targets; do
            sync_project "$project"
            run_migrations "$project"
            echo
        done

        # Final summary
        log "${GREEN}=== Sincronização completa! ===${NC}"
        log "Log salvo em: $LOG_FILE"
        ;;
esac
