# 🚀 TidyFactor-Go CMS — Architecture & Technical Reference

## 🌟 The AI-Native Website Operating System (v1.6.1)

**TidyFactor-Go** is a modern, zero-dependency, document-driven Website Operating System engineered for rapid deployment, extreme stability, and native AI coding agent collaboration. It combines a state-of-the-art **React 19 + Tailwind CSS v4** frontend with an ultra-lightweight **PHP Flight + SQLite 3 WAL** backend.

```text
                    TidyFactor-Go Master Architecture
                                   │
       ┌───────────────────────────┼───────────────────────────┐
       ↓                           ↓                           ↓
🎨 Modern Frontend          ⚡ Headless REST API         💾 Storage & DB
 React 19 + TypeScript       PHP Flight Framework        SQLite 3 (WAL Mode)
 Vite 6 + Tailwind v4        15 RESTful Endpoints        JSON-First Document Model
 Radix UI + Lucide           Bcrypt Auth + Rate Limit    Self-Healing Migrations
 Google GenAI Integration    SVG XSS Sanitizer           One-Click Unified Backup
       │                           │                           │
       └───────────────────────────┼───────────────────────────┘
                                   ↓
                   Zero-Build Production Deployment
               (Apache / LiteSpeed / cPanel / WHM Ready)
```

---

## 🏛️ 1. Frontend Architecture & Technology Stack

The client application is built on cutting-edge web foundations, designed for instant reactivity, complete internationalization, and high-converting visual polish:

| Technology | Version | Architectural Role |
| :--- | :--- | :--- |
| **React** | `19.0.1` | Concurrent rendering, modern hooks, and state management |
| **Vite** | `6.2.3` | Ultra-fast HMR and optimized production bundle compilation |
| **Tailwind CSS** | `v4.1.14` | Next-generation CSS engine via `@tailwindcss/vite` |
| **Radix UI** | Latest | Unstyled, fully accessible UI primitives (`Slot`, `Select`, `Switch`, `Tooltip`) |
| **Icons** | `Lucide React` | Clean, lightweight SVG icon system |
| **Animation** | `Framer Motion` + `GSAP` | Smooth scroll sequences, page transitions, and micro-interactions |
| **AI Content** | `@google/genai` | Google Gemini API integration for native AI copywriting & translation |
| **Forms** | `react-hook-form` + `zod` | Performant form state with strict schema validation |
| **i18n** | `i18next` + `react-i18next` | Native Arabic (RTL) and English (LTR) language switching |

### Frontend Directory Structure:
```text
src/
├── assets/         ← Brand logos, icons, and static images
├── components/     ← Modular UI components (Navbar, Footer, Hero, Modals, Cards)
├── content/        ← Localized copy, defaults, and dictionary strings
├── hooks/          ← Custom React hooks for API data fetching and state
├── layouts/        ← Root layout, direction-aware containers, and navigation shells
├── lib/            ← API client (Axios), i18n configuration, and utility functions
├── pages/          ← Public pages (Home, About, Services, Projects, Pricing, Contact, Blog) & Admin Dashboard
├── routes/         ← React Router v7 route definitions and protected route guards
├── types/          ← TypeScript strict interfaces for data models and API payloads
├── App.tsx         ← Application root with theme and language providers
├── index.css       ← Tailwind CSS v4 theme variables and global resets
└── main.tsx        ← Vite entry point
```

---

## ⚡ 2. Backend & REST API Architecture (`backend/cms-api`)

The backend engine is engineered with **zero framework bloat**, using PHP Flight for maximum execution speed and minimal memory footprint:

### Key Architectural Layers:
1. **PHP Flight Router**: Lightweight request dispatching, middleware pipeline, and JSON response formatting.
2. **SQLite 3 with Write-Ahead Logging (WAL)**:
   - PRAGMA `journal_mode = WAL` enables concurrent reads during writes without table locks.
   - PRAGMA `synchronous = NORMAL` balances data safety with exceptional write throughput.
   - Zero database daemon maintenance (no MySQL/PostgreSQL memory overhead on shared hosting).
3. **JSON-First Document Store**:
   - `site.json` and database JSON columns store complex nested page content.
   - Self-healing schema migrations automatically check and initialize missing tables on boot.
4. **Unified Media Manager**:
   - Handles file uploads to `uploads/` directory.
   - Built-in SVG sanitizer strips dangerous scripts (`<script>`, `onload`, `onerror`) to prevent stored XSS vulnerabilities.
   - Image resizing and WebP optimization support.

---

## 📚 3. REST API Endpoints Specification

TidyFactor-Go exposes 15 REST endpoints covering authentication, content CRUD, media, and diagnostics:

| HTTP Method | Endpoint | Description | Auth Required |
| :--- | :--- | :--- | :---: |
| `POST` | `/api/auth/login` | Authenticate admin user with Bcrypt verification | No |
| `POST` | `/api/auth/logout` | Invalidate active session token | Yes |
| `GET` | `/api/auth/check` | Verify current session authentication status | Yes |
| `GET` | `/api/site` | Retrieve entire site JSON document (public cacheable) | No |
| `POST` | `/api/site` | Update site JSON document and trigger schema sync | Yes |
| `GET` | `/api/pages` | List all dynamic content pages and metadata | No |
| `GET` | `/api/pages/:id` | Fetch specific page content by ID or slug | No |
| `POST` | `/api/pages` | Create a new content page | Yes |
| `PUT` | `/api/pages/:id` | Update existing page content and sections | Yes |
| `DELETE` | `/api/pages/:id` | Delete a content page | Yes |
| `GET` | `/api/publications` | List blog posts, articles, and announcements | No |
| `POST` | `/api/publications` | Create new publication | Yes |
| `POST` | `/api/media/upload` | Upload and sanitize image/asset (PNG, JPG, SVG, WebP) | Yes |
| `GET` | `/api/backup/export` | Export unified JSON backup payload | Yes |
| `POST` | `/api/backup/import` | Restore site from JSON backup file | Yes |

---

## 🔒 4. Security & Hardening Protocols

1. **Authentication Security**:
   - Passwords hashed using `password_hash()` with `PASSWORD_BCRYPT` (cost factor: 12).
   - In-memory rate limiting locks out IP addresses after 5 consecutive failed login attempts (15-minute cooldown).
2. **SQL Injection Immunity**:
   - 100% of database queries execute through PDO prepared statements with strict parameter binding.
3. **Cross-Site Scripting (XSS) Defense**:
   - Strict SVG XML DOM parsing cleans malicious attributes before file storage.
   - Markdown rendering safely escapes raw HTML.
4. **HTTP Security Headers**:
   - `.htaccess` enforces `X-Frame-Options: SAMEORIGIN`, `X-Content-Type-Options: nosniff`, and `Referrer-Policy: strict-origin-when-cross-origin`.

---

## 🚀 5. Development & Deployment Lifecycle

### Local Development:
```bash
# 1. Start Backend API (Terminal 1)
cd backend/cms-api
php -S localhost:8000 -t public

# 2. Start Frontend Dev Server (Terminal 2)
npm install
npm run dev
# App running at http://localhost:3000
```

### Production Build & Packaging:
```bash
# Type check and build frontend assets
npm run build

# Package standalone production release archive
npm run release
# Output: dist-release/TidyFactor-Go-v1.6.1.zip
```

### Deploying to cPanel / Shared Hosting:
1. Upload the contents of `dist-release/` (or the built `dist/` + `backend/` + `.htaccess`) to `public_html/`.
2. Ensure `storage/` and `uploads/` directories have write permissions (`0755` or `0775`).
3. Visit `https://yourdomain.com` — the automated installation wizard (`install/`) will guide you through setting up the initial admin password.
