# Online Food Order - API Documentation

## Overview
This is a RESTful API for an online food ordering system built with Laravel 12 and JWT Authentication.

## Base URL
```
http://localhost:8000/api
```

## Authentication
The API uses JWT (JSON Web Tokens) for authentication. 

### Getting a Token
1. Register a new user or login with existing credentials
2. The response will include a `token`
3. Include the token in the `Authorization` header for protected routes:
   ```
   Authorization: Bearer {token}
   ```

## Test Credentials
Two test users have been created:

### Admin User
```
Email: admin@example.com
Password: password123
Role: admin
```

### Regular User
```
Email: user@example.com
Password: password123
Role: user
```

---

## Dashboard Statistics

### Get Dashboard Stats
**GET** `/stats`

**No authentication required** - This is a public endpoint

**Response (200 OK):**
```json
{
    "success": true,
    "data": {
        "total_products": 8,
        "total_orders": 2,
        "total_users": 1,
        "total_categories": 6
    }
}
```

**Returns:**
- `total_products` - Total number of products in system
- `total_orders` - Total number of orders placed
- `total_users` - Total number of regular users (role = 'user' only)
- `total_categories` - Total number of product categories

**Example cURL:**
```bash
curl http://localhost:8000/api/stats
```

---

## Authentication Endpoints

### 1. Register User
**POST** `/register`

**Request Body:**
```json
{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "password123",
    "password_confirmation": "password123"
}
```

**Response (201 Created):**
```json
{
    "success": true,
    "message": "User registered successfully",
    "data": {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com",
        "role": "user"
    }
}
```

---

### 2. Login User
**POST** `/login`

**Request Body:**
```json
{
    "email": "admin@example.com",
    "password": "password123"
}
```

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Login successful",
    "data": {
        "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
        "user": {
            "id": 1,
            "name": "Admin User",
            "email": "admin@example.com",
            "role": "admin"
        }
    }
}
```

---

### 3. Get User Profile
**GET** `/profile`

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "name": "Admin User",
        "email": "admin@example.com",
        "role": "admin",
        "created_at": "2026-03-15T12:00:00.000000Z"
    }
}
```

---

### 4. Logout User
**POST** `/logout`

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Logout successful"
}
```

---

### 5. Change Password
**POST** `/change-password`

**Headers:**
```
Authorization: Bearer {token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "current_password": "password123",
    "new_password": "newpassword456",
    "new_password_confirmation": "newpassword456"
}
```

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Password changed successfully"
}
```

---

## User Management Endpoints

### 6. Get All Users
**GET** `/users`

**⚠️ Admin Only**

**Query Parameters (Optional):**
- `per_page` - Items per page (default: 15)
- `page` - Page number (default: 1)

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "Admin User",
            "email": "admin@example.com",
            "role": "admin",
            "email_verified_at": null,
            "created_at": "2026-03-15T12:00:00.000000Z",
            "updated_at": "2026-03-15T12:00:00.000000Z"
        },
        {
            "id": 2,
            "name": "Regular User",
            "email": "user@example.com",
            "role": "user",
            "email_verified_at": null,
            "created_at": "2026-03-15T12:00:00.000000Z",
            "updated_at": "2026-03-15T12:00:00.000000Z"
        }
    ],
    "pagination": {
        "total": 2,
        "per_page": 15,
        "current_page": 1,
        "last_page": 1,
        "from": 1,
        "to": 2,
        "has_more": false
    }
}
```

---

### 7. Get Single User
**GET** `/users/{id}`

**⚠️ Admin Only**

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "data": {
        "id": 2,
        "name": "Regular User",
        "email": "user@example.com",
        "role": "user",
        "email_verified_at": null,
        "created_at": "2026-03-15T12:00:00.000000Z",
        "updated_at": "2026-03-15T12:00:00.000000Z"
    }
}
```

---

### 8. Update User
**PUT** `/users/{id}`

**⚠️ Admin Only**

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "name": "New User Name",
    "email": "newemail@example.com",
    "role": "admin"
}
```

**Response (200 OK):**
```json
{
    "success": true,
    "message": "User updated successfully",
    "data": {
        "id": 2,
        "name": "New User Name",
        "email": "newemail@example.com",
        "role": "admin",
        "email_verified_at": null,
        "created_at": "2026-03-15T12:00:00.000000Z",
        "updated_at": "2026-03-15T12:01:00.000000Z"
    }
}
```

---

### 9. Delete User
**DELETE** `/users/{id}`

**⚠️ Admin Only**

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "message": "User deleted successfully"
}
```

---

## Pagination

All index endpoints (GET /categories, GET /products, GET /users, GET /orders) support pagination.

**Query Parameters:**
- `per_page` - Number of items per page (default: 15)
- `page` - Page number (default: 1)

**Example:**
```bash
curl -X GET http://localhost:8000/api/categories?per_page=10&page=1 \
  -H "Authorization: Bearer {token}"
```

**Pagination Response:**
```json
{
    "success": true,
    "data": [...],
    "pagination": {
        "total": 25,
        "per_page": 10,
        "current_page": 1,
        "last_page": 3,
        "from": 1,
        "to": 10,
        "has_more": true
    }
}
```

---

## Category Endpoints

### 10. Get All Categories
**GET** `/categories`

**Query Parameters (Optional):**
- `per_page` - Items per page (default: 15)
- `page` - Page number (default: 1)

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "Burgers",
            "slug": "burgers",
            "description": "Delicious homemade burgers",
            "status": 1,
            "created_at": "2026-03-15T12:00:00.000000Z",
            "updated_at": "2026-03-15T12:00:00.000000Z",
            "products": [...]
        }
    ],
    "pagination": {
        "total": 6,
        "per_page": 15,
        "current_page": 1,
        "last_page": 1,
        "from": 1,
        "to": 6,
        "has_more": false
    }
}
```

---

### 11. Get Single Category
**GET** `/categories/{id}`

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "name": "Burgers",
        "slug": "burgers",
        "description": "Delicious homemade burgers",
        "status": 1,
        "created_at": "2026-03-15T12:00:00.000000Z",
        "updated_at": "2026-03-15T12:00:00.000000Z",
        "products": [
            {...}
        ]
    }
}
```

---

### 12. Create Category
**POST** `/categories`

**⚠️ Admin Only**

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "name": "Salads",
    "description": "Fresh healthy salads",
    "image" : null,
    "status": true
}
// image: [image file] (optional, max 2MB, types: jpeg|png|jpg|gif|webp)
```

**Response (201 Created):**
```json
{
    "success": true,
    "message": "Category created successfully",
    "data": {
        "name": "Salads",
        "slug": "salads",
        "description": "Fresh healthy salads",
        "status": 1,
        "updated_at": "2026-03-15T12:30:00.000000Z",
        "created_at": "2026-03-15T12:30:00.000000Z",
        "id": 5
    }
}
```

---

### 13. Update Category
**PUT** `/categories/{id}`

**⚠️ Admin Only**

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "name": "Updated Category Name",
    "description": "Updated description",
    "status": true
}
```

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Category updated successfully",
    "data": {
        "id": 1,
        "name": "Updated Category Name",
        "slug": "updated-category-name",
        "description": "Updated description",
        "status": 1,
        "created_at": "2026-03-15T12:00:00.000000Z",
        "updated_at": "2026-03-15T12:30:00.000000Z"
    }
}
```

---

### 14. Delete Category
**DELETE** `/categories/{id}`

**⚠️ Admin Only**

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Category deleted successfully"
}
```

---

## Product Endpoints

### 15. Get All Products
**GET** `/products`

**Query Parameters (Optional):**
- `per_page` - Items per page (default: 15)
- `page` - Page number (default: 1)

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "category_id": 1,
            "name": "Classic Cheeseburger",
            "slug": "classic-cheeseburger",
            "description": "Juicy classic burger with melted cheese",
            "price": "9.99",
            "image": null,
            "stock": 50,
            "status": 1,
            "created_at": "2026-03-15T12:00:00.000000Z",
            "updated_at": "2026-03-15T12:00:00.000000Z",
            "category": {
                "id": 1,
                "name": "Burgers",
                "slug": "burgers",
                ...
            }
        }
    ],
    "pagination": {
        "total": 8,
        "per_page": 15,
        "current_page": 1,
        "last_page": 1,
        "from": 1,
        "to": 8,
        "has_more": false
    }
}
```

---

### 16. Get Single Product
**GET** `/products/{id}`

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "category_id": 1,
        "name": "Classic Cheeseburger",
        "slug": "classic-cheeseburger",
        "description": "Juicy classic burger with melted cheese",
        "price": "9.99",
        "image": null,
        "stock": 50,
        "status": 1,
        "created_at": "2026-03-15T12:00:00.000000Z",
        "updated_at": "2026-03-15T12:00:00.000000Z",
        "category": {
            "id": 1,
            "name": "Burgers",
            "slug": "burgers",
            ...
        }
    }
}
```

---

### 17. Create Product
**POST** `/products`

**⚠️ Admin Only**

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "category_id": 1,
    "name": "Double Burger",
    "description": "Two patties with cheese",
    "price": 14.99,
    "image": null,
    "stock": 25,
    "status": true
}
```

**Response (201 Created):**
```json
{
    "success": true,
    "message": "Product created successfully",
    "data": {
        "category_id": 1,
        "name": "Double Burger",
        "slug": "double-burger",
        "description": "Two patties with cheese",
        "price": "14.99",
        "image": null,
        "stock": 25,
        "status": 1,
        "updated_at": "2026-03-15T12:30:00.000000Z",
        "created_at": "2026-03-15T12:30:00.000000Z",
        "id": 9,
        "category": {
            "id": 1,
            "name": "Burgers",
            ...
        }
    }
}
```

---

### 18. Update Product
**PUT** `/products/{id}`

**⚠️ Admin Only**

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "name": "Premium Cheeseburger",
    "price": 12.99,
    "stock": 45,
    "description": "Premium quality cheeseburger"
}
```

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Product updated successfully",
    "data": {
        "id": 1,
        "category_id": 1,
        "name": "Premium Cheeseburger",
        "slug": "premium-cheeseburger",
        "description": "Premium quality cheeseburger",
        "price": "12.99",
        "image": null,
        "stock": 45,
        "status": 1,
        "created_at": "2026-03-15T12:00:00.000000Z",
        "updated_at": "2026-03-15T12:30:00.000000Z",
        "category": {
            "id": 1,
            "name": "Burgers",
            ...
        }
    }
}
```

---

### 19. Delete Product
**DELETE** `/products/{id}`

**⚠️ Admin Only**

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Product deleted successfully"
}
```

---

## Error Responses

### Validation Error (422)
```json
{
    "success": false,
    "message": "Validation failed",
    "errors": {
        "email": [
            "The email field is required."
        ]
    }
}
```

### Unauthorized (401)
```json
{
    "success": false,
    "message": "Invalid credentials"
}
```

### Forbidden - Admin Only (403)
```json
{
    "success": false,
    "message": "Unauthorized - Admin access required"
}
```

### Server Error (500)
```json
{
    "success": false,
    "message": "Failed to create category",
    "error": "Error message details"
}
```

---

## Testing with cURL

### Example: Login and Get Token
```bash
curl -X POST http://localhost:8000/api/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "admin@example.com",
    "password": "password123"
  }'
```

### Example: Get All Categories (with pagination)
```bash
curl -X GET "http://localhost:8000/api/categories?per_page=10&page=1" \
  -H "Authorization: Bearer {your_token_here}"
```

### Example: Get All Products with 5 items per page
```bash
curl -X GET "http://localhost:8000/api/products?per_page=5" \
  -H "Authorization: Bearer {your_token_here}"
```

### Example: Get All Users - Page 2 (Admin Only)
```bash
curl -X GET "http://localhost:8000/api/users?per_page=10&page=2" \
  -H "Authorization: Bearer {admin_token_here}"
```

### Example: Get All Orders with pagination
```bash
curl -X GET "http://localhost:8000/api/orders?per_page=20" \
  -H "Authorization: Bearer {your_token_here}"
```

### Example: Create New Category (Admin Only)
```bash
curl -X POST http://localhost:8000/api/categories \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer {admin_token_here}" \
  -d '{
    "name": "Beverages",
    "description": "Drinks and beverages",
    "status": true
  }'
```

---

## Database Schema

### Users Table
- id (Primary Key)
- name (string)
- email (unique string)
- password (hashed string)
- role (enum: 'user', 'admin') - default: 'user'
- email_verified_at (nullable timestamp)
- remember_token (nullable string)
- created_at (timestamp)
- updated_at (timestamp)

### Categories Table
- id (Primary Key)
- name (string)
- slug (unique string)
- description (text, nullable)
- status (boolean) - default: 1
- created_at (timestamp)
- updated_at (timestamp)

### Products Table
- id (Primary Key)
- category_id (Foreign Key → categories.id)
- name (string)
- slug (unique string)
- description (text, nullable)
- price (decimal 10,2)
- image (string, nullable)
- stock (integer) - default: 0
- status (boolean) - default: 1
- created_at (timestamp)
- updated_at (timestamp)

---

## Features Implemented

✅ JWT Authentication (Register, Login, Logout, Profile)
✅ User Roles (Admin & Regular User)
✅ User Management (View, Update, Delete users - Admin only)
✅ Change Password (All authenticated users)
✅ Category CRUD (Admin only for create/update/delete)
✅ Product CRUD (Admin only for create/update/delete)
✅ Product-Category Relationship
✅ Order Management (Create, View, Update Status, Cancel, Delete)
✅ Dashboard Statistics (Total Products, Orders, Users, Categories)
✅ Input Validation
✅ Consistent JSON Response Format
✅ Error Handling
✅ Test Data Seeders

---

## Running the Server

```bash
php artisan serve
```

The API will be accessible at `http://localhost:8000/api`

---

## Order Endpoints

**⚠️ All order endpoints require `Content-Type: application/json` header with raw JSON body. Using form-data will result in 422 Unprocessable Content error.**

### 20. Create Order
**POST** `/orders`

**Headers:**
```
Authorization: Bearer {token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "phone": "0123456789",
    "address": "123 Main Street, Downtown",
    "notes": "Extra napkins please",
    "items": [
        {
            "product_id": 1,
            "quantity": 2
        },
        {
            "product_id": 3,
            "quantity": 1
        }
    ]
}
```

**Response (201 Created):**
```json
{
    "success": true,
    "message": "Order created successfully",
    "data": {
        "id": 1,
        "user_id": 2,
        "order_number": "ORD-F8TXQEMQHA-1773546370",
        "status": "pending",
        "phone": "0123456789",
        "address": "123 Main Street, Downtown",
        "notes": "Extra napkins please",
        "total_amount": "32.97",
        "created_at": "2026-03-15T03:46:10.000000Z",
        "updated_at": "2026-03-15T03:46:10.000000Z",
        "user": {
            "id": 2,
            "name": "Premium User",
            "email": "user@example.com",
            "role": "user"
        },
        "items": [
            {
                "id": 1,
                "order_id": 1,
                "product_id": 1,
                "quantity": 2,
                "price": "9.99",
                "subtotal": "19.98",
                "product": {
                    "id": 1,
                    "name": "Classic Cheeseburger",
                    "price": "9.99",
                    "stock": 50
                }
            },
            {
                "id": 2,
                "order_id": 1,
                "product_id": 3,
                "quantity": 1,
                "price": "12.99",
                "subtotal": "12.99",
                "product": {
                    "id": 3,
                    "name": "Margherita Pizza",
                    "price": "12.99",
                    "stock": 30
                }
            }
        ]
    }
}
```

---

### 21. Get All Orders
**GET** `/orders`

**Query Parameters (Optional):**
- `per_page` - Items per page (default: 15)
- `page` - Page number (default: 1)

**Headers:**
```
Authorization: Bearer {token}
```

**Behavior:**
- Regular users see only their own orders
- Admin users see all orders in the system

**Response (200 OK):**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "user_id": 2,
            "order_number": "ORD-F8TXQEMQHA-1773546370",
            "status": "pending",
            "phone": "0123456789",
            "address": "123 Main Street, Downtown",
            "notes": "Extra napkins please",
            "total_amount": "32.97",
            "created_at": "2026-03-15T03:46:10.000000Z",
            "updated_at": "2026-03-15T03:46:10.000000Z",
            "user": {
                "id": 2,
                "name": "Premium User",
                "email": "user@example.com"
            },
            "items": [
                {...}
            ]
        }
    ],
    "pagination": {
        "total": 2,
        "per_page": 15,
        "current_page": 1,
        "last_page": 1,
        "from": 1,
        "to": 2,
        "has_more": false
    }
}
```

---

### 22. Get Single Order
**GET** `/orders/{id}`

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "user_id": 2,
        "order_number": "ORD-F8TXQEMQHA-1773546370",
        "status": "pending",
        "phone": "0123456789",
        "address": "123 Main Street, Downtown",
        "notes": "Extra napkins please",
        "total_amount": "32.97",
        "created_at": "2026-03-15T03:46:10.000000Z",
        "updated_at": "2026-03-15T03:46:10.000000Z",
        "user": {
            "id": 2,
            "name": "Premium User",
            "email": "user@example.com",
            "role": "user"
        },
        "items": [
            {
                "id": 1,
                "order_id": 1,
                "product_id": 1,
                "quantity": 2,
                "price": "9.99",
                "subtotal": "19.98",
                "product": {
                    "id": 1,
                    "name": "Classic Cheeseburger",
                    "description": "Juicy classic burger with melted cheese",
                    "price": "9.99",
                    "stock": 50
                }
            },
            {
                "id": 2,
                "order_id": 1,
                "product_id": 3,
                "quantity": 1,
                "price": "12.99",
                "subtotal": "12.99",
                "product": {
                    "id": 3,
                    "name": "Margherita Pizza",
                    "description": "Traditional pizza with tomato, mozzarella and basil",
                    "price": "12.99",
                    "stock": 30
                }
            }
        ]
    }
}
```

---

### 23. Update Order Status
**PUT** `/orders/{id}`

**⚠️ Admin Only**

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**⚠️ IMPORTANT: Use raw JSON, NOT form-data. Using form-data will return 422 error.**

**Request Body:**
```json
{
    "status": "confirmed"
}
```

**Valid Status Values:**
- `pending` - Initial status when order is created
- `confirmed` - Order confirmed by admin
- `preparing` - Kitchen is preparing the order
- `ready` - Order is ready for pickup/delivery
- `delivering` - Order is being delivered
- `completed` - Order completed
- `cancelled` - Order cancelled

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Order status updated successfully",
    "data": {
        "id": 1,
        "order_number": "ORD-F8TXQEMQHA-1773546370",
        "status": "confirmed",
        "total_amount": "32.97",
        "updated_at": "2026-03-15T04:00:00.000000Z"
    }
}
```

---

### 24. Cancel Order
**POST** `/orders/{id}/cancel`

**Headers:**
```
Authorization: Bearer {token}
```

**Behavior:**
- Regular users can cancel orders in `pending` or `confirmed` status
- Admin users can cancel orders in any status

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Order cancelled successfully",
    "data": {
        "id": 1,
        "order_number": "ORD-F8TXQEMQHA-1773546370",
        "status": "cancelled",
        "total_amount": "32.97",
        "updated_at": "2026-03-15T04:00:00.000000Z"
    }
}
```

---

### 25. Delete Order
**DELETE** `/orders/{id}`

**⚠️ Admin Only**

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Order deleted successfully"
}
```

---

## Order Management - cURL Examples

### Example: Login and Get Token
```bash
curl -X POST http://localhost:8000/api/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "password123"
  }'
```

### Example: Create a New Order
```bash
curl -X POST http://localhost:8000/api/orders \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer {your_token_here}" \
  -d '{
    "phone": "0123456789",
    "address": "123 Main Street, City",
    "notes": "Please deliver quickly",
    "items": [
      {
        "product_id": 1,
        "quantity": 2
      },
      {
        "product_id": 3,
        "quantity": 1
      }
    ]
  }'
```

### Example: Get All My Orders
```bash
curl -X GET "http://localhost:8000/api/orders?per_page=10" \
  -H "Authorization: Bearer {your_token_here}"
```

### Example: Get All Orders (Admin with pagination)
```bash
curl -X GET "http://localhost:8000/api/orders?per_page=20&page=1" \
  -H "Authorization: Bearer {admin_token_here}"
```

### Example: Get Single Order Details
```bash
curl -X GET http://localhost:8000/api/orders/1 \
  -H "Authorization: Bearer {your_token_here}"
```

### Example: Update Order Status (Admin Only)
```bash
curl -X PUT http://localhost:8000/api/orders/1 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer {admin_token_here}" \
  -d '{
    "status": "confirmed"
  }'
```

### Example: Cancel Order
```bash
curl -X POST http://localhost:8000/api/orders/1/cancel \
  -H "Authorization: Bearer {your_token_here}"
```

### Example: Delete Order (Admin Only)
```bash
curl -X DELETE http://localhost:8000/api/orders/1 \
  -H "Authorization: Bearer {admin_token_here}"
```

---

## Orders Database Schema

### Orders Table
- id (Primary Key)
- user_id (Foreign Key → users.id)
- order_number (unique string) - Format: ORD-{RANDOM}-{TIMESTAMP}
- status (enum: pending|confirmed|preparing|ready|delivering|completed|cancelled)
- phone (string)
- address (string)
- notes (text, nullable)
- total_amount (decimal 10,2)
- created_at (timestamp)
- updated_at (timestamp)

### Order Items Table
- id (Primary Key)
- order_id (Foreign Key → orders.id, cascade delete)
- product_id (Foreign Key → products.id)
- quantity (integer)
- price (decimal 10,2) - Price at time of order
- subtotal (decimal 10,2) - quantity × price
- created_at (timestamp)
- updated_at (timestamp)

---

## Payment Options Management

### List Payment Options
**GET** `/payment-options`

**Authentication:** Required (Bearer Token)

**Query Parameters:**
- `per_page` (optional) - Items per page (default: 15)
- `page` (optional) - Page number (default: 1)

**Response (200 OK):**
```json
{
  "success": true,
  "message": "Payment options retrieved successfully",
  "data": [
    {
      "id": 1,
      "name": "Credit Card",
      "description": "Pay using credit card",
      "status": true,
      "created_at": "2026-03-15T09:45:00Z",
      "updated_at": "2026-03-15T09:45:00Z"
    },
    {
      "id": 2,
      "name": "Debit Card",
      "description": "Pay using debit card",
      "status": true,
      "created_at": "2026-03-15T09:45:01Z",
      "updated_at": "2026-03-15T09:45:01Z"
    },
    {
      "id": 3,
      "name": "Cash on Delivery",
      "description": "Pay when order is delivered",
      "status": true,
      "created_at": "2026-03-15T09:45:02Z",
      "updated_at": "2026-03-15T09:45:02Z"
    },
    {
      "id": 4,
      "name": "Online Wallet",
      "description": "Pay using mobile wallet",
      "status": true,
      "created_at": "2026-03-15T09:45:03Z",
      "updated_at": "2026-03-15T09:45:03Z"
    }
  ],
  "pagination": {
    "total": 4,
    "count": 4,
    "per_page": 15,
    "current_page": 1,
    "total_pages": 1
  }
}
```

**cURL Example:**
```bash
curl -X GET "http://localhost:8000/api/payment-options?per_page=10" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

---

### Get Single Payment Option
**GET** `/payment-options/{id}`

**Authentication:** Required (Bearer Token)

**Response (200 OK):**
```json
{
  "success": true,
  "message": "Payment option retrieved successfully",
  "data": {
    "id": 1,
    "name": "Credit Card",
    "description": "Pay using credit card",
    "status": true,
    "created_at": "2026-03-15T09:45:00Z",
    "updated_at": "2026-03-15T09:45:00Z"
  }
}
```

**Response (404 Not Found):**
```json
{
  "success": false,
  "message": "Payment option not found"
}
```

**cURL Example:**
```bash
curl -X GET "http://localhost:8000/api/payment-options/1" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

---

### Create Payment Option (Admin Only)
**POST** `/payment-options`

**Authentication:** Required (Bearer Token) - Admin only

**Request Body:**
```json
{
  "name": "Google Pay",
  "description": "Pay using Google Pay",
  "status": true
}
```

**Validation Rules:**
- `name` - required, string, unique (max 255 chars)
- `description` - required, string
- `status` - required, boolean

**Response (201 Created):**
```json
{
  "success": true,
  "message": "Payment option created successfully",
  "data": {
    "id": 5,
    "name": "Google Pay",
    "description": "Pay using Google Pay",
    "status": true,
    "created_at": "2026-03-15T10:00:00Z",
    "updated_at": "2026-03-15T10:00:00Z"
  }
}
```

**Response (403 Forbidden):**
```json
{
  "success": false,
  "message": "Unauthorized. Only admin can create payment options"
}
```

**Response (422 Unprocessable Entity):**
```json
{
  "success": false,
  "message": "Validation failed",
  "errors": {
    "name": ["The name field is required.", "The name has already been taken."]
  }
}
```

**cURL Example:**
```bash
curl -X POST "http://localhost:8000/api/payment-options" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Google Pay",
    "description": "Pay using Google Pay",
    "status": true
  }'
```

---

### Update Payment Option (Admin Only)
**PUT** `/payment-options/{id}`

**Authentication:** Required (Bearer Token) - Admin only

**Request Body:**
```json
{
  "name": "Updated Payment Method",
  "description": "Updated description",
  "status": false
}
```

**Response (200 OK):**
```json
{
  "success": true,
  "message": "Payment option updated successfully",
  "data": {
    "id": 1,
    "name": "Updated Payment Method",
    "description": "Updated description",
    "status": false,
    "created_at": "2026-03-15T09:45:00Z",
    "updated_at": "2026-03-15T10:15:00Z"
  }
}
```

**Response (403 Forbidden):**
```json
{
  "success": false,
  "message": "Unauthorized. Only admin can update payment options"
}
```

**cURL Example:**
```bash
curl -X PUT "http://localhost:8000/api/payment-options/1" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Updated Payment Method",
    "description": "Updated description",
    "status": false
  }'
```

---

### Delete Payment Option (Admin Only)
**DELETE** `/payment-options/{id}`

**Authentication:** Required (Bearer Token) - Admin only

**Response (200 OK):**
```json
{
  "success": true,
  "message": "Payment option deleted successfully"
}
```

**Response (403 Forbidden):**
```json
{
  "success": false,
  "message": "Unauthorized. Only admin can delete payment options"
}
```

**Response (409 Conflict):**
```json
{
  "success": false,
  "message": "Cannot delete payment option that has associated payments",
  "data": {
    "payment_count": 5
  }
}
```

**cURL Example:**
```bash
curl -X DELETE "http://localhost:8000/api/payment-options/1" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

---

## Payments

### List All Payments (Admin Only)
**GET** `/payments`

**Authentication:** Required (Bearer Token) - Admin only

**Query Parameters:**
- `per_page` (optional) - Items per page (default: 15)
- `page` (optional) - Page number (default: 1)

**Response (200 OK):**
```json
{
  "success": true,
  "message": "Payments retrieved successfully",
  "data": [
    {
      "id": 1,
      "order_id": 1,
      "payment_option_id": 1,
      "amount": "32.97",
      "status": "pending",
      "transaction_id": "TXN-1234567890",
      "notes": "Payment for order",
      "created_at": "2026-03-15T10:00:00Z",
      "updated_at": "2026-03-15T10:00:00Z",
      "order": {
        "id": 1,
        "order_number": "ORD-ABC123-1234567890",
        "status": "pending"
      },
      "payment_option": {
        "id": 1,
        "name": "Credit Card"
      }
    }
  ],
  "pagination": {
    "total": 1,
    "count": 1,
    "per_page": 15,
    "current_page": 1,
    "total_pages": 1
  }
}
```

**Response (403 Forbidden):**
```json
{
  "success": false,
  "message": "Unauthorized. Only admin can view all payments"
}
```

**cURL Example:**
```bash
curl -X GET "http://localhost:8000/api/payments?per_page=10&page=1" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

---

### Get Single Payment
**GET** `/payments/{id}`

**Authentication:** Required (Bearer Token)
- Users can only view their own order's payments
- Admins can view any payment

**Response (200 OK):**
```json
{
  "success": true,
  "message": "Payment retrieved successfully",
  "data": {
    "id": 1,
    "order_id": 1,
    "payment_option_id": 1,
    "amount": "32.97",
    "status": "pending",
    "transaction_id": "TXN-1234567890",
    "notes": "Payment for order",
    "created_at": "2026-03-15T10:00:00Z",
    "updated_at": "2026-03-15T10:00:00Z",
    "order": {
      "id": 1,
      "order_number": "ORD-ABC123-1234567890",
      "user_id": 2,
      "total_amount": "32.97",
      "status": "pending"
    },
    "payment_option": {
      "id": 1,
      "name": "Credit Card",
      "description": "Pay using credit card"
    }
  }
}
```

**Response (403 Forbidden):**
```json
{
  "success": false,
  "message": "You can only view payments for your own orders"
}
```

**Response (404 Not Found):**
```json
{
  "success": false,
  "message": "Payment not found"
}
```

**cURL Example:**
```bash
curl -X GET "http://localhost:8000/api/payments/1" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

---

### Create Payment for Order
**POST** `/payments`

**Authentication:** Required (Bearer Token)
- Users can create payments for their own orders
- Admins can create payments for any order

**Request Body:**
```json
{
  "order_id": 1,
  "payment_option_id": 1,
  "transaction_id": "TXN-1234567890",
  "notes": "Payment for order"
}
```

**Validation Rules:**
- `order_id` - required, integer, must exist in orders table
- `payment_option_id` - required, integer, must exist and be active
- `transaction_id` - optional, string (max 255 chars)
- `notes` - optional, string

**Business Logic:**
1. Amount is automatically calculated from `order.total_amount`
2. Payment option must have `status = true` (active)
3. Order cannot have another completed payment (only one completed payment per order)
4. Payment status defaults to "pending"

**Response (201 Created):**
```json
{
  "success": true,
  "message": "Payment created successfully",
  "data": {
    "id": 1,
    "order_id": 1,
    "payment_option_id": 1,
    "amount": "32.97",
    "status": "pending",
    "transaction_id": "TXN-1234567890",
    "notes": "Payment for order",
    "created_at": "2026-03-15T10:00:00Z",
    "updated_at": "2026-03-15T10:00:00Z"
  }
}
```

**Response (403 Forbidden):**
```json
{
  "success": false,
  "message": "You can only create payments for your own orders"
}
```

**Response (422 Unprocessable Entity):**
```json
{
  "success": false,
  "message": "Cannot create payment",
  "errors": {
    "order_id": "Order already has a completed payment or order not found",
    "payment_option_id": "Payment option is not available"
  }
}
```

**cURL Example:**
```bash
curl -X POST "http://localhost:8000/api/payments" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "order_id": 1,
    "payment_option_id": 1,
    "transaction_id": "TXN-1234567890",
    "notes": "Payment for order"
  }'
```

---

### Update Payment Status (Admin Only)
**PUT** `/payments/{id}`

**Authentication:** Required (Bearer Token) - Admin only

**Request Body:**
```json
{
  "status": "completed"
}
```

**Validation Rules:**
- `status` - required, string, must be one of: `pending`, `completed`, `failed`, `refunded`

**Response (200 OK):**
```json
{
  "success": true,
  "message": "Payment updated successfully",
  "data": {
    "id": 1,
    "order_id": 1,
    "payment_option_id": 1,
    "amount": "32.97",
    "status": "completed",
    "transaction_id": "TXN-1234567890",
    "notes": "Payment for order",
    "created_at": "2026-03-15T10:00:00Z",
    "updated_at": "2026-03-15T10:15:00Z"
  }
}
```

**Response (403 Forbidden):**
```json
{
  "success": false,
  "message": "Unauthorized. Only admin can update payment status"
}
```

**Response (422 Unprocessable Entity):**
```json
{
  "success": false,
  "message": "Invalid payment status",
  "errors": {
    "status": "The status must be one of: pending, completed, failed, refunded"
  }
}
```

**cURL Example:**
```bash
curl -X PUT "http://localhost:8000/api/payments/1" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "status": "completed"
  }'
```

---

### Delete Payment (Admin Only)
**DELETE** `/payments/{id}`

**Authentication:** Required (Bearer Token) - Admin only

**Response (200 OK):**
```json
{
  "success": true,
  "message": "Payment deleted successfully"
}
```

**Response (403 Forbidden):**
```json
{
  "success": false,
  "message": "Unauthorized. Only admin can delete payments"
}
```

**Response (404 Not Found):**
```json
{
  "success": false,
  "message": "Payment not found"
}
```

**cURL Example:**
```bash
curl -X DELETE "http://localhost:8000/api/payments/1" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

---

## Payment Database Schema

### Payment Options Table
- id (Primary Key)
- name (unique string, max 255)
- description (text, nullable)
- status (boolean) - default: 1 (Active)
- created_at (timestamp)
- updated_at (timestamp)

### Payments Table
- id (Primary Key)
- order_id (Foreign Key → orders.id, cascade delete)
- payment_option_id (Foreign Key → payment_options.id)
- amount (decimal 10,2) - Auto-calculated from order.total_amount
- status (enum: pending|completed|failed|refunded)
- transaction_id (string, nullable, unique)
- notes (text, nullable)
- created_at (timestamp)
- updated_at (timestamp)

---

## Payment Workflow Example

### Step 1: List Available Payment Options
```bash
curl -X GET "http://localhost:8000/api/payment-options" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

### Step 2: Create an Order (via orders API)
```bash
# See Orders section for order creation
```

### Step 3: Create a Payment for the Order
```bash
curl -X POST "http://localhost:8000/api/payments" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "order_id": 1,
    "payment_option_id": 1,
    "transaction_id": "TXN-ABC123",
    "notes": "Payment via Credit Card"
  }'
```

### Step 4: View Payment Details
```bash
curl -X GET "http://localhost:8000/api/payments/1" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

### Step 5: Admin Updates Payment Status (after processing)
```bash
curl -X PUT "http://localhost:8000/api/payments/1" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "status": "completed"
  }'
```

---

## Create User (Admin Only)

### POST `/users`

**⚠️ Admin Only**

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: multipart/form-data
```

**Request Body (Form Data):**
```
name: John Doe (required)
email: john@example.com (required, unique)
password: password123 (required, min 6 chars)
password_confirmation: password123 (required, must match password)
role: user (optional, default: user, values: user|admin)
avatar: [image file] (optional, max 2MB, types: jpeg|png|jpg|gif|webp)
```

**Response (201 Created):**
```json
{
    "success": true,
    "message": "User created successfully",
    "data": {
        "name": "John Doe",
        "email": "john@example.com",
        "role": "user",
        "avatar": "avatars/ho78zzUbkP_1773677248.png",
        "updated_at": "2026-03-16T16:07:28.000000Z",
        "created_at": "2026-03-16T16:07:28.000000Z",
        "id": 4
    }
}
```

**Example cURL (without avatar):**
```bash
curl -X POST "http://localhost:8000/api/users" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Jane Smith",
    "email": "jane@example.com",
    "password": "securepass123",
    "password_confirmation": "securepass123",
    "role": "user"
  }'
```

**Example cURL (with avatar):**
```bash
curl -X POST "http://localhost:8000/api/users" \
  -H "Authorization: Bearer {admin_token}" \
  -F "name=Jane Smith" \
  -F "email=jane@example.com" \
  -F "password=securepass123" \
  -F "password_confirmation=securepass123" \
  -F "role=user" \
  -F "avatar=@/path/to/avatar.png"
```

---

## Get User Orders (Admin Only)

### GET `/users/{user}/orders`

**⚠️ Admin Only**

**Query Parameters (Optional):**
- `per_page` - Items per page (default: 15)
- `page` - Page number (default: 1)

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Orders retrieved successfully for user: John Doe",
    "user": {
        "id": 3,
        "name": "John Doe",
        "email": "john@example.com"
    },
    "data": [
        {
            "id": 1,
            "user_id": 3,
            "order_number": "ORD-ABC123-1234567890",
            "total_amount": "45.98",
            "status": "pending",
            "payment_status": "pending",
            "paid_by": null,
            "phone": "09123456789",
            "address": "123 Main Street",
            "notes": "Please deliver in morning",
            "created_at": "2026-03-15T10:00:00.000000Z",
            "updated_at": "2026-03-15T10:00:00.000000Z",
            "items": [...]
        }
    ],
    "pagination": {
        "total": 1,
        "per_page": 15,
        "current_page": 1,
        "last_page": 1,
        "from": 1,
        "to": 1,
        "has_more": false
    }
}
```

**Example cURL:**
```bash
curl -X GET "http://localhost:8000/api/users/3/orders?per_page=10" \
  -H "Authorization: Bearer {admin_token}"
```

---

## Favorites API (User Only)

### 42. Get User's Favorite Products
**GET** `/favorites`

**Headers:**
```
Authorization: Bearer {token}
```

**Query Parameters (Optional):**
- `per_page` - Items per page (default: 15)
- `page` - Page number (default: 1)

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Favorites retrieved successfully",
    "data": [
        {
            "id": 1,
            "user_id": 3,
            "product_id": 1,
            "created_at": "2026-03-15T09:33:53.000000Z",
            "updated_at": "2026-03-15T09:33:53.000000Z",
            "product": {
                "id": 1,
                "category_id": 1,
                "name": "Classic Cheeseburger",
                "slug": "classic-cheeseburger",
                "description": "Juicy classic burger with melted cheese",
                "price": "9.99",
                "image": null,
                "stock": 50,
                "status": true,
                "created_at": "2026-03-15T02:48:24.000000Z",
                "updated_at": "2026-03-15T02:48:24.000000Z"
            }
        }
    ],
    "pagination": {
        "total": 1,
        "per_page": 15,
        "current_page": 1,
        "last_page": 1,
        "from": 1,
        "to": 1,
        "has_more": false
    }
}
```

**Example cURL:**
```bash
curl -X GET "http://localhost:8000/api/favorites" \
  -H "Authorization: Bearer {token}"
```

---

### 43. Add Product to Favorites
**POST** `/favorites`

**Headers:**
```
Authorization: Bearer {token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "user_id" : 5,
    "product_id": 1
}
```

**Response (201 Created):**
```json
{
    "success": true,
    "message": "Product added to favorites successfully",
    "data": {
        "id": 5,
        "user_id": 3,
        "product_id": 1,
        "created_at": "2026-03-16T08:30:45.000000Z",
        "updated_at": "2026-03-16T08:30:45.000000Z",
        "product": {
            "id": 1,
            "category_id": 1,
            "name": "Classic Cheeseburger",
            "slug": "classic-cheeseburger",
            "description": "Juicy classic burger with melted cheese",
            "price": "9.99",
            "image": null,
            "stock": 50,
            "status": true
        }
    }
}
```

**Error Response (409 Conflict - Already Favorited):**
```json
{
    "success": false,
    "message": "Product is already in your favorites",
    "data": {
        "id": 1,
        "user_id": 3,
        "product_id": 1,
        "created_at": "2026-03-15T09:33:53.000000Z",
        "updated_at": "2026-03-15T09:33:53.000000Z"
    }
}
```

**Example cURL:**
```bash
curl -X POST "http://localhost:8000/api/favorites" \
  -H "Authorization: Bearer {token}" \
  -H "Content-Type: application/json" \
  -d '{"product_id": 1}'
```

---

### 44. Remove Product from Favorites
**DELETE** `/favorites/{product_id}`

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Product removed from favorites successfully"
}
```

**Error Response (404 Not Found):**
```json
{
    "success": false,
    "message": "Product not found in your favorites"
}
```

**Example cURL:**
```bash
curl -X DELETE "http://localhost:8000/api/favorites/1" \
  -H "Authorization: Bearer {token}"
```

---

### 45. Check if Product is Favorited
**GET** `/favorites/check/{product_id}`

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
{
    "success": true,
    "message": "Favorite status retrieved",
    "data": {
        "product_id": "1",
        "is_favorited": true
    }
}
```

**When Not Favorited:**
```json
{
    "success": true,
    "message": "Favorite status retrieved",
    "data": {
        "product_id": "3",
        "is_favorited": false
    }
}
```

**Example cURL:**
```bash
curl -X GET "http://localhost:8000/api/favorites/check/1" \
  -H "Authorization: Bearer {token}"
```

---

## Order Fields Update

### Order Model Now Includes:

#### new fields added to orders table:
- `payment_status` (enum: pending|completed|failed|refunded) - Status of the payment
- `paid_by` (string, nullable) - Payment option name (e.g., "Credit Card", "Cash on Delivery")

### Example Order with Payment Fields:
```json
{
    "id": 1,
    "user_id": 3,
    "order_number": "ORD-ABC123-1234567890",
    "total_amount": "45.98",
    "status": "pending",
    "payment_status": "completed",
    "paid_by": "Credit Card",
    "phone": "09123456789",
    "address": "123 Main Street",
    "notes": "Please deliver in morning",
    "created_at": "2026-03-15T10:00:00.000000Z",
    "updated_at": "2026-03-15T10:00:00.000000Z"
}
```

---

## Database Schema - Favorites Table

### Favorites Table
- id (Primary Key)
- user_id (Foreign Key → users.id, cascade delete)
- product_id (Foreign Key → products.id, cascade delete)
- created_at (timestamp)
- updated_at (timestamp)
- Unique Constraint on (user_id, product_id) - Prevents duplicate favorites

---

## Next Steps (Optional)

- Add image retrieval endpoints
- Add bulk favorite operations
- Implement favorite count statistics
- Add user activity tracking
- Add notification system for order updates
- Add review and rating system
- Add discount and coupon management
- Add advanced search and filtering
- Add reporting and analytics endpoints
- Implement payment gateway integration (Stripe, PayPal, etc.)
