# EL3AB Player App - Build Plan (PHP)

## Objective

Build an Arabic-first competitive gaming web app. Chess is the first fully playable game. PHP backend, vanilla HTML/CSS/JS frontend. Icons only (no emojis). chess.js for client-side move validation. Stockfish bot API for AI opponents.

---

## Tech Stack

| Layer | Tool |
|-------|------|
| Backend | PHP 8.x (server-rendered pages + JSON API endpoints) |
| Frontend | HTML5, CSS3 (custom properties + flexbox/grid), vanilla JS |
| Chess Logic | chess.js (browser, move validation + game state) |
| Chess Board | Custom HTML/CSS/JS board (drag & drop) |
| Icons | SVG icon system (inline SVGs, no emojis anywhere) |
| Database | PostgreSQL 15 via Supabase (self-hosted) |
| Auth | Supabase Auth (GoTrue) via REST API |
| Realtime | Supabase Realtime (WebSocket for live games) |
| Bot API | Stockfish API at stockfishapi.caprover.al-arcade.com |
| Deploy | Docker (php:8.3-apache) on CapRover, auto-deploy on git push |

---

## Server & Connections

| Resource | URL/Host |
|----------|----------|
| Server IP | 3.68.63.185 |
| SSH Key | `Connections and docs /NewServer.pem` (user: ubuntu) |
| Supabase Kong | https://safe-supabase-kong.caprover.al-arcade.com |
| Supabase Anon Key | `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlzcyI6InN1cGFiYXNlIiwiaWF0IjoxNzM1Njg5NjAwLCJleHAiOjE4OTM0NTYwMDB9.31PF6PvP-pSrvRuQwLFptQoejR0W1A7o53lZhEbnz84` |
| Supabase Service Key | `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoic2VydmljZV9yb2xlIiwiaXNzIjoic3VwYWJhc2UiLCJpYXQiOjE3MzU2ODk2MDAsImV4cCI6MTg5MzQ1NjAwMH0.wNfmuJNkX-bZwD7RbjxOChlRf_3Xm4I7bswEYTcDCg4` |
| App URL | https://el3ab-player.caprover.al-arcade.com |
| Stockfish API | https://stockfishapi.caprover.al-arcade.com |
| Stockfish Admin | admin / Alarcade123# |
| Stockfish Mgmt Key | sk-alarc-stockfish-mgmt-2024 |

---

## Deployment

Docker image: `php:8.3-apache`
- Apache serves PHP directly (no nginx needed)
- `captain-definition` points to Dockerfile
- CapRover auto-deploys on `git push`

```dockerfile
FROM php:8.3-apache
RUN docker-php-ext-install pdo pdo_pgsql pgsql
RUN a2enmod rewrite headers
COPY . /var/www/html/
COPY .htaccess /var/www/html/
RUN chown -R www-data:www-data /var/www/html
EXPOSE 80
```

---

## Project Structure

```
/
  captain-definition
  Dockerfile
  .htaccess
  config/
    database.php          -- Supabase REST + direct PG connection config
    constants.php         -- App constants, URLs, keys
  public/
    css/
      app.css             -- All styles (design tokens, components, layout)
      chessboard.css      -- Board-specific styles
    js/
      app.js              -- Global utilities, nav, toast system
      chess.min.js        -- chess.js library
      board.js            -- Chessboard rendering, drag/drop, animations
      game.js             -- Game logic (vs bot, timers, move submission)
      auth.js             -- Login/register/session management
      realtime.js         -- Supabase Realtime WebSocket client
    icons/
      sprite.svg          -- SVG sprite sheet (all icons)
    img/
      bots/               -- Bot portrait images
  pages/
    home.php              -- Dashboard (welcome, quick play, recent games)
    login.php             -- Login form
    register.php          -- Registration form
    play.php              -- Game selection + match settings
    game.php              -- Active chess game (board, clocks, controls)
    bots.php              -- Bot selection grid
    profile.php           -- Player profile + stats
    leaderboard.php       -- Rating leaderboard
    friends.php           -- Friends list + requests
    tournaments.php       -- Tournament listing
    tournament.php        -- Single tournament detail
    shop.php              -- Cosmetics store
    achievements.php      -- Achievement grid
    notifications.php     -- Notification center
    settings.php          -- User settings
    orgs.php              -- Organizations listing
    org.php               -- Single org detail
  api/
    auth.php              -- POST login/register/logout endpoints
    game.php              -- POST start-game, submit-move, resign, etc.
    profile.php           -- GET/PATCH profile data
    friends.php           -- POST add/accept/remove friend
    matchmaking.php       -- POST queue/dequeue
    leaderboard.php       -- GET rankings
    notifications.php     -- GET/PATCH notifications
    shop.php              -- GET items, POST purchase
    tournaments.php       -- GET list, POST register
  includes/
    header.php            -- HTML head + top nav
    footer.php            -- Bottom nav + closing tags
    auth_check.php        -- Session guard (redirect to login if not authed)
    supabase.php          -- Supabase REST API helper class
  templates/
    nav-desktop.php       -- Side navigation (desktop)
    nav-bottom.php        -- Bottom tab bar (mobile)
    toast.php             -- Toast notification markup
```

---

## Database (Supabase PostgreSQL - 99 tables exist)

### Key Tables Used by Player App

| Table | Purpose |
|-------|---------|
| profiles (48 cols) | Player data, ratings, stats, economy, bans |
| matches (39 cols) | Game records (FEN, PGN, moves, ratings, bot_id) |
| friendships | Friend requests and connections |
| notifications | Push-style notifications |
| tournaments | Tournament definitions |
| tournament_registrations | Player signups |
| leaderboards | Cached rankings |
| cosmetics | Shop items |
| player_cosmetics | Owned items |
| player_achievements | Achievement progress |
| achievements | Achievement definitions |
| economy_transactions | Coin/gem history |
| matchmaking_queue | Live matchmaking |
| feature_flags | Feature toggles |
| game_plugins | Available games (chess, backgammon, etc.) |
| organizations | Clubs/orgs |
| org_members | Org membership |
| rating_history | Rating over time |
| activity_feed | Social feed |

### profiles table columns
id, username, display_name, display_name_ar, avatar_url, banner_url, bio, bio_ar, country_code, city, preferred_language, elo_bullet, elo_blitz, elo_rapid, elo_classical, fide_id, fide_rating_standard, fide_rating_rapid, fide_rating_blitz, fide_title, xp, level, coins, gems, is_online, last_seen_at, is_banned, ban_reason, ban_expires_at, total_games_played, total_wins, total_draws, total_losses, total_tournaments_played, total_tournaments_won, win_streak, best_win_streak, created_at, updated_at, premium_currency, last_daily_reward, daily_streak, banned_by, current_game, games_played, avatar_frame_id, avatar_border_color, active_org_frame_id

### matches table columns
id, game_key, white_player_id, black_player_id, match_type, tournament_id, tournament_round, pairing_id, status, result, time_control, initial_time_ms, increment_ms, white_time_remaining_ms, black_time_remaining_ms, starting_fen, current_fen, pgn, moves (jsonb), move_count, game_state (jsonb), white_rating_before, black_rating_before, white_rating_after, black_rating_after, rating_change_white, rating_change_black, bot_id, bot_difficulty, is_flagged, cheat_score, analysis_complete, is_rated, is_rematch, rematch_of, started_at, completed_at, created_at, updated_at

---

## Stockfish Bot API

Base: https://stockfishapi.caprover.al-arcade.com

### Endpoints Used
- `POST /api/chess/move` -- Get bot move (fen + bot_id)
- `POST /api/chess/analyze` -- Position analysis (post-game)
- `GET /api/chess/bots` -- List all bots

### Available Bots (7)
| ID | Name (AR) | ELO | Style |
|----|-----------|-----|-------|
| amina | Amina al-Mubtadi'a | 400-600 | beginner |
| tarek | Tariq al-Mutahaffiz | 800-1000 | defensive |
| nour | Nour al-Muhajima | 1000-1200 | aggressive |
| omar | Omar al-Istratiji | 1200-1400 | positional |
| layla | Layla al-Mubdi'a | 1400-1600 | creative |
| ziad | Ziad al-Sulb | 1600-1800 | solid |
| grandmaster | al-Grand Master | 2000-2200 | near_perfect |

Portrait URLs: `https://stockfishapi.caprover.al-arcade.com/portraits/{bot_id}.jpg`

---

## Design System

### Colors (CSS custom properties)
```css
:root {
  --bg-0: #050D17;       /* page background */
  --bg-1: #0A1525;       /* header/nav background */
  --bg-2: #142640;       /* card background */
  --bg-3: #1C3254;       /* elevated elements, inputs */
  --gold: #E7A832;       /* brand accent, primary CTA */
  --cyan: #15D7FF;       /* secondary accent, active states */
  --blue: #2979FF;       /* links */
  --success: #34D399;
  --error: #EF4444;
  --warning: #F59E0B;
  --text-1: #F1F5F9;     /* primary text */
  --text-2: #94A3B8;     /* secondary text */
  --text-3: #64748B;     /* muted text */
  --border: rgba(255,255,255,0.10);
  --radius-sm: 8px;
  --radius-md: 12px;
  --radius-lg: 16px;
}
```

### Typography
- Arabic: 'IBM Plex Sans Arabic', system sans-serif
- Latin/numbers: 'Inter', system sans-serif
- Direction: RTL (dir="rtl" on html)

### Icons
- All icons are inline SVGs stored in a sprite (`public/icons/sprite.svg`)
- Usage: `<svg class="icon"><use href="/icons/sprite.svg#icon-name"></use></svg>`
- NO emojis anywhere in the UI
- Icon set needed: home, play, trophy, leaderboard, friends, shop, star, settings, profile, bell, coin, gem, clock, flag, crown, check, x, arrow-left, arrow-right, menu, search, plus, minus, edit, trash, send, heart, shield, sword, bot, board, piece

### Layout
- Mobile-first, max-width 600px content area centered
- Desktop: 72px side nav on right (RTL), content centered in remaining space
- Header: sticky top, 56px height
- Bottom nav: 64px, mobile only (hidden on lg+)
- All interactive elements min 48px touch target

---

## Build Phases

### Phase 1: Foundation
- [ ] Dockerfile + captain-definition + .htaccess
- [ ] config/database.php + config/constants.php
- [ ] includes/supabase.php (REST helper: GET, POST, PATCH via cURL)
- [ ] public/css/app.css (full design system + layout)
- [ ] public/icons/sprite.svg (all icons)
- [ ] includes/header.php + includes/footer.php
- [ ] templates/nav-desktop.php + templates/nav-bottom.php

### Phase 2: Auth
- [ ] pages/login.php (form + JS validation)
- [ ] pages/register.php (form + JS)
- [ ] api/auth.php (proxy to Supabase GoTrue: signup, login, logout, refresh)
- [ ] public/js/auth.js (session storage, token refresh, guards)
- [ ] includes/auth_check.php (server-side redirect)

### Phase 3: Home + Profile
- [ ] pages/home.php (welcome, play button, daily reward, recent games)
- [ ] pages/profile.php (avatar, ratings, stats, W/D/L, economy)
- [ ] api/profile.php (GET profile, PATCH update)
- [ ] public/js/app.js (global utils, fetch wrapper, toast)

### Phase 4: Chess Game (Core)
- [ ] public/js/chess.min.js (chess.js library)
- [ ] public/css/chessboard.css (board, pieces, squares, highlights)
- [ ] public/js/board.js (render board, drag/drop pieces, flip, animations)
- [ ] public/js/game.js (game flow: start, moves, clock, resign, draw offer)
- [ ] pages/game.php (game page: board + clocks + move list + controls)
- [ ] api/game.php (start game, record moves, end game, update ratings)

### Phase 5: Bot Play
- [ ] pages/bots.php (bot selection grid with portraits + difficulty)
- [ ] pages/play.php (game setup: select game, time control, mode)
- [ ] Bot integration in game.js (fetch from Stockfish API on bot turn)
- [ ] Thinking indicator animation

### Phase 6: Social
- [ ] pages/friends.php (friends list, pending requests, search)
- [ ] api/friends.php (add/accept/remove/block)
- [ ] pages/notifications.php (notification list, mark read)
- [ ] api/notifications.php (GET list, PATCH read)

### Phase 7: Competitive
- [ ] pages/leaderboard.php (rankings by time control)
- [ ] api/leaderboard.php (GET top 100 by category)
- [ ] pages/tournaments.php (tournament listing + filters)
- [ ] pages/tournament.php (single tournament: bracket, standings)
- [ ] api/tournaments.php (GET list, POST register)

### Phase 8: Economy & Cosmetics
- [ ] pages/shop.php (cosmetics grid with prices)
- [ ] api/shop.php (GET items, POST purchase)
- [ ] pages/achievements.php (achievement grid + progress)
- [ ] Daily reward system (claim endpoint)

### Phase 9: Organizations
- [ ] pages/orgs.php (org listing)
- [ ] pages/org.php (single org: members, info)
- [ ] Org membership API

### Phase 10: Settings + Polish
- [ ] pages/settings.php (account, preferences, language, sounds)
- [ ] Responsive testing (mobile 375px, tablet 768px, desktop 1920px)
- [ ] RTL polish pass
- [ ] Error pages (404, 500)
- [ ] Loading states, empty states
- [ ] Final deployment + smoke test

---

## Auth Flow (Supabase GoTrue via REST)

```
1. User submits login form
2. JS sends POST to /api/auth.php with email+password
3. PHP proxies to Supabase: POST {KONG_URL}/auth/v1/token?grant_type=password
4. On success: returns access_token + refresh_token
5. JS stores tokens in localStorage
6. All subsequent API calls include: Authorization: Bearer {access_token}
7. Token refresh: POST {KONG_URL}/auth/v1/token?grant_type=refresh_token
```

---

## Game Flow (vs Bot)

```
1. Player selects bot + time control on /play.php
2. JS creates match via POST /api/game.php (action=start, bot_id, time_control)
3. PHP inserts into matches table, returns match_id + starting FEN
4. Redirect to /game.php?id={match_id}
5. Board renders from FEN using chess.js + board.js
6. Player makes move -> chess.js validates -> POST /api/game.php (action=move)
7. PHP updates matches.moves + current_fen
8. JS calls Stockfish API: POST /api/chess/move with current FEN + bot_id
9. Bot response arrives -> animate move on board -> update state
10. Repeat until checkmate/stalemate/resign/timeout
11. PHP updates match result + rating changes
```

---

## Key Principles

1. NO emojis - only SVG icons from the sprite
2. Arabic-first RTL layout throughout
3. PHP renders pages server-side, JS handles interactivity
4. All API calls go through /api/*.php (acts as proxy to Supabase)
5. chess.js runs client-side for instant move validation
6. Clean, dark gaming aesthetic with gold/cyan accents
7. Mobile-first but desktop must look proper (centered content, side nav)
8. Every page loads fast - no SPA overhead, no build step for frontend
