# Headless E-Commerce Backend - Implementation Complete

## 📋 Summary

A fully functional headless e-commerce backend has been implemented in Laravel following REST API best practices, designed to work seamlessly with your Next.js frontend.

---

## 🗄️ DATABASE SCHEMA

### Products Table
```sql
CREATE TABLE products (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL,
  slug VARCHAR(255) UNIQUE NOT NULL,
  description TEXT NOT NULL,
  price DECIMAL(10, 2) NOT NULL,
  stock INT DEFAULT 0,
  image_path VARCHAR(255) NULL,
  category VARCHAR(255) NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
```

### Orders Table
```sql
CREATE TABLE orders (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  customer_email VARCHAR(255) NOT NULL,
  total_price DECIMAL(10, 2) NOT NULL,
  status VARCHAR(255) DEFAULT 'pending',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
```

### OrderItems Table
```sql
CREATE TABLE order_items (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  order_id BIGINT NOT NULL,
  product_id BIGINT NOT NULL,
  quantity INT NOT NULL,
  price DECIMAL(10, 2) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
  FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
);
```

---

## 🧠 DATA MODELS

### Product Model (`app/Models/Product.php`)
- **Fillable Fields**: name, slug, description, price, stock, image_path, category
- **Casts**: price (decimal:2), stock (integer)
- **Relationships**: 
  - `hasMany(OrderItem)` - One product can appear in many order items
- **Methods**: None custom (uses standard Eloquent methods)

### Order Model (`app/Models/Order.php`)
- **Fillable Fields**: customer_email, total_price, status
- **Casts**: total_price (decimal:2)
- **Relationships**:
  - `hasMany(OrderItem)` as `items()` - One order contains many order items
- **Default Status**: 'pending'

### OrderItem Model (`app/Models/OrderItem.php`)
- **Fillable Fields**: order_id, product_id, quantity, price
- **Casts**: quantity (integer), price (decimal:2)
- **Relationships**:
  - `belongsTo(Order)` - Each item belongs to an order
  - `belongsTo(Product)` - Each item references a product

---

## 🔌 API ENDPOINTS

### 1. **GET /api/products**
**Description**: Retrieve all products

**Response (200 OK)**:
```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/path/to/image.jpg",
      "created_at": "2025-12-11T10:30:00Z",
      "updated_at": "2025-12-11T10:30:00Z"
    }
  ]
}
```

**Error (500 Internal Server Error)**:
```json
{
  "status": "error",
  "message": "Failed to fetch products"
}
```

---

### 2. **GET /api/products/{slug}**
**Description**: Retrieve a single product by slug

**Parameters**:
- `slug` (string, path) - Product slug (e.g., "brazilian-blue-topaz")

**Response (200 OK)**:
```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/path/to/image.jpg",
    "created_at": "2025-12-11T10:30:00Z",
    "updated_at": "2025-12-11T10:30:00Z"
  }
}
```

**Error (404 Not Found)**:
```json
{
  "status": "error",
  "message": "Product not found"
}
```

**Error (500 Internal Server Error)**:
```json
{
  "status": "error",
  "message": "Failed to fetch product"
}
```

---

### 3. **POST /api/orders**
**Description**: Create a new order with validation, server-side price calculation, and stock reduction

**Request Body**:
```json
{
  "customer_email": "customer@example.com",
  "items": [
    {
      "product_id": 1,
      "quantity": 2
    },
    {
      "product_id": 2,
      "quantity": 1
    }
  ]
}
```

**Validation Rules**:
- `customer_email`: required, valid email format
- `items`: required, must be array with minimum 1 item
- `items.*.product_id`: required, integer, must exist in products table
- `items.*.quantity`: required, integer, minimum 1

**Response (201 Created)**:
```json
{
  "status": "success",
  "message": "Order created successfully",
  "data": {
    "order_id": 5,
    "customer_email": "customer@example.com",
    "total_price": 699.97,
    "status": "pending",
    "created_at": "2025-12-11T10:35:00Z"
  }
}
```

**Error (422 Unprocessable Entity - Validation Failed)**:
```json
{
  "status": "error",
  "message": "Validation failed",
  "errors": {
    "customer_email": ["The customer email field is required."],
    "items": ["The items field is required."]
  }
}
```

**Error (400 Bad Request - Stock Insufficient)**:
```json
{
  "status": "error",
  "message": "Insufficient stock for product: Brazilian Blue Topaz"
}
```

**Error (500 Internal Server Error)**:
```json
{
  "status": "error",
  "message": "An unexpected error occurred"
}
```

---

### 4. **GET /api/orders**
**Description**: Retrieve all orders (for admin dashboard)

**Response (200 OK)**:
```json
{
  "status": "success",
  "data": [
    {
      "id": 1,
      "customer_email": "customer@example.com",
      "total_price": 699.97,
      "status": "pending",
      "items": [
        {
          "id": 1,
          "order_id": 1,
          "product_id": 1,
          "quantity": 2,
          "price": 199.99,
          "product": { ... }
        }
      ],
      "created_at": "2025-12-11T10:35:00Z",
      "updated_at": "2025-12-11T10:35:00Z"
    }
  ]
}
```

---

### 5. **GET /api/orders/{id}**
**Description**: Retrieve a specific order with line items

**Parameters**:
- `id` (integer, path) - Order ID

**Response (200 OK)**:
```json
{
  "status": "success",
  "data": {
    "id": 1,
    "customer_email": "customer@example.com",
    "total_price": 699.97,
    "status": "pending",
    "items": [
      {
        "id": 1,
        "order_id": 1,
        "product_id": 1,
        "quantity": 2,
        "price": 199.99,
        "product": { ... }
      }
    ],
    "created_at": "2025-12-11T10:35:00Z",
    "updated_at": "2025-12-11T10:35:00Z"
  }
}
```

**Error (404 Not Found)**:
```json
{
  "status": "error",
  "message": "Order not found"
}
```

---

## 🔐 CORS Configuration

**File**: `config/cors.php`

```php
return [
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => [
        'http://localhost:3000',      // Next.js dev server
        'http://127.0.0.1:3000',
    ],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,  // Important for cookies/tokens
];
```

**Key Settings**:
- ✅ Allows requests from Next.js running on `localhost:3000`
- ✅ Supports credentials (important for authentication)
- ✅ Allows all HTTP methods and headers
- ✅ CSRF cookie endpoint configured

---

## 📂 File Locations

```
app/
  └── Http/
      └── Controllers/
          └── Api/
              ├── ProductController.php    [GET /api/products, GET /api/products/{slug}]
              └── OrderController.php      [POST /api/orders, GET /api/orders, GET /api/orders/{id}]

app/
  └── Models/
      ├── Product.php                    [with relationships]
      ├── Order.php                      [with relationships]
      └── OrderItem.php                  [with relationships]

database/
  └── migrations/
      ├── 2025_12_11_082827_create_products_table.php
      ├── 2025_12_11_082902_create_orders_table.php
      └── 2025_12_11_082903_create_order_items_table.php

config/
  └── cors.php                           [CORS configuration]

routes/
  └── api.php                            [API routes]
```

---

## 🚀 Key Features Implemented

### Product Controller
✅ **GET /api/products** - Returns all products with absolute image URLs
✅ **GET /api/products/{slug}** - Find product by slug with 404 handling
✅ **Formatted Response** - Consistent JSON structure with all product details
✅ **Image URL Generation** - Uses `asset()` helper for full absolute URLs

### Order Controller
✅ **Server-Side Price Calculation** - Never trusts client-side pricing
✅ **Stock Validation** - Checks availability before creating order
✅ **Stock Reduction** - Automatically decrements stock on successful order
✅ **Database Transactions** - Ensures data consistency with rollback on error
✅ **Input Validation** - Comprehensive validation of email and order items
✅ **Relationship Loading** - Eager loads items and products for efficiency
✅ **Error Handling** - Detailed error messages for validation and business logic failures

### Models & Relationships
✅ **Eloquent ORM** - Full model setup with relationships
✅ **Type Casting** - Proper decimal and integer casting
✅ **Fillable Attributes** - Mass assignment security configured
✅ **Foreign Keys** - Cascade delete configured for data integrity

### API Configuration
✅ **CORS Setup** - Configured for Next.js frontend
✅ **Sanctum Ready** - Can be extended with authentication
✅ **JSON Responses** - All endpoints return JSON (no views)
✅ **HTTP Status Codes** - Proper codes: 200, 201, 400, 404, 422, 500

---

## 🔐 Cookie-Based Authentication

The API uses Laravel Sanctum's stateful session authentication:

- `POST /api/register` accepts `name`, `email`, `password`, and `password_confirmation`; new accounts receive the `user` role.
- `POST /api/login` accepts `email` and `password`.
- `GET /api/user` returns the authenticated user; `POST /api/logout` ends the session.
- Validation failures return HTTP `422`; protected routes return HTTP `401` when signed out.

Before login or registration, call `GET /sanctum/csrf-cookie`. Configure the frontend HTTP client to send credentials and the XSRF token (Axios: `withCredentials: true` and `withXSRFToken: true`). Set `SANCTUM_STATEFUL_DOMAINS` to the frontend hostnames (including ports in development), allow those exact origins in CORS, and set `SESSION_DOMAIN` to the shared parent domain when frontend and API are on separate subdomains. Use HTTPS for production cookie sessions.

For this project, CORS allows `http://localhost:8080`, `https://e4emerald.com`, `https://www.e4emerald.com`, and `https://admin.e4emerald.com`, and the sample Sanctum stateful list includes their hostnames. Keep `SESSION_DOMAIN=null` for local development. On the live server, set `SESSION_DOMAIN=.e4emerald.com` and `SESSION_SECURE_COOKIE=true`, then run `php artisan optimize:clear`. A localhost frontend calling the live API is a cross-site cookie flow and can be blocked by browser third-party-cookie restrictions; use the local API or a same-origin development proxy for reliable local cookie authentication.

The admin sidebar's **My Account** link opens `/account` and displays the signed-in user's details.

## Password reset API

- `POST /api/forgot-password` with `{ "email": "user@example.com" }` sends a reset email when the account exists. The response message is intentionally generic so the endpoint does not reveal registered addresses.
- `POST /api/reset-password` with `{ "token": "...", "email": "user@example.com", "password": "...", "password_confirmation": "..." }` resets the password. Tokens expire after 60 minutes and are single-use.

Reset emails link to `FRONTEND_URL/reset-password?token=...&email=...`; the React page should read those query parameters and submit them to the reset endpoint. `FRONTEND_URL` must be set to the actual frontend origin. Production `.env` must use the exact Laravel mail variable names: `MAIL_MAILER=smtp`, `MAIL_HOST`, `MAIL_PORT`, `MAIL_USERNAME`, `MAIL_PASSWORD`, `MAIL_ENCRYPTION`, `MAIL_FROM_ADDRESS`, and `MAIL_FROM_NAME`. Set the sender to an address verified by your mail provider. `MAIL_MAILER=log` only writes messages to `storage/logs/laravel.log`; it does not send email. The API deliberately returns a generic success for unknown addresses, returns `429` when the reset broker throttles a repeat request, and surfaces mail transport failures as server errors rather than claiming delivery.

These two endpoints are exempt from CSRF validation because they are public password-reset flows; reset completion still requires a valid, expiring, single-use token, and both endpoints are rate-limited. They do not require a Sanctum session or CSRF cookie. On success, show a confirmation and return the user to the login page; do not automatically authenticate them after a password reset. Login, registration, and other stateful authenticated API requests continue to use the normal Sanctum CSRF/session setup.

## Google and Apple social login

The web routes start OAuth and receive the provider callback:

- `GET https://admin.e4emerald.com/auth/social/google/redirect`
- `GET https://admin.e4emerald.com/auth/social/apple/redirect`
- Compatibility aliases for frontends using an `/api` base URL: `GET https://admin.e4emerald.com/api/auth/social/google/redirect` and `/api/auth/social/apple/redirect`. These start the same OAuth flow with web session middleware enabled.
- `GET|POST https://admin.e4emerald.com/auth/social/{provider}/callback`

Google returns by GET; Apple is configured for `form_post`, so its callback is a POST. The Apple callback route is narrowly exempted from Laravel's CSRF token check because the cross-site Apple form cannot send Laravel's token. Socialite still validates OAuth state/nonce. Do not remove state validation or mark the provider `stateless()`.

Configure these production values in the server's `.env` (never commit real secrets):

```env
APP_URL=https://admin.e4emerald.com
FRONTEND_URL=https://e4emerald.com
SESSION_DOMAIN=.e4emerald.com
SESSION_SECURE_COOKIE=true
SESSION_SAME_SITE=none

GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=...
GOOGLE_REDIRECT_URI=https://admin.e4emerald.com/auth/social/google/callback

APPLE_CLIENT_ID=...
APPLE_CLIENT_SECRET=...
APPLE_REDIRECT_URI=https://admin.e4emerald.com/auth/social/apple/callback
```

Keep the real `.env` private. Google credentials come from a Google Cloud OAuth 2.0 Web application client. Add the exact callback URL above as an authorized redirect URI and add `e4emerald.com` (and any `www` frontend origin you use) as an authorized JavaScript origin. Configure the OAuth consent screen and publish/authorize the app as required for your audience.

For Apple, enable **Sign in with Apple** for the App ID, create a Services ID, associate it with the primary website domain `e4emerald.com`, and register the exact return URL `https://admin.e4emerald.com/auth/social/apple/callback`. Use the Services ID as `APPLE_CLIENT_ID`. Create a Sign in with Apple key and generate a client-secret JWT using the Apple Team ID, Key ID, Services ID, and downloaded private key; put that JWT in `APPLE_CLIENT_SECRET`. Apple client-secret JWTs expire (maximum six months), so rotate it before expiry. Enable `form_post`/web authentication as required by the Apple configuration.

For local development, create separate OAuth credentials and use the exact local callback URLs, such as `http://localhost:8000/auth/social/google/callback` and `http://localhost:8000/auth/social/apple/callback`. Apple requires HTTPS for production web domains; local Apple testing may require an HTTPS tunnel and registering that exact URL.

The backend creates a `user` account when the verified provider email is new, or signs in the existing account matching that email. It redirects to the React route `/auth/social-callback?provider=google|apple`; failures use `?social_error=provider`, `missing-email`, or `unverified-email`. The callback page should query `GET /api/user` with cookies enabled to confirm the session, then route the signed-in user into the app. If that request returns `401`, display a sign-in error. A provider may not return a usable email; those accounts are not created.

Example React buttons:

```jsx
const API_URL = import.meta.env.VITE_API_URL ?? 'https://admin.e4emerald.com';

function SocialLoginButtons() {
  return (
    <>
      <button onClick={() => window.location.assign(`${API_URL}/auth/social/google/redirect`)}>
        Continue with Google
      </button>
      <button onClick={() => window.location.assign(`${API_URL}/auth/social/apple/redirect`)}>
        Continue with Apple
      </button>
    </>
  );
}
```

On the callback page, read the query string for `social_error` first. On success, call `${API_URL}/api/user` using `fetch(url, { credentials: 'include' })` (or an Axios client configured with `withCredentials: true`); then clear the callback query from browser history and navigate to the app. Configure the frontend API URL, `SANCTUM_STATEFUL_DOMAINS`, CORS allowed origins, and `.e4emerald.com` session cookie domain consistently. Do not put provider client secrets in frontend environment variables.

## 📝 Next.js Frontend Integration

### Example: Fetch Products
```javascript
// pages/products.js
export async function getStaticProps() {
  const res = await fetch('http://localhost:8000/api/products');
  const { data } = await res.json();
  
  return {
    props: { products: data },
    revalidate: 3600, // ISR: revalidate every hour
  };
}
```

### Example: Create Order
```javascript
// pages/checkout.js
async function submitOrder(orderData) {
  const response = await fetch('http://localhost:8000/api/orders', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      customer_email: orderData.email,
      items: orderData.items.map(item => ({
        product_id: item.id,
        quantity: item.qty,
      })),
    }),
  });

  const result = await response.json();
  
  if (!response.ok) {
    throw new Error(result.message);
  }

  return result.data;
}
```

---

## 🧪 Testing the API

### Using cURL

**Test 1: Get All Products**
```bash
curl http://localhost:8000/api/products
```

**Test 2: Get Single Product**
```bash
curl http://localhost:8000/api/products/brazilian-blue-topaz
```

**Test 3: Create Order**
```bash
curl -X POST http://localhost:8000/api/orders \
  -H "Content-Type: application/json" \
  -d '{
    "customer_email": "customer@example.com",
    "items": [
      {"product_id": 1, "quantity": 2}
    ]
  }'
```

**Test 4: Get Order**
```bash
curl http://localhost:8000/api/orders/1
```

---

## 🔧 Additional Commands

**Run Migrations**:
```bash
php artisan migrate
```

**Rollback Migrations**:
```bash
php artisan migrate:rollback
```

**Create Test Product** (via Tinker):
```bash
php artisan tinker
>>> App\Models\Product::create(['name' => 'Test Product', 'slug' => 'test-product', 'description' => 'Test', 'price' => 99.99, 'stock' => 10]);
```

**Check Routes**:
```bash
php artisan route:list --path=api
```

---

## 📚 Documentation Files Created

1. **Product Migration**: Columns for product details with timestamps
2. **Order Migration**: Customer email, total price, status tracking
3. **OrderItem Migration**: Links orders to products with quantity and price
4. **Product Model**: With orderItems relationship
5. **Order Model**: With items relationship (hasMany OrderItem)
6. **OrderItem Model**: With belongsTo relationships
7. **ProductController**: Index and show methods returning JSON
8. **OrderController**: Index, store, and show methods with validation
9. **CORS Config**: Configured for localhost:3000
10. **API Routes**: All endpoints properly structured

---

## ✅ Checklist - All Tasks Completed

- [x] Create Products table with migration
- [x] Create Orders table with migration
- [x] Create OrderItems table with migration
- [x] Create Product model with fillable and relationships
- [x] Create Order model with fillable and relationships
- [x] Create OrderItem model with fillable and relationships
- [x] Implement ProductController with GET /api/products
- [x] Implement GET /api/products/{slug} with 404 handling
- [x] Implement OrderController with POST /api/orders
- [x] Add server-side price calculation
- [x] Add stock validation and reduction
- [x] Add input validation with detailed errors
- [x] Implement database transactions for order creation
- [x] Configure CORS for Next.js (localhost:3000)
- [x] Create API routes file
- [x] Test migrations successfully
- [x] Create sample product data

---

## 🎯 You're Ready to Go!

Your headless e-commerce backend is now fully operational. Your Next.js frontend can:
- ✅ Fetch all products from `/api/products`
- ✅ Get detailed product info from `/api/products/{slug}`
- ✅ Submit orders to `/api/orders`
- ✅ View order details from `/api/orders/{id}`

All endpoints are protected by CORS rules and return proper JSON responses. Database transactions ensure data consistency, and server-side validation prevents invalid orders.

Happy coding! 🚀
