# GlobalShop REST API Documentation (Phase 2 Core Core)

GlobalShop is a highly gamified e-commerce API platform inspired by modern marketplaces like Temu & AliExpress. It features dual currencies (Fiat & Coins), referrals, daily missions, achievements, free gifts, lucky wheel, and mystery box rewards.

---

## 1. General Architecture & Specifications

- **Endpoint URL**: `https://<your-host>/backend/api`
- **Output Format**: Standard JSON `application/json; charset=UTF-8`
- **Architecture**: MVC (Model-View-Controller) utilizing native PDO and custom PSR-4 Class Autoloader.
- **Authentication**: Stateless JWT via HTTP Authorization Header (`Authorization: Bearer <JWT_TOKEN>`).
- **Security Protocols**:
  - 100% SQL Injection Protection via PDO Prepared Statements.
  - IP-based Sliding-Window Rate Limiting (60 requests/min, custom headers returned).
  - Production-grade security headers (`X-Content-Type-Options`, `X-Frame-Options`, `X-XSS-Protection`, `Content-Security-Policy`).
  - Image optimization engine converts uploads (e.g., user avatars) into WebP format with secure MIME-type checkers and produces downscaled thumbnail variants.

---

## 2. Global Headers & Responses

### Request Headers
```http
Content-Type: application/json
Authorization: Bearer <your_jwt_token_here>
```

### Response Headers (Rate Limiting)
All endpoints return standard rate-limiting headers:
```http
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
X-RateLimit-Reset: 1772545890
```

### Standard Response Structure
```json
{
  "success": true,
  "status": 200,
  "message": "Success",
  "timestamp": 1772545821,
  "data": {}
}
```

---

## 3. API Reference Endpoints

### 3.1 Authentication & Registration

#### POST `/auth/register`
Creates a user account, generates their personal referral code, and ties their account to their referrer if a valid code is supplied.

- **Request Body**:
```json
{
  "email": "user@example.com",
  "password": "securepassword123",
  "first_name": "John",
  "last_name": "Doe",
  "referral_code": "GS8872FA"  // Optional referral code
}
```
- **Success Response (201 Created)**:
```json
{
  "success": true,
  "status": 201,
  "message": "Registration successful.",
  "data": {
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "user": {
      "id": 4,
      "email": "user@example.com",
      "first_name": "John",
      "last_name": "Doe",
      "referral_code": "GSXYZ99",
      "coin_balance": 0,
      "level": "Bronze"
    }
  }
}
```

#### POST `/auth/login`
Authenticates a user and issues a stateless JWT access token.

- **Request Body**:
```json
{
  "email": "user@example.com",
  "password": "securepassword123"
}
```
- **Success Response (200 OK)**:
```json
{
  "success": true,
  "status": 200,
  "message": "Login successful.",
  "data": {
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "user": {
      "id": 4,
      "email": "user@example.com",
      "first_name": "John",
      "last_name": "Doe",
      "avatar": "uploads/avatars/avatar_64a123.webp",
      "referral_code": "GSXYZ99",
      "coin_balance": 150,
      "exp_points": 25,
      "level": "Bronze"
    }
  }
}
```

---

### 3.2 Product & Categories Catalog

#### GET `/products`
Fetches a list of catalog products. Supports multiple filtering parameters.

- **Query Parameters**:
  - `category` (int): Filter by category ID.
  - `search` (string): Text search across SKU, names, and descriptions.
  - `is_flash_sale` (0 or 1): Flash sale items.
  - `is_coin_product` (0 or 1): Items redeemable via coin balances.
  - `is_gift_product` (0 or 1): Free gift campaign rewards.
  - `sort` (string): Sort values (`price_asc`, `price_desc`, `name_asc`, `name_desc`, `id_desc`).
  
- **Success Response (200 OK)**:
```json
{
  "success": true,
  "status": 200,
  "message": "Products list retrieved successfully.",
  "data": [
    {
      "id": 1,
      "sku": "GS-PH-11",
      "name": "Smart Ultra Watch",
      "slug": "smart-ultra-watch",
      "price": "49.99",
      "discount_percentage": 10,
      "stock": 100,
      "image_url": "uploads/products/watch.webp",
      "is_flash_sale": 0,
      "is_coin_product": 0
    }
  ]
}
```

#### GET `/products/{id}`
Returns granular product specifications, available color/size variants, multi-image gallery assets, customer reviews, and recommended up-sell products.

- **Success Response (200 OK)**:
```json
{
  "success": true,
  "status": 200,
  "message": "Product details retrieved successfully.",
  "data": {
    "id": 1,
    "name": "Smart Ultra Watch",
    "price": "49.99",
    "stock": 100,
    "images": [
      "uploads/products/watch_side.webp",
      "uploads/products/watch_back.webp"
    ],
    "variants": [
      { "id": 1, "name": "Color", "value": "Alpine Black", "price_adjustment": "0.00", "stock": 50 },
      { "id": 2, "name": "Color", "value": "Ocean Orange", "price_adjustment": "5.00", "stock": 50 }
    ],
    "specifications": [
      { "name": "Waterproof", "value": "IP68 Rating" }
    ],
    "reviews": [
      { "id": 1, "rating": 5, "comment": "Excellent tracker", "first_name": "Mert" }
    ],
    "upsell_products": [
      { "id": 5, "name": "Watch Charging Cradle", "price": "9.99", "image_url": "uploads/prod/cradle.webp" }
    ]
  }
}
```

#### GET `/categories`
Lists all category nodes, parent classifications, hierarchy ordering, and vector visual asset files.

---

### 3.3 Shopping Cart & Wishlist (Requires Authentication)

#### GET `/cart`
Returns active cart items with dynamic variant pricing adjustments, limits, and order totals.

#### POST `/cart`
Adds an item with selected variant parameters. Checks live inventory stock availability.
- **Request Body**:
```json
{
  "product_id": 1,
  "variant_id": 2, // Optional
  "quantity": 2
}
```

#### PUT `/cart/{id}`
Updates cart item quantity. Validates requested quantity against product warehouse stocks.
- **Request Body**:
```json
{ "quantity": 5 }
```

#### DELETE `/cart/{id}`
Removes an item from the user's cart.

#### GET `/wishlist`
Lists user's wishlisted items.

#### POST `/wishlist`
Toggles a product's presence in the user's wishlist (adds if absent, removes if present).
- **Request Body**:
```json
{ "product_id": 12 }
```

---

### 3.4 User Profile, Addresses & Upload System (Requires Authentication)

#### GET `/user/profile`
Returns current account summary, coin balances, level status (Bronze, Silver, Gold, etc.), experience points, and referral metrics.

#### PUT `/user/profile`
Updates profile metadata.
- **Request Body**:
```json
{
  "first_name": "Arthur",
  "last_name": "Dent"
}
```

#### POST `/user/avatar`
Uploads a user avatar. Expects a `multipart/form-data` payload containing an image under the key `avatar`.
- **System Action**: Formats image to a compressed `.webp` format and creates a `.webp` avatar thumbnail in a sub-folder automatically.

#### GET `/user/addresses`
Lists saved user shipping addresses.

#### POST `/user/addresses`
Adds an address. Setting `is_default: true` clears the default status from other saved addresses.
- **Request Body**:
```json
{
  "title": "Home Address",
  "full_name": "Arthur Dent",
  "phone": "+15550199",
  "address_line_1": "15 Country Lane",
  "address_line_2": "Apt B",
  "city": "Cottington",
  "state": "Wessex",
  "country": "United Kingdom",
  "zip_code": "C1209",
  "is_default": true
}
```

---

### 3.5 Checkouts, Coupon Codes, and Orders

#### POST `/orders`
Initiates a transaction. Fetches cart items, processes optional discount coupons, calculates minimum free-shipping limits, decreases product inventories, and clears the cart.
- **Request Body**:
```json
{
  "address_id": 3,
  "payment_method": "CreditCard",
  "coupon_code": "SAVE20", // Optional
  "notes": "Leave at front door" // Optional
}
```
- **Campaign Trigger**: If this checkout is the user's **first transaction**, their referrer will automatically be marked as "Completed" in the referrals engine, and they will receive referral campaign coins (defined in settings, e.g., 250 coins).

#### POST `/coupons/apply`
Validates coupon expiration, minimum spend constraints, and discount values.

---

### 3.6 Gamification & Coin Campaigns (Requires Authentication)

#### GET `/referrals`
Provides a referral campaign dashboard summary showing active guidelines, invited user accounts, status, and claimable invitation rewards.

#### GET `/coins/wallet`
Provides coin transaction history ledgers (earnings and redemptions).

#### POST `/coins/daily-login`
Claims the daily login bonus coin reward (e.g., 10 coins + 5 EXP). Limit: One claim per calendar day. Completes daily login progression missions.

#### POST `/coins/spin`
Spins the lucky wheel. Costs 20 coins.
- **Reward Selector**: Runs a mathematically-weighted selector using defined row probabilities.
- **Potential Drops**: Fixed coin increments (10, 50, 100, 500 coins), fixed value discount coupons ($5, $10, etc.), or free shipping coupons.

#### POST `/coins/mystery-box`
Deducts 50 coins to open a randomized mystery prize box with unique drops (percentage coupons, heavy-discount tickets).

#### GET `/gifts/campaigns`
Lists active Free Gift campaigns (e.g., "Collect 500 Coins for a free jacket", "Invite 3 Friends for a free smart watch").

#### POST `/gifts/claim`
Claims a free gift by submitting a campaign ID and shipping address. The system validates whether user achievements/referral counts meet the required campaign conditions before saving the claim as "Pending".
