#!/bin/bash
# WordChat Plugin Version Updater
# Updates version in all 3 required locations

set -e

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

echo -e "${BLUE}==================================${NC}"
echo -e "${BLUE}WordChat Version Updater${NC}"
echo -e "${BLUE}==================================${NC}"

# Get current version
CURRENT_VERSION=$(grep -E "^\s*\*\s*Version:" wordchat-pro.php | sed -E 's/.*Version:[[:space:]]*([0-9.]+).*/\1/')
echo -e "Current version: ${YELLOW}$CURRENT_VERSION${NC}"
echo ""

# Ask for new version
read -p "Enter new version (e.g., 0.1.28): " NEW_VERSION

# Validate version format
if ! [[ $NEW_VERSION =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    echo -e "${RED}Error: Invalid version format. Use X.Y.Z (e.g., 0.1.28)${NC}"
    exit 1
fi

echo ""
echo -e "Updating from ${YELLOW}$CURRENT_VERSION${NC} to ${GREEN}$NEW_VERSION${NC}"
echo ""

# Confirm
read -p "Continue? (y/n): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Cancelled."
    exit 0
fi

# Backup files
echo "Creating backups..."
cp wordchat-pro.php wordchat-pro.php.bak
cp readme.txt readme.txt.bak

# Update wordchat-pro.php plugin header
echo "Updating wordchat-pro.php header..."
sed -i.tmp "s/\* Version: $CURRENT_VERSION/* Version: $NEW_VERSION/" wordchat-pro.php

# Update WORDCHAT_VERSION constant
echo "Updating WORDCHAT_VERSION constant..."
sed -i.tmp "s/define('WORDCHAT_VERSION', '$CURRENT_VERSION');/define('WORDCHAT_VERSION', '$NEW_VERSION');/" wordchat-pro.php

# Update readme.txt stable tag
echo "Updating readme.txt stable tag..."
sed -i.tmp "s/Stable tag: .*/Stable tag: $NEW_VERSION/" readme.txt

# Clean up temp files
rm -f wordchat-pro.php.tmp readme.txt.tmp

# Verify changes
echo ""
echo -e "${GREEN}==================================${NC}"
echo -e "${GREEN}Version Updated Successfully!${NC}"
echo -e "${GREEN}==================================${NC}"
echo ""

# Show what was changed
echo "Updated locations:"
echo "1. wordchat-pro.php header:"
grep -n "Version:" wordchat-pro.php | head -1

echo "2. WORDCHAT_VERSION constant:"
grep -n "WORDCHAT_VERSION" wordchat-pro.php | head -1

echo "3. readme.txt stable tag:"
grep -n "Stable tag:" readme.txt

echo ""
echo -e "${BLUE}Backups created:${NC}"
echo "  - wordchat-pro.php.bak"
echo "  - readme.txt.bak"
echo ""
echo -e "${BLUE}Next steps:${NC}"
echo "1. Test the plugin with the new version"
echo "2. Run ./build.sh to create the release ZIP"
echo "3. Commit changes: git add . && git commit -m 'Bump version to $NEW_VERSION'"
echo ""
