# Noahvelle POS Backend - Quick Start Guide

## 🚀 5-Minute Setup

### Step 1: Start XAMPP Services
1. Open XAMPP Control Panel
2. Click **Start** next to Apache
3. Click **Start** next to MySQL
4. Wait for both to show "Running" ✅

### Step 2: Create Database (Fastest Way)
1. Go to `http://localhost/phpmyadmin`
2. Click **Databases**
3. Create new database: `noahvelle_pos`
4. Go to **Import** tab
5. Upload file: `backend/sql/schema.sql`
6. Click **Go**
7. Wait for "Import has been executed successfully" message ✅

### Step 3: Verify Installation
Open in browser:
```
http://localhost/Noahvelle%20POS/backend/
```

You should see JSON with API endpoint information ✅

## 📚 Test the API

### Login (Using Postman or similar)
```
Method: POST
URL: http://localhost/Noahvelle%20POS/backend/api/auth.php?action=login

Body (raw JSON):
{
  "id": "admin",
  "pin": "1234"
}

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

### Get All Products
```
Method: GET
URL: http://localhost/Noahvelle%20POS/backend/api/products.php?action=get_all

Response: Array of products with variations
```

### Create a Sale
```
Method: POST
URL: http://localhost/Noahvelle%20POS/backend/api/transactions.php?action=create

Body (raw JSON):
{
  "date": "2026-03-11 14:30:00",
  "customer_id": 101,
  "cashier_id": "admin",
  "total_amount": 8500,
  "discount_amount": 0,
  "final_amount": 8500,
  "payment_method": "cash",
  "status": "completed",
  "items": [
    {
      "product_id": 1,
      "variation_id": "1-1",
      "quantity": 1,
      "unit_price": 8500,
      "discount_amount": 0,
      "line_total": 8500
    }
  ]
}

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

## 🔗 Connect Frontend to Backend

### In Your React App:

1. Copy the `API_INTEGRATION.js` file or include it in your project
2. Use in components like this:

```javascript
// Login
const result = await POSApiService.login('admin', '1234');

// Load Products
const products = await POSApiService.getAllProducts();

// Create Transaction
await POSApiService.createTransaction({
  date: new Date().toISOString().slice(0, 19).replace('T', ' '),
  customer_id: null,
  cashier_id: 'admin',
  total_amount: 10000,
  discount_amount: 0,
  final_amount: 10000,
  payment_method: 'cash',
  status: 'completed',
  items: [...]
});
```

## 📁 Directory Structure Overview

```
backend/
├── api/                    # API Endpoints
│   ├── auth.php           # Login/Authentication
│   ├── products.php       # Products & Inventory
│   ├── customers.php      # Customer Management
│   ├── transactions.php   # Sales/Invoices
│   ├── suppliers.php      # Supplier Management
│   ├── expenses.php       # Expense Tracking
│   └── promotions.php     # Promotions & Discounts
├── models/                # Database Classes
│   ├── User.php
│   ├── Product.php
│   ├── Customer.php
│   ├── Transaction.php
│   ├── Supplier.php
│   ├── Expense.php
│   └── Promotion.php
├── config/
│   ├── database.php       # Settings
│   └── Database.php       # Connection Class
├── includes/
│   ├── cors.php           # CORS Headers
│   └── POSHelper.php      # Helper Functions
├── sql/
│   └── schema.sql         # Database Schema
├── logs/                  # Error Logs (created on first error)
├── README.md              # Full API Documentation
├── SETUP.md               # Detailed Setup Guide
├── API_INTEGRATION.js     # Frontend Integration Guide
└── index.php              # API Info Page
```

## 🔑 Default Users

| User ID  | PIN  | Role    |
|----------|------|---------|
| admin    | 1234 | Admin   |
| cashier1 | 0000 | Cashier |
| cashier2 | 1111 | Cashier |

## 📊 Sample Data Included

✅ Products (6 items with variations)
✅ Customers (5 customers with loyalty data)
✅ Suppliers (3 suppliers)
✅ Categories (5 categories)
✅ Users (3 users with different roles)

## ⚡ Next Steps

1. **Test APIs** - Use Postman to test all endpoints
2. **Integrate Frontend** - Use `API_INTEGRATION.js` in your React app
3. **Load Test Data** - APIs are pre-populated with sample data from mockData.js
4. **Customize** - Update database config for production environment

## 🐛 Troubleshooting

### "Database Connection Failed"
- ✅ Check MySQL is running in XAMPP
- ✅ Verify credentials in `backend/config/database.php`
- ✅ Ensure database `noahvelle_pos` exists

### No data returned from API
- ✅ Check if database schema was imported correctly
- ✅ Check browser console and backend/logs/error.log for errors
- ✅ Verify table names in `backend/sql/schema.sql`

### CORS errors in browser
- ✅ CORS is already enabled in all API endpoints
- ✅ Check `api/*/action=*` endpoints have CORS headers

### ModRewrite errors
- ✅ ModRewrite is optional (APIs work without it)
- ✅ If you want clean URLs, ensure Apache has mod_rewrite enabled

## 📖 Full Documentation

- **Setup Details**: `backend/SETUP.md`
- **API Reference**: `backend/README.md`
- **Frontend Integration**: `backend/API_INTEGRATION.js`

## 🎯 API Endpoints Summary

| Module      | GET | POST | PUT | DELETE |
|-------------|-----|------|-----|--------|
| Auth        | ✓   | ✓    | -   | -      |
| Products    | ✓   | ✓    | ✓   | -      |
| Customers   | ✓   | ✓    | ✓   | -      |
| Transactions| ✓   | ✓    | -   | -      |
| Suppliers   | ✓   | ✓    | -   | -      |
| Expenses    | ✓   | ✓    | ✓   | -      |
| Promotions  | ✓   | ✓    | -   | -      |

## 🔐 Security Notes

⚠️ **Before Production:**
- Change database password
- Use stronger PIN hashing (bcrypt not MD5)
- Implement JWT tokens
- Restrict CORS to your domain
- Add input validation
- Use HTTPS only

## 💡 Pro Tips

1. **Test with Postman**: Download Postman for easy API testing
2. **Check Error Logs**: View `backend/logs/error.log` for debugging
3. **Use Transaction ID**: Save transaction IDs for refunds/returns
4. **Loyalty Points**: Auto-calculated at 1 point per 100 LKR
5. **Stock Updates**: Automatically updated when transactions are created

---

**Need Help?** Check `backend/README.md` for complete API documentation.

**Ready to Deploy?** See `backend/SETUP.md` for production configuration.
