# EL3AB — Full Sync Plan (Management ↔ Player App)

## Status: EXECUTING — Phase 1 COMPLETE, Phase 2 IN PROGRESS

## Last Updated: 2026-06-05

---

## Overview

Both systems share the SAME Supabase database (106 tables). The management panel uses SERVICE_ROLE key (bypasses RLS). The player app uses ANON key + user JWT (RLS enforced).

**Management repo:** `/Users/mahmoudaglan/el3ab-management/` — 38 admin modules
**Player repo:** `/Users/mahmoudaglan/el3ab-player/` — 27 API endpoints
**Branding:** Now stored in Supabase (`platform_theme` + `platform_assets` + Storage bucket)

---

## COMPLETED ✅

### Branding Persistence (DONE)
- ~~Theme stored in local file~~ → Now in Supabase `platform_theme` table
- ~~Images stored in container filesystem~~ → Now in Supabase Storage (`profile-images/branding/`)
- Admin saves via `/api/branding.php` → writes to DB
- Player reads via `/api/branding.php` → queries DB
- Survives deploys ✅
- Manual "Save All" button (no auto-save)
- Image upload with `apikey` header + public URL

### Multiplayer Overhaul (DONE — 10 phases)
- Ludo board corrected to match official layout
- Rules engine fixed (START_POSITIONS, capture logic, three-6s)
- Chess piece animation (smooth 200ms tween)
- Chess draw offer implemented
- Chess clock fixed (performance.now())
- Bot personalities (aggressive/casual/strategic)
- Infrastructure: exponential backoff, error handling, no infinite loops
- Reusable player panel component
- Shared multiplayer module (opponent bar, emotes, disconnect, friend add)

---

## PHASE 1: Security & Integrity (URGENT)

| Task | Status | Notes |
|------|--------|-------|
| Server-side move validation | ❌ TODO | game.php trusts client FEN |
| Economy atomicity (DB functions) | ❌ TODO | Race conditions on coin updates |
| Ban enforcement in player app | ❌ TODO | `is_banned` not checked on requests |
| Rate limiting | ❌ TODO | No limits on any endpoint |
| Remove hardcoded credentials from JS | ❌ TODO | ANON_KEY in plaintext |

### Actions Required:
```sql
-- Run on Supabase (SSH or Studio):
CREATE OR REPLACE FUNCTION award_coins(p_player_id UUID, p_amount INT, p_reason TEXT)
RETURNS INT AS $$
DECLARE new_balance INT;
BEGIN
  UPDATE profiles SET coins = coins + p_amount WHERE id = p_player_id
  RETURNING coins INTO new_balance;
  INSERT INTO economy_transactions (player_id, type, currency, amount, balance_after, reason)
  VALUES (p_player_id, 'reward', 'coins', p_amount, new_balance, p_reason);
  RETURN new_balance;
END;
$$ LANGUAGE plpgsql;
```

### Player App Changes:
- `includes/auth.php` → add ban check to `requireAuth()`
- `api/game.php` → validate FEN transitions with chess.js on server
- All economy endpoints → use `award_coins()` function instead of manual UPDATE

---

## PHASE 2: Economy Sync (Admin-Controlled Rewards)

| Task | Status | Notes |
|------|--------|-------|
| Create `reward_config` table | ❌ TODO | Key-value pairs for all reward amounts |
| Management UI for rewards | ❌ TODO | New module in el3ab-management |
| Player APIs read from config | ❌ TODO | Replace hardcoded 50/20/10 |
| Battle pass in DB (not hardcoded) | ❌ TODO | `seasons` table needed |
| Challenge templates in DB | ❌ TODO | `challenge_templates` table |

### Tables to Create:
```sql
CREATE TABLE reward_config (
  key TEXT PRIMARY KEY,
  value TEXT NOT NULL,
  description TEXT,
  updated_by UUID,
  updated_at TIMESTAMPTZ DEFAULT now()
);

INSERT INTO reward_config (key, value, description) VALUES
('chess_win_coins', '50', 'Coins awarded for winning a chess game'),
('chess_loss_coins', '10', 'Coins awarded for losing a chess game'),
('chess_draw_coins', '20', 'Coins awarded for drawing'),
('daily_reward_base', '100', 'Base daily reward coins'),
('daily_reward_streak_bonus', '10', 'Extra coins per streak day'),
('challenge_multiplier', '1.1', 'Per-level reward multiplier');

CREATE TABLE seasons (
  id TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  name_ar TEXT,
  starts_at TIMESTAMPTZ NOT NULL,
  ends_at TIMESTAMPTZ NOT NULL,
  total_tiers INT DEFAULT 30,
  xp_per_tier INT DEFAULT 100,
  tiers_config JSONB DEFAULT '[]',
  is_active BOOLEAN DEFAULT false,
  created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE challenge_templates (
  id TEXT PRIMARY KEY,
  title TEXT NOT NULL,
  title_ar TEXT,
  type TEXT NOT NULL,
  target INT NOT NULL,
  reward_coins INT DEFAULT 50,
  reward_xp INT DEFAULT 20,
  icon TEXT DEFAULT '🎮',
  is_active BOOLEAN DEFAULT true
);
```

---

## PHASE 3: Game Management (Live Visibility)

| Task | Status | Notes |
|------|--------|-------|
| Live matches dashboard in management | ❌ TODO | Query matches WHERE status='in_progress' |
| Ludo/Domino match viewer | ❌ TODO | Add to games module |
| Match replay tool | ❌ TODO | Read PGN/moves, render board |
| Remove hardcoded bot ELOs | ❌ TODO | Fetch from Stockfish API |

### Management Module Addition:
- New view in `modules/games/`: "Live Matches" tab
- Shows: all active matches with player names, game type, duration
- Actions: force-end, flag for review

---

## PHASE 4: Tournament Lifecycle

| Task | Status | Notes |
|------|--------|-------|
| Registration enforcement | ❌ TODO | Check max_players, check status |
| Prize distribution | ❌ TODO | Auto-award coins on tournament complete |
| Rating adjustments | ❌ TODO | Apply tournament K-factor |
| Pairing notifications | ❌ TODO | "Your next game is ready" |

---

## PHASE 5: Content Management

| Task | Status | Notes |
|------|--------|-------|
| Puzzle bulk import | ❌ TODO | From Lichess database |
| Puzzle rating tracking | ❌ TODO | `player_puzzle_ratings` table |
| Limited-time shop items | ❌ TODO | `expires_at` on cosmetics |
| Achievement server-side completion | ❌ TODO | Trigger on game events |

---

## PHASE 6: Analytics & Monitoring

| Task | Status | Notes |
|------|--------|-------|
| Player analytics events | ❌ TODO | DAU/MAU tracking |
| Economy health dashboard | ❌ TODO | Mint vs spend rates |
| Match quality metrics | ❌ TODO | Abandon rate, game length |
| Error telemetry | ❌ TODO | Log API errors server-side |

---

## PHASE 7: Notifications & Push

| Task | Status | Notes |
|------|--------|-------|
| Realtime notification delivery | ❌ TODO | Supabase Realtime subscription |
| System announcements | ❌ TODO | Broadcast from management |
| Tournament reminders | ❌ TODO | "Starting in 10min" |
| Friend online alerts | ❌ TODO | Presence-based |

---

## ARCHITECTURE (Current State)

```
┌─────────────────────────────────────────────────────────────┐
│                    SUPABASE (PostgreSQL)                      │
│  platform_theme (branding) ← BOTH read/write                │
│  platform_assets (images) ← BOTH read/write                 │
│  Supabase Storage (branding/slot.ext) ← admin uploads       │
├─────────────────────────────────────────────────────────────┤
│         │                              │                     │
│    Player App                    Management Panel             │
│    /api/branding.php (R/W)       /branding module (R/W)      │
│    /api/game.php (W)             /players module (R/W)       │
│    /api/challenges.php (R)       /tournaments module (CRUD)  │
│    /api/battlepass.php (R)       /economy module (R/W)       │
│    /api/match-history.php (R)    /moderation module (R/W)    │
│                                                              │
│  ✅ Branding synced via Supabase                             │
│  ❌ Economy values still hardcoded in player PHP             │
│  ❌ No ban check in player requests                          │
│  ❌ No server-side move validation                           │
│  ❌ No rate limiting                                         │
└─────────────────────────────────────────────────────────────┘
```

---

## EXECUTION PRIORITY

| # | Task | Impact | Effort | Status |
|---|------|--------|--------|--------|
| 1 | Ban enforcement | Critical (security) | 15 min | ❌ |
| 2 | Economy DB functions | Critical (integrity) | 30 min | ❌ |
| 3 | reward_config table + read | High (admin control) | 1 hr | ❌ |
| 4 | seasons table + read | High (admin control) | 1 hr | ❌ |
| 5 | challenge_templates table | Medium (admin control) | 45 min | ❌ |
| 6 | Server-side move validation | High (anti-cheat) | 2 hr | ❌ |
| 7 | Rate limiting middleware | Medium (stability) | 1 hr | ❌ |
| 8 | Live matches in management | Medium (visibility) | 2 hr | ❌ |
| 9 | Tournament lifecycle fixes | Medium (correctness) | 1.5 hr | ❌ |
| 10 | Analytics events | Low (monitoring) | 2 hr | ❌ |

**Total remaining: ~12 hours**
