---
description: Glitch Payment Gateway project coding guidelines — WooCommerce payment plugin conventions, stack, folder structure, dev commands
globs: 
alwaysApply: true
---

# Glitch Payment Gateway — Project Rules

## Project Overview

A bespoke WooCommerce payment gateway plugin for Glitch, a major South African payment provider. Enables merchants to accept payments through Glitch's infrastructure with support for multiple payment methods, webhooks, refunds, and full order status synchronization.

- **Plugin root:** `src/` — Main plugin PHP files, gateway class, includes
- **Includes:** `src/includes/` — Helper classes, API client, webhook handler
- **Admin:** `src/admin/` — WooCommerce settings page, admin views
- **Templates:** `src/templates/` — Checkout and payment form templates
- **Assets:** `src/assets/` — CSS and JS for checkout/admin
- **Docs:** `docs/` — Architecture, deployment, and task documentation
- **Tests:** `tests/` — PHPUnit test cases

## Stack

- **CMS:** WordPress 6.x
- **E-commerce:** WooCommerce 8.x+ (HPOS compatible)
- **Language:** PHP 8.1+
- **Database:** MySQL / MariaDB (via WordPress $wpdb and WC CRUD)
- **Payment Provider:** Glitch API (South Africa)
- **Currency:** ZAR (South African Rand)
- **Testing:** PHPUnit + WooCommerce test framework
- **Styling:** WordPress admin CSS + minimal custom checkout CSS
- **Dev Environment:** Docker (WordPress + MySQL containers)

---

## CRITICAL: Never Push to Live

You must **never** push, deploy, or sync code to the live/production environment. All live deployments are the user's responsibility. This includes:

- Running any deploy command that targets production
- Triggering any CI/CD pipeline that pushes to live
- Using `git push` to production branches
- Invoking any deploy action aimed at the live server

You may deploy to **local** or **staging** environments only.

---

## CRITICAL: Always Follow task.mdc

Before starting **any** task, you **MUST** read and follow the rules in `.cursor/rules/task.mdc`. This includes:

- Planning before implementation (Plan Node)
- Writing checklists to `docs/task/todo.md` **for planned, multi-step work** (features, refactors, multi-step tasks) — not for every ad-hoc single-message request or quick fix
- Updating `docs/task/lessons.md` after any user correction
- Verification before marking work complete (3-tier verification gate pipeline)
- The full Task Management Protocol

These rules apply to **every** task — including ad-hoc chat requests, quick fixes, and multi-step implementations. **Never skip this.**

> **The `manage_todo_list` IDE tool is NOT a substitute for `docs/task/todo.md`.** For planned multi-step work, you MUST write task checklists to the file. The IDE tool is supplementary only — the file is the mandatory source of truth.

---

## CRITICAL: Document & Commit at Batch Boundaries (Session-Aware)

During iterative chat sessions, you do NOT run the full logging/doc-sync/commit cycle after every single message. Instead, **implement changes immediately** but **defer** the documentation and commit cycle until a **batch boundary**.

### What is a batch boundary?

A batch boundary occurs when ANY of the following is true:

1. **User signals completion** — says "done", "that's good", "commit", "push", "wrap up", or similar
2. **User changes topic** — moves to a clearly different task or feature area
3. **You reach ~5 accumulated changes** — auto-trigger if many small changes have piled up without a commit
4. **Session is ending** — user says goodbye or you detect the conversation is wrapping up
5. **User explicitly asks to commit** — always commit immediately when asked

### At each batch boundary, run the full cycle ONCE:

0. **Pre-verification gates (BLOCKING — must ALL pass before proceeding to steps 1–7):**
   - **a. Agent Self-Evaluation Gate** — Ask yourself: *"Is what I implemented the best solution for this problem?"* If NO, re-implement. Iterate until genuinely YES. See `task.mdc` → Agent Self-Evaluation Gate.
   - **b. Visual Verification Gate** — If the work affects front-end/UI: open a browser, navigate to affected pages, resize to proper dimensions, take screenshots, and visually confirm. **HTML inspection, DOM analysis, `curl`, and reading source code do NOT count** — only rendered browser screenshots. If purely back-end, this auto-passes. See `task.mdc` → Visual Verification Gate.
   - **c. User Verification Gate** — ONLY after gates (a) and (b) pass: STOP. Summarize changes, include visual verification results if applicable. Include an explicit `Not Tested` list (or `Not Tested: none`). Ask: "Would you like to test this before I proceed with docs and commit?" Wait for user response.
   - **d. Scenario Evidence Rule (MANDATORY)** — Verify all required behavior-path scenarios were executed end-to-end. **Test Fixture Rule:** If a scenario requires specific data that no existing page/view/route provides, create a temporary test fixture. Clean up after.
   - Trivial changes (typos, comment edits, data-only updates) may skip all three gates.
   - **CRITICAL: Steps 1–7 below are LOCKED until step 0 completes.**
1. **Log agent observations (BLOCKING GATE)** — Follow `.cursor/rules/agent-observations.mdc`. Append to `docs/agent-observations/`. If zero: "Observations: none." **Silence is a violation.**
2. **Update the daily task log** — add row(s) to `docs/task/logs/YYYY-MM-DD.md`. Create if missing.
3. **Update affected documentation** — per `doc-sync.mdc` rules. Only for significant changes.
4. **Get explicit user approval before committing** — present **3 numbered commit message options**. Ask: "Ready to commit and push?" Wait for user.
5. **Verification gate (BLOCKING)** — Confirm ALL verification steps passed.
6. **Commit & push (ONLY after explicit user approval)** — follow `commit.mdc` rules.

### Between batch boundaries:

- Implement changes as requested — no logging/commit overhead
- Keep mental track of what you've changed

---

## CRITICAL: Never Auto-Commit or Auto-Push

You must **NEVER** commit or push without **explicit user approval**. This applies to ALL branches, ALL tasks, ALL batch boundaries — no exceptions.

When you believe work is ready to commit:
1. Tell the user what changed (brief summary)
2. Present **3 numbered commit message options** (subject line only, concise → descriptive)
3. Ask: "Ready to commit?"
4. **Wait for the user to say yes**
5. After committing, ask before pushing: "Committed. Ready to push to <branch>?"
6. **Wait for explicit approval**

---

## CRITICAL: Date-Prefix All Generated Files

Every file you create inside `docs/` subdirectories that are date-scoped **MUST** include a date prefix: `YYYY-MM-DD-{slug}.md`.

- **Plans:** `docs/task/planning/draft/YYYY-MM-DD-{slug}.md`
- **Reports:** `docs/reports/YYYY-MM-DD-{slug}.md`

Exceptions: `docs/task/todo.md`, `docs/task/lessons.md`, `docs/task/logs/YYYY-MM-DD.md`, observation log files.

---

## CRITICAL: No Backups in Source Directories

Never create backup files, hidden folders, or temporary artifacts inside the source directories. **No exceptions.** No `.bak`, `.backup.json`, `.old`, `.orig`, `.tmp` files. Use `docs/backups/` if needed.

---

## MANDATORY: Auto-Update Documentation

When working on files under `src/`, documentation sync rules apply automatically via `.cursor/rules/doc-sync.mdc`.

### Quick Triage — Which Doc to Read First

| If this is broken… | Read first |
|---------------------|------------|
| Payment not initiating / checkout errors | [docs/plugin/features/1-checkout-flow.md](docs/plugin/features/1-checkout-flow.md) |
| Webhook not processing / duplicate events | [docs/plugin/features/2-webhooks.md](docs/plugin/features/2-webhooks.md) |
| Refund failing / chargeback issues | [docs/plugin/features/3-refunds.md](docs/plugin/features/3-refunds.md) |
| Admin settings not saving / credentials | [docs/plugin/features/4-admin-settings.md](docs/plugin/features/4-admin-settings.md) |
| Order status wrong / transaction ID missing | [docs/plugin/features/5-order-management.md](docs/plugin/features/5-order-management.md) |
| API errors / authentication failing | [docs/plugin/architecture/2-api-integration.md](docs/plugin/architecture/2-api-integration.md) |
| Signature verification / security issue | [docs/plugin/architecture/3-security.md](docs/plugin/architecture/3-security.md) |
| Gateway not loading / class errors | [docs/plugin/architecture/1-gateway-architecture.md](docs/plugin/architecture/1-gateway-architecture.md) |

---

## CRITICAL: Route Doc Work Through Index Tables

When working inside `src/`, you **MUST** start by searching the split index tables:

```bash
rg -n -i "<task keywords>" docs/plugin/**/0-index.md
```

Use 1–3 task-specific terms relevant to the work area. **Never skip this search step.**

---

## Related Rule Files

Read these **before** working in their domain:

| When working on… | Read… |
|-------------------|-------|
| **ALL tasks (always read first)** | **`.cursor/rules/task.mdc`** |
| **Rate limit prevention (always active)** | **`.cursor/rules/ratelimitting.mdc`** |
| **Source code changes (doc sync rules)** | **`.cursor/rules/doc-sync.mdc`** |
| **Pre-commit observations (source code work)** | **`.cursor/rules/agent-observations.mdc`** |
| Browser verification of UI changes | `.cursor/rules/devtools.mdc` |
| Committing and pushing changes | `.cursor/rules/commit.mdc` |

---

## MANDATORY: Browser Verification Before Completion

After **every** new feature, bug fix, or change that touches the UI or frontend behavior, you **MUST** verify using browser tools before marking complete. See `.cursor/rules/devtools.mdc`.

---

## MANDATORY: Element IDs on Every Rendered Element

Every HTML-producing element you create **MUST** have a descriptive `id` attribute. **Zero exceptions.**

### Naming Convention

`{page-or-feature}-{section}-{element}` in kebab-case.

### What Must Have an ID

- All container elements
- All interactive controls (buttons, inputs, selects)
- All table parts
- All form labels
- All list items in loops (use dynamic IDs with unique key)

### Hard Rules

1. **No element may be rendered without an `id`.**
2. **Dynamic list items** use the item's unique key in the `id`.
3. **Nested elements** maintain parent hierarchy in their `id` prefix.
4. **If any element is missing an `id`, the code is incomplete.**

### PHP Template Examples

```php
<div id="glitch-checkout-form-container">
  <label id="glitch-checkout-card-label" for="glitch-card-number">Card Number</label>
  <input id="glitch-checkout-card-number" type="text" name="card_number" />
  <button id="glitch-checkout-submit-btn" type="submit">Pay Now</button>
</div>
```

```php
<?php foreach ( $payment_methods as $method ) : ?>
  <div id="glitch-method-<?php echo esc_attr( $method->id ); ?>-container">
    <input id="glitch-method-<?php echo esc_attr( $method->id ); ?>-radio" type="radio" name="payment_method" />
    <label id="glitch-method-<?php echo esc_attr( $method->id ); ?>-label"><?php echo esc_html( $method->title ); ?></label>
  </div>
<?php endforeach; ?>
```

---

## MANDATORY: Task Tracking

Follow the full task lifecycle defined in `.cursor/rules/task.mdc`:

1. Add task item(s) in `docs/task/todo.md` before implementation
2. Create `docs/task/planning/draft/{YYYY-MM-DD}-{slug}.md` for multi-step tasks
3. Track progress in `docs/task/todo.md`
4. Move completed items out of `docs/task/todo.md`
5. Append a row to today's daily task log `docs/task/logs/YYYY-MM-DD.md`

### Task Ledger — Daily Log Files (`docs/task/logs/YYYY-MM-DD.md`)

```markdown
# Task Log — MM/DD/YYYY

> 0 tasks

| Title | Description | Start Date | End Date | Category | Type |
| --- | --- | --- | --- | --- | --- |
```

- `Title` — Action-oriented, specific enough to be searchable
- `Description` — Concise, outcome-focused
- `Start Date` / `End Date` — `MM/DD/YYYY` format
- `Category` — One of: `Payment`, `Webhooks`, `Refunds`, `Admin`, `API`, `Security`, `Config`, `Bug`, `Docs`
- `Type` — `Task` (single-scope) or `Sprint` (grouped multi-item work)

---

## Coding Conventions

### PHP

- Follow WordPress Coding Standards (WPCS)
- Use strict type declarations: `declare(strict_types=1);`
- Prefix all functions, classes, and hooks with `glitch_` or `Glitch_`
- Use `sanitize_*()` for all input, `esc_*()` for all output — no exceptions
- Use WordPress `$wpdb->prepare()` for all database queries — never raw SQL with user input
- Store sensitive data (API keys) using `WC_Settings_API` — never in plain options
- Use WooCommerce CRUD methods (not direct meta queries) for order data

### Gateway Class

- Extend `WC_Payment_Gateway` for the main gateway class
- Implement `process_payment()`, `process_refund()`, `init_form_fields()`, `admin_options()`
- Use `$this->log()` wrapper for debug logging (respects debug toggle)
- Store Glitch transaction references in order meta with prefixed keys: `_glitch_transaction_id`, `_glitch_payment_status`
- Use `wc_get_order()` to retrieve orders — never `new WC_Order()` directly

### Webhooks & Security

- Verify webhook signatures using HMAC-SHA256 before processing any event
- Implement idempotent webhook handling — check `_glitch_webhook_processed_{event_id}` meta before acting
- Return proper HTTP status codes: 200 for processed, 400 for invalid, 500 for errors
- Never trust client-side payment status — always verify server-to-server

### File Naming

- Classes: `class-glitch-{name}.php` (e.g., `class-glitch-gateway.php`)
- Includes: `{function-area}.php` (e.g., `webhook-handler.php`, `api-client.php`)
- Templates: `{template-name}.php` in `src/templates/`
- Admin views: `{view-name}.php` in `src/admin/views/`

---

## Dev Server & Build

```bash
cd <project-path>
docker compose up -d          # Start WordPress + MySQL containers
# Dev site: http://localhost:8080
# WP Admin: http://localhost:8080/wp-admin
composer install              # Install PHP dependencies
composer test                 # Run PHPUnit tests
composer lint                 # Run PHPCS linter
```
