# 📐 Headless E-Commerce Architecture Diagram

## System Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                    NEXT.JS FRONTEND                             │
│              (http://localhost:3000)                            │
│                                                                 │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │  React Components (Pages, Products, Cart, Checkout)     │  │
│  └─────────────────────┬──────────────────────────────────┘  │
│                        │                                       │
│                        │ API Requests (Fetch/Axios)           │
│                        │ CORS enabled                          │
└────────────────────────┼───────────────────────────────────────┘
                         │
                         │ HTTP/JSON
                         │
┌────────────────────────▼───────────────────────────────────────┐
│              LARAVEL 11 BACKEND                                │
│           (http://localhost:8000)                              │
│                                                                │
│  ┌────────────────────────────────────────────────────────┐   │
│  │           API ROUTES (routes/api.php)                 │   │
│  │                                                         │   │
│  │  GET    /api/products              ProductController  │   │
│  │  GET    /api/products/{slug}       ProductController  │   │
│  │  POST   /api/orders                OrderController    │   │
│  │  GET    /api/orders                OrderController    │   │
│  │  GET    /api/orders/{id}           OrderController    │   │
│  └─────────────┬──────────────────────────────────────────┘   │
│                │                                               │
│  ┌─────────────▼──────────────────────────────────────────┐   │
│  │              CONTROLLERS                               │   │
│  │                                                         │   │
│  │  ┌──────────────────────────────────────────────┐     │   │
│  │  │ Api/ProductController                       │     │   │
│  │  │ ├─ index()    → GET all products           │     │   │
│  │  │ └─ show()     → GET product by slug        │     │   │
│  │  └──────────────────────────────────────────────┘     │   │
│  │                                                         │   │
│  │  ┌──────────────────────────────────────────────┐     │   │
│  │  │ Api/OrderController                         │     │   │
│  │  │ ├─ index()    → GET all orders              │     │   │
│  │  │ ├─ store()    → CREATE new order            │     │   │
│  │  │ └─ show()     → GET order by id             │     │   │
│  │  └──────────────────────────────────────────────┘     │   │
│  └─────────────┬──────────────────────────────────────────┘   │
│                │                                               │
│  ┌─────────────▼──────────────────────────────────────────┐   │
│  │              MODELS & BUSINESS LOGIC                   │   │
│  │                                                         │   │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐ │   │
│  │  │  Product     │  │   Order      │  │  OrderItem   │ │   │
│  │  │              │  │              │  │              │ │   │
│  │  │ • name       │  │ • customer_  │  │ • quantity   │ │   │
│  │  │ • slug       │  │   email      │  │ • price      │ │   │
│  │  │ • price      │  │ • total_     │  │              │ │   │
│  │  │ • stock      │  │   price      │  │ Relationships│ │   │
│  │  │ • category   │  │ • status     │  │ • order()    │ │   │
│  │  │              │  │              │  │ • product()  │ │   │
│  │  └──────────────┘  └──────────────┘  └──────────────┘ │   │
│  │        │                   ▲                 ▲           │   │
│  │        │                   │                 │           │   │
│  │        └───────────────────┴─────────────────┘           │   │
│  │              Relationships & Queries                      │   │
│  └─────────────┬──────────────────────────────────────────┘   │
│                │                                               │
│  ┌─────────────▼──────────────────────────────────────────┐   │
│  │              DATABASE (MySQL)                          │   │
│  │                                                         │   │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐ │   │
│  │  │  products    │  │   orders     │  │order_items   │ │   │
│  │  │              │  │              │  │              │ │   │
│  │  │ id (PK)      │  │ id (PK)      │  │ id (PK)      │ │   │
│  │  │ name         │  │ customer_    │  │ order_id(FK) │ │   │
│  │  │ slug (UNIQUE)│  │   email      │  │ product_id   │ │   │
│  │  │ description  │  │ total_price  │  │   (FK)       │ │   │
│  │  │ price        │  │ status       │  │ quantity     │ │   │
│  │  │ stock        │  │ timestamps   │  │ price        │ │   │
│  │  │ category     │  │              │  │ timestamps   │ │   │
│  │  │ timestamps   │  │              │  │              │ │   │
│  │  └──────────────┘  └──────────────┘  └──────────────┘ │   │
│  │                                                         │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                │
│  ┌────────────────────────────────────────────────────────┐   │
│  │         CORS & CONFIGURATION                          │   │
│  │  • Origins: http://localhost:3000                     │   │
│  │  • Methods: GET, POST, PUT, DELETE, OPTIONS           │   │
│  │  • Credentials: Enabled                               │   │
│  │  • Paths: /api/*, /sanctum/csrf-cookie               │   │
│  └────────────────────────────────────────────────────────┘   │
│                                                                │
└────────────────────────────────────────────────────────────────┘
```

---

## Data Flow Diagram

### Flow 1: Get All Products
```
Frontend                        Backend
   │                              │
   ├──→ GET /api/products        │
   │                              ├─→ ProductController@index()
   │                              ├─→ Product::all()
   │                              ├─→ Format response with image URLs
   │                          ┌───┤
   │ ←──────────────────────────┘
   │   {status, data: [...]}
   │
   Render product list
```

### Flow 2: Get Product by Slug
```
Frontend                        Backend
   │                              │
   ├─→ GET /api/products/slug     │
   │                              ├─→ ProductController@show()
   │                              ├─→ Product::where('slug', ...)->firstOrFail()
   │                              ├─→ Return single product
   │                          ┌───┤
   │ ←──────────────────────────┘
   │   {status, data: {...}}
   │
   Render product detail page
```

### Flow 3: Create Order (with Validation & Stock Management)
```
Frontend                        Backend
   │                              │
   ├─→ POST /api/orders           │
   │   {customer_email, items}    │
   │                              ├─→ OrderController@store()
   │                              ├─→ Validate input (422 if invalid)
   │                              ├─→ Start transaction
   │                              │
   │                              ├─→ For each item:
   │                              │   ├─→ Get product from DB
   │                              │   ├─→ Check stock available?
   │                              │   │   └─→ No? Rollback (400)
   │                              │   ├─→ Calculate server-side price
   │                              │   └─→ Decrement stock
   │                              │
   │                              ├─→ Create Order record
   │                              ├─→ Create OrderItem records
   │                              ├─→ Commit transaction
   │                          ┌───┤
   │ ←──────────────────────────┘
   │   {status, message, data}
   │
   Redirect to success page
```

### Flow 4: Get Orders
```
Frontend                        Backend
   │                              │
   ├─→ GET /api/orders            │
   │                              ├─→ OrderController@index()
   │                              ├─→ Order::with('items.product')->get()
   │                              ├─→ Return all orders
   │                          ┌───┤
   │ ←──────────────────────────┘
   │   {status, data: [...]}
   │
   Render orders list/dashboard
```

---

## Database Relationships

```
                     ┌─────────────────┐
                     │    PRODUCTS     │
                     ├─────────────────┤
                     │ id (PK)         │◄─────┐
                     │ name            │      │
                     │ slug            │      │ 1
                     │ price           │      │
                     │ stock           │      │
                     │ category        │      │
                     └─────────────────┘      │
                                              │
                                         Has Many
                                              │
                     ┌─────────────────┐      │
                     │  ORDER_ITEMS    │      │
                     ├─────────────────┤      │
                     │ id (PK)         │      │
                     │ order_id (FK)───┼─────┐│
                     │ product_id (FK)─┼─────┘│
                     │ quantity        │      │
                     │ price           │      │
                     └─────────────────┘      │
                            ▲                 │
                            │ Has Many        │
                            │                 │
                     ┌──────┴──────┐          │
                     │   ORDERS    │          │
                     ├─────────────┤          │
                     │ id (PK)     │          │
                     │ customer_   │          │
                     │  email      │          │
                     │ total_price │          │
                     │ status      │          │
                     └─────────────┘          │
                                              │
                    (Foreign Key Constraints)
                    Product.id → OrderItem.product_id
                    Order.id → OrderItem.order_id
                    CASCADE DELETE enabled
```

---

## Request-Response Examples

### Example 1: List Products
```
REQUEST:
────────
GET /api/products HTTP/1.1
Host: localhost:8000
Accept: application/json

RESPONSE:
─────────
HTTP/1.1 200 OK
Content-Type: application/json

{
  "status": "success",
  "data": [
    {
      "id": 1,
      "name": "Brazilian Blue Topaz",
      "slug": "brazilian-blue-topaz",
      "description": "Beautiful blue topaz from Brazil",
      "price": 199.99,
      "stock": 10,
      "category": "Gemstone",
      "image_url": "http://localhost:8000/storage/...",
      "created_at": "2025-12-11T10:30:00Z",
      "updated_at": "2025-12-11T10:30:00Z"
    }
  ]
}
```

### Example 2: Create Order
```
REQUEST:
────────
POST /api/orders HTTP/1.1
Host: localhost:8000
Content-Type: application/json

{
  "customer_email": "john@example.com",
  "items": [
    {
      "product_id": 1,
      "quantity": 2
    }
  ]
}

RESPONSE (Success):
───────────────────
HTTP/1.1 201 Created
Content-Type: application/json

{
  "status": "success",
  "message": "Order created successfully",
  "data": {
    "order_id": 5,
    "customer_email": "john@example.com",
    "total_price": 399.98,
    "status": "pending",
    "created_at": "2025-12-11T10:35:00Z"
  }
}

RESPONSE (Validation Error):
────────────────────────────
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
  "status": "error",
  "message": "Validation failed",
  "errors": {
    "customer_email": ["The customer email field is required."],
    "items": ["The items field is required."]
  }
}

RESPONSE (Stock Error):
──────────────────────
HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "status": "error",
  "message": "Insufficient stock for product: Brazilian Blue Topaz"
}
```

---

## Technology Stack

```
┌─────────────────────────────────────────────┐
│           TECHNOLOGY STACK                  │
├─────────────────────────────────────────────┤
│ Frontend:                                   │
│  • Next.js 13+                              │
│  • React                                    │
│  • TypeScript (optional)                    │
│                                             │
│ Backend:                                    │
│  • Laravel 11                               │
│  • PHP 8.2+                                 │
│  • MySQL 8.0+                               │
│                                             │
│ API:                                        │
│  • REST API                                 │
│  • JSON responses                           │
│  • CORS enabled                             │
│                                             │
│ Database:                                   │
│  • MySQL                                    │
│  • Eloquent ORM                             │
│  • Database transactions                    │
│                                             │
│ Deployment:                                 │
│  • XAMPP (Local Dev)                        │
│  • Apache (Recommended)                     │
│  • PHP-FPM (Production)                     │
└─────────────────────────────────────────────┘
```

---

## Security Layers

```
┌────────────────────────────────────────────────┐
│         SECURITY FEATURES                      │
├────────────────────────────────────────────────┤
│                                                │
│ 1. CORS CONFIGURATION                         │
│    └─ Only http://localhost:3000 allowed      │
│                                                │
│ 2. INPUT VALIDATION                           │
│    ├─ Email format validation                 │
│    ├─ Product existence validation            │
│    ├─ Quantity minimum validation             │
│    └─ Detailed error responses                │
│                                                │
│ 3. SERVER-SIDE PRICE CALCULATION              │
│    └─ Never trusts client pricing             │
│                                                │
│ 4. STOCK VALIDATION                           │
│    ├─ Checks availability before order        │
│    └─ Prevents overselling                    │
│                                                │
│ 5. DATABASE TRANSACTIONS                      │
│    ├─ Atomic operations                       │
│    ├─ Automatic rollback on error             │
│    └─ Data consistency guaranteed             │
│                                                │
│ 6. FOREIGN KEY CONSTRAINTS                    │
│    ├─ Referential integrity                   │
│    ├─ Cascade delete enabled                  │
│    └─ Orphaned records prevented              │
│                                                │
│ 7. SANCTUM READY                              │
│    ├─ CSRF protection configured              │
│    └─ Can add token-based auth                │
│                                                │
└────────────────────────────────────────────────┘
```

---

## Performance Optimizations

```
┌────────────────────────────────────────────────┐
│    PERFORMANCE CONSIDERATIONS                  │
├────────────────────────────────────────────────┤
│                                                │
│ 1. EAGER LOADING                              │
│    └─ Order->items->product prevents N+1      │
│                                                │
│ 2. PROPER INDEXING                            │
│    ├─ slug (UNIQUE) on products               │
│    └─ Foreign keys indexed automatically      │
│                                                │
│ 3. TYPE CASTING                               │
│    ├─ Ensures proper data types               │
│    └─ Reduces conversion overhead             │
│                                                │
│ 4. QUERY OPTIMIZATION                         │
│    ├─ Selective field retrieval possible      │
│    └─ Pagination can be added                 │
│                                                │
│ 5. CACHING POTENTIAL                          │
│    ├─ Product lists can be cached             │
│    ├─ Redis integration possible              │
│    └─ Asset caching for images                │
│                                                │
└────────────────────────────────────────────────┘
```

---

## Future Enhancement Points

```
Current Implementation:           Can Be Extended With:
──────────────────────────────    ──────────────────────
✅ Product retrieval              → Admin product management
✅ Basic order creation            → Payment gateway integration
✅ Stock management               → Inventory management dashboard
✅ CORS configured               → User authentication (Sanctum)
✅ Error handling                → Email notifications
✅ Database transactions         → Order status tracking
                                  → Customer accounts
                                  → Product ratings & reviews
                                  → Wishlist functionality
                                  → Advanced search & filtering
                                  → Analytics & reporting
```

---

This architecture provides a solid foundation for a modern e-commerce system with clear separation between frontend and backend!
