name: Update Plugin Version

on:
  release:
    types: [created, edited]

jobs:
  update-version:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Get release tag
        id: get_tag
        run: echo "TAG=${GITEA_REF#refs/tags/}" >> $GITEA_ENV

      - name: Update version in plugin file
        run: |
          # Replace version in plugin header
          sed -i "s/Version: .*/Version: ${{ env.TAG }}/" wp-digital-download.php
          
          # Replace version in PHP constant
          sed -i "s/define('WPDD_VERSION', '[^']*');/define('WPDD_VERSION', '${{ env.TAG }}');/" wp-digital-download.php
          
          # Verify changes
          echo "Plugin header version:"
          grep "Version:" wp-digital-download.php
          echo "PHP constant version:"
          grep "WPDD_VERSION" wp-digital-download.php

      - name: Commit changes
        run: |
          git config --local user.email "action@gitea.com"
          git config --local user.name "Gitea Action"
          git add wp-digital-download.php
          git commit -m "Update version to ${{ env.TAG }}"
          git push

      - name: Create plugin zip
        run: |
          mkdir -p /tmp/wp-digital-download
          rsync -av --exclude=".git" --exclude=".gitea" --exclude=".playwright-mcp" --exclude="build" . /tmp/wp-digital-download/
          cd /tmp
          zip -r $GITEA_WORK_DIR/wp-digital-download.zip wp-digital-download

      - name: Upload zip to release
        uses: actions/upload-release-asset@v1
        env:
          GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
        with:
          upload_url: ${{ gitea.event.release.upload_url }}
          asset_path: build/wp-digital-download.zip
          asset_name: wp-digital-download.zip
          asset_content_type: application/zip