name: WordPress Plugin CI

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
  workflow_dispatch:          # اجرای دستی هم فعال باشه

jobs:

  # ────────── Job 1: بررسی Syntax ──────────
  syntax-check:
    name: PHP Syntax Check
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.2'

      - name: Check PHP syntax errors
        run: find . -name "*.php" -exec php -l {} \;

  # ────────── Job 2: استانداردهای کدنویسی ──────────
  coding-standards:
    name: WordPress Coding Standards
    runs-on: ubuntu-latest
    needs: syntax-check
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.head_ref }}

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.2'
          tools: composer, cs2pr

      - name: Install Composer dependencies
        run: composer install --no-progress --prefer-dist

      # اول خودکار فیکس کن
      - name: Auto-fix with PHPCBF
        run: composer phpcbf || true
        # || true چون اگه چیزی برای فیکس نباشه exit code 0 نمیده

      # اگه تغییری بود، commit بزن
      - name: Commit fixes
        run: |
          git config --local user.email "github-actions[bot]@users.noreply.github.com"
          git config --local user.name "github-actions[bot]"
          git diff --quiet || (git add -A && git commit -m "🔧 Auto-fix coding standards via PHPCBF")
          git push || true

      # بعد بررسی کن خطای دیگه‌ای مونده یا نه
      - name: Run PHPCS
        run: composer phpcs

  # ────────── Job 3: تست روی چند نسخه PHP ──────────
  multi-version-test:
    name: PHP ${{ matrix.php }} | WP ${{ matrix.wp }}
    runs-on: ubuntu-latest
    needs: syntax-check

    strategy:
      matrix:
        php: ['7.4', '8.0', '8.1', '8.2']
        wp: ['6.3', 'latest']

    services:
      mysql:
        image: mysql:5.7
        env:
          MYSQL_ROOT_PASSWORD: root
          MYSQL_DATABASE: wordpress_test
        ports:
          - 3306:3306

    steps:
      - uses: actions/checkout@v4

      - name: Setup PHP ${{ matrix.php }}
        uses: shivammathur/setup-php@v2
        with:
          php-version: ${{ matrix.php }}
          extensions: mysqli
          tools: phpunit

      - name: Install WP Test Suite
        run: |
          bash bin/install-wp-tests.sh wordpress_test root root 127.0.0.1 ${{ matrix.wp }}

      - name: Run PHPUnit
        run: phpunit
