# Noahvelle POS Backend API Documentation

## Overview
This is a comprehensive PHP REST API for the Noahvelle POS system - a point-of-sale system for a Sri Lankan boutique.

## Base URL
```
http://localhost/Noahvelle%20POS/backend/api/
```

## Response Format
All endpoints return JSON responses with appropriate HTTP status codes.

### Success Response
```json
{
  "success": true,
  "data": { ... }
}
```

### Error Response
```json
{
  "error": "Error message",
  "status": 400
}
```

---

## Authentication Endpoints

### POST `/auth.php?action=login`
Authenticate a user (admin/cashier) with PIN.

**Request:**
```json
{
  "id": "admin",
  "pin": "1234"
}
```

**Response (Success):**
```json
{
  "success": true,
  "user": {
    "id": "admin",
    "name": "Kamal Perera",
    "role": "admin",
    "email": "kamal@noahvelle.lk"
  }
}
```

---

## Product Endpoints

### GET `/products.php?action=get_all`
Get all products with variations.

**Query Parameters:**
- `category_id` (optional): Filter by category

**Response:**
```json
[
  {
    "id": 1,
    "name": "Handloom Cotton Saree",
    "category_id": 1,
    "brand": "LankaLooms",
    "cost": 4500,
    "price": 8500,
    "image_url": "https://...",
    "status": "active",
    "variations": [
      {
        "id": "1-1",
        "product_id": 1,
        "size": "Free",
        "color": "Red/Gold",
        "stock": 12,
        "sku": "W-SAREE-001-F",
        "barcode": "20260101",
        "low_stock_threshold": 5,
        "printed_label_count": 24
      }
    ]
  }
]
```

### GET `/products.php?action=get`
Get a specific product.

**Query Parameters:**
- `id`: Product ID

### GET `/products.php?action=by_barcode`
Get product by barcode.

**Query Parameters:**
- `barcode`: Barcode string

### GET `/products.php?action=low_stock`
Get products below stock threshold.

### POST `/products.php?action=create`
Create a new product.

**Request:**
```json
{
  "name": "New Product",
  "category_id": 1,
  "brand": "Brand Name",
  "cost": 1000,
  "price": 2000,
  "image_url": "https://...",
  "description": "Product description"
}
```

### PUT `/products.php?action=update`
Update a product.

**Query Parameters:**
- `id`: Product ID

---

## Customer Endpoints

### GET `/customers.php?action=get_all`
Get all customers.

**Response:**
```json
[
  {
    "id": 101,
    "name": "Kasun Perera",
    "email": "kasun.p@example.lk",
    "phone": "077-1234567",
    "loyalty_points": 450,
    "total_spent": 125000,
    "last_visit": "2026-02-25 14:30:00",
    "birthday": "1990-03-10",
    "status": "active"
  }
]
```

### GET `/customers.php?action=get`
Get specific customer.

**Query Parameters:**
- `id`: Customer ID

### GET `/customers.php?action=search`
Search customers by name, email, or phone.

**Query Parameters:**
- `term`: Search term

### GET `/customers.php?action=upcoming_birthdays`
Get customers with upcoming birthdays.

**Query Parameters:**
- `days` (optional): Days ahead to check (default: 3)

### GET `/customers.php?action=stats`
Get customer statistics.

**Query Parameters:**
- `id`: Customer ID

**Response:**
```json
{
  "total_purchases": 5,
  "total_spent": 45000,
  "last_purchase": "2026-02-25 14:30:00",
  "avg_purchase_value": 9000
}
```

### POST `/customers.php?action=create`
Create a new customer.

**Request:**
```json
{
  "name": "Dilshan Bandara",
  "email": "dilshan.b@example.lk",
  "phone": "076-4445555",
  "address": "123 Main Street",
  "city": "Colombo",
  "postal_code": "00700",
  "birthday": "1992-12-15"
}
```

### PUT `/customers.php?action=update`
Update customer information.

**Query Parameters:**
- `id`: Customer ID

---

## Transaction Endpoints

### POST `/transactions.php?action=create`
Create a new transaction (sale).

**Request:**
```json
{
  "date": "2026-03-11 14:30:00",
  "customer_id": 101,
  "cashier_id": "admin",
  "total_amount": 10000,
  "discount_amount": 0,
  "final_amount": 10000,
  "payment_method": "cash",
  "status": "completed",
  "notes": "Optional notes",
  "items": [
    {
      "product_id": 1,
      "variation_id": "1-1",
      "quantity": 1,
      "unit_price": 8500,
      "discount_amount": 0,
      "line_total": 8500
    }
  ]
}
```

**Response:**
```json
{
  "success": true,
  "transaction_id": "INV-1234567890"
}
```

### GET `/transactions.php?action=get`
Get transaction details.

**Query Parameters:**
- `id`: Transaction ID

**Response:**
```json
{
  "id": "INV-1001",
  "transaction_date": "2026-02-27 10:30:00",
  "customer_id": 101,
  "cashier_id": "cashier1",
  "total_amount": 13500,
  "discount_amount": 0,
  "final_amount": 13500,
  "payment_method": "Card",
  "status": "completed",
  "items": [
    {
      "id": 1,
      "transaction_id": "INV-1001",
      "product_id": 1,
      "product_name": "Handloom Cotton Saree",
      "quantity": 1,
      "unit_price": 8500,
      "barcode": "20260101",
      "line_total": 8500
    }
  ]
}
```

### GET `/transactions.php?action=get_all`
Get all transactions with filters.

**Query Parameters:**
- `start_date` (optional): YYYY-MM-DD
- `end_date` (optional): YYYY-MM-DD
- `status` (optional): completed, pending, cancelled, returned
- `customer_id` (optional): Filter by customer

### GET `/transactions.php?action=sales_stats`
Get sales statistics.

**Query Parameters:**
- `start_date` (optional): YYYY-MM-DD
- `end_date` (optional): YYYY-MM-DD

**Response:**
```json
{
  "total_transactions": 12,
  "total_sales": 125000,
  "average_sale": 10417,
  "returned_orders": 1
}
```

---

## Supplier Endpoints

### GET `/suppliers.php?action=get_all`
Get all suppliers.

### GET `/suppliers.php?action=get`
Get specific supplier.

**Query Parameters:**
- `id`: Supplier ID

### POST `/suppliers.php?action=create`
Create a new supplier.

**Request:**
```json
{
  "name": "LankaLooms Pvt Ltd",
  "contact_person": "Mr. Perera",
  "phone": "011-2345678",
  "email": "orders@lankalooms.lk",
  "address": "No. 45, Handloom Road",
  "city": "Kurunegala",
  "postal_code": "60000"
}
```

### POST `/suppliers.php?action=create_payment`
Record a supplier payment.

**Request:**
```json
{
  "supplier_id": 1,
  "total_bill": 150000,
  "paid_amount": 150000,
  "due_amount": 0,
  "payment_date": "2026-02-15",
  "payment_method": "bank_transfer",
  "reference": "REF-001",
  "invoice_ref": "INV-SUP-001",
  "notes": "Paid for goods"
}
```

### GET `/suppliers.php?action=payments`
Get supplier payments.

**Query Parameters:**
- `supplier_id`: Supplier ID

### GET `/suppliers.php?action=balance`
Get supplier balance.

**Query Parameters:**
- `supplier_id`: Supplier ID

---

## Expense Endpoints

### GET `/expenses.php?action=get_all`
Get all expenses.

**Query Parameters:**
- `start_date` (optional): YYYY-MM-DD
- `end_date` (optional): YYYY-MM-DD
- `category` (optional): Filter by category

### POST `/expenses.php?action=create`
Create a new expense.

**Request:**
```json
{
  "category": "Rent",
  "amount": 75000,
  "expense_date": "2026-03-01",
  "description": "Shop Rent - March",
  "payed_by": "admin",
  "receipt_file": "receipt.pdf"
}
```

### PUT `/expenses.php?action=update`
Update expense.

**Query Parameters:**
- `id`: Expense ID

### GET `/expenses.php?action=stats`
Get expense statistics.

**Query Parameters:**
- `start_date` (optional): YYYY-MM-DD
- `end_date` (optional): YYYY-MM-DD

**Response:**
```json
[
  {
    "category": "Rent",
    "count": 1,
    "total": 75000
  },
  {
    "category": "Electricity Bill",
    "count": 1,
    "total": 12500
  }
]
```

### GET `/expenses.php?action=total`
Get total expenses for period.

**Query Parameters:**
- `start_date` (optional): YYYY-MM-DD
- `end_date` (optional): YYYY-MM-DD

---

## Promotion Endpoints

### GET `/promotions.php?action=get_all`
Get all promotions.

**Response:**
```json
[
  {
    "id": "p1",
    "name": "Avurudu Sale",
    "type": "seasonal",
    "discount_type": "percentage",
    "discount_value": 15,
    "start_date": "2026-03-01",
    "end_date": "2026-04-15",
    "is_active": true,
    "description": "15% off on Sarees and Sarongs",
    "applicable_products": [
      { "product_id": 1, "name": "Handloom Cotton Saree" }
    ]
  }
]
```

### GET `/promotions.php?action=active`
Get active promotions (within date range).

### GET `/promotions.php?action=get`
Get specific promotion.

**Query Parameters:**
- `id`: Promotion ID

### POST `/promotions.php?action=create`
Create a new promotion.

**Request:**
```json
{
  "name": "Avurudu Sale",
  "type": "seasonal",
  "discount_type": "percentage",
  "discount_value": 15,
  "start_date": "2026-03-01",
  "end_date": "2026-04-15",
  "is_active": true,
  "description": "15% off on Sarees",
  "applicable_products": [1, 2, 3]
}
```

### GET `/promotions.php?action=get_discount`
Calculate applicable discount for a product.

**Query Parameters:**
- `product_id`: Product ID
- `quantity` (optional): Item quantity
- `total_amount`: Item total amount

**Response:**
```json
{
  "discount_amount": 1500
}
```

---

## HTTP Status Codes

- `200` - OK (successful GET/POST/PUT)
- `201` - Created (successful resource creation)
- `400` - Bad Request (invalid parameters)
- `404` - Not Found (resource doesn't exist)
- `500` - Server Error (database/internal error)

---

## Error Handling

All endpoints return error messages in the following format:

```json
{
  "error": "Description of what went wrong"
}
```

---

## Security Considerations

⚠️ **Important for Production:**

1. **Authentication**: Implement JWT tokens for API authentication
2. **Rate Limiting**: Add rate limiting to prevent abuse
3. **Input Validation**: All inputs should be validated on the server
4. **SQL Injection**: User PreparedStatements are already used
5. **CORS**: Restrict to specific domains instead of `*`
6. **HTTPS**: Always use HTTPS in production
7. **Database**: Use strong passwords and principle of least privilege

---

## Example Frontend Integration

```javascript
const API_BASE = 'http://localhost/Noahvelle%20POS/backend/api/';

class POSApi {
  static async login(userId, pin) {
    return this._post('auth.php?action=login', { id: userId, pin });
  }

  static async getProducts() {
    return this._get('products.php?action=get_all');
  }

  static async getCustomers() {
    return this._get('customers.php?action=get_all');
  }

  static async createTransaction(transactionData) {
    return this._post('transactions.php?action=create', transactionData);
  }

  static async _get(endpoint) {
    const response = await fetch(API_BASE + endpoint);
    return await response.json();
  }

  static async _post(endpoint, data) {
    const response = await fetch(API_BASE + endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    });
    return await response.json();
  }
}

// Usage
const user = await POSApi.login('admin', '1234');
const products = await POSApi.getProducts();
```

---

## Changelog

### v1.0.0 (2026-03-11)
- Initial release
- All core modules implemented
- Product catalog with variations
- Customer management with loyalty points
- Sales transactions with items
- Supplier management with payment tracking
- Expense tracking by category
- Promotion system with multiple types
