# Noahvelle POS Backend - Installation & Setup Guide

## Prerequisites
- XAMPP (Apache + MySQL + PHP 7.4+)
- Windows environment (as per your workspace)

## Installation Steps

### 1. Database Setup

**Option A: Using phpMyAdmin (Easiest)**
1. Open XAMPP Control Panel
2. Start Apache and MySQL
3. Go to `http://localhost/phpmyadmin`
4. Create a new database named: `noahvelle_pos`
5. Select the database
6. Go to "Import" tab
7. Browse and select: `backend/sql/schema.sql`
8. Click "Go" to execute

**Option B: Using MySQL Command Line**
```bash
mysql -u root -p
CREATE DATABASE noahvelle_pos;
USE noahvelle_pos;
SOURCE C:/xampp/htdocs/Noahvelle\ POS/backend/sql/schema.sql;
```

### 2. Configure Database Connection

Edit `backend/config/database.php`:
```php
define('DB_HOST', 'localhost');      // Your host (usually localhost)
define('DB_USER', 'root');           // MySQL username
define('DB_PASS', '');               // MySQL password (usually empty for XAMPP)
define('DB_NAME', 'noahvelle_pos');  // Database name
```

### 3. Create Logs Directory

Create a folder: `backend/logs/` (for error logging)

### 4. Set Permissions

Ensure `backend/logs/` folder is writable by the web server.

### 5. Test Installation

Access the API:
```
http://localhost/Noahvelle%20POS/backend/api/auth.php?action=get_all
```

You should see an empty JSON array `[]` if setup is correct.

## Default Users (Pre-loaded)

| User ID  | Name          | Role    | PIN  |
|----------|---------------|---------|------|
| admin    | Kamal Perera  | admin   | 1234 |
| cashier1 | Nimali Silva  | cashier | 0000 |
| cashier2 | Sunil Bandara | cashier | 1111 |

## Backend File Structure

```
backend/
├── api/                    # API endpoint files
│   ├── auth.php           # User authentication
│   ├── products.php       # Product endpoints
│   ├── customers.php      # Customer endpoints
│   ├── transactions.php   # Transaction/Sales endpoints
│   ├── suppliers.php      # Supplier endpoints
│   ├── expenses.php       # Expense endpoints
│   └── promotions.php     # Promotion endpoints
├── models/                # Database models
│   ├── User.php
│   ├── Product.php
│   ├── Customer.php
│   ├── Transaction.php
│   ├── Supplier.php
│   ├── Expense.php
│   └── Promotion.php
├── config/
│   ├── database.php       # Database configuration
│   └── Database.php       # Database connection class
├── includes/
│   └── cors.php           # CORS headers
├── sql/
│   └── schema.sql         # Database schema
├── logs/                  # Error logs (create this folder)
└── README.md             # This file
```

## Database Tables

- **users** - Administrators and cashiers
- **customers** - Customer records with loyalty points
- **categories** - Product categories
- **products** - Product information
- **products_variations** - Product sizes, colors, SKUs, barcodes
- **suppliers** - Supplier information
- **supplier_payments** - Supplier payment tracking
- **transactions** - Sales invoices
- **transaction_items** - Items in each transaction
- **credit_notes** - Refund credit notes
- **returns** - Return records
- **expenses** - Business expenses
- **promotions** - Discount promotions
- **promotion_products** - Applicable products per promotion
- **customer_loyalty** - Loyalty points history

## Testing the API

Use Postman or similar tool to test:

### Login
```
POST: http://localhost/Noahvelle%20POS/backend/api/auth.php?action=login
Body (JSON):
{
  "id": "admin",
  "pin": "1234"
}
```

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

### Create Transaction
```
POST: http://localhost/Noahvelle%20POS/backend/api/transactions.php?action=create
Body (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",
  "items": [
    {
      "product_id": 1,
      "variation_id": "1-1",
      "quantity": 1,
      "unit_price": 8500,
      "discount_amount": 0,
      "line_total": 8500
    }
  ]
}
```

## Important Notes

1. **Passwords**: Default user PINs are hashed with MD5. For production, update the User model to use bcrypt.

2. **CORS**: The backend allows all origins (`*`). For production, restrict to your frontend domain:
   ```php
   header("Access-Control-Allow-Origin: http://yourfrontend.com");
   ```

3. **Security**: 
   - Never commit database credentials in production
   - Use environment variables for sensitive data
   - Implement proper JWT-based authentication
   - Add input validation and SQL injection prevention

4. **Transaction Atomicity**: All transaction operations use database transactions to ensure data integrity.

5. **Stock Management**: Stock is automatically updated when transactions are created.

6. **Loyalty Points**: Customers earn 1 point per 100 LKR spent.

## Connecting Frontend to Backend

Update your JavaScript API calls to point to the backend:

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

// Login example
async function login(userId, pin) {
  const response = await fetch(`${API_BASE_URL}auth.php?action=login`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ id: userId, pin: pin })
  });
  return await response.json();
}

// Get products example
async function getProducts() {
  const response = await fetch(`${API_BASE_URL}products.php?action=get_all`);
  return await response.json();
}
```

## Troubleshooting

### "Database Connection Failed"
- Check if MySQL is running in XAMPP
- Verify DB_HOST, DB_USER, DB_PASS in config/database.php
- Ensure database `noahvelle_pos` exists

### "Access Denied" on API calls
- Check CORS headers
- Ensure "Access-Control-Allow-Origin" is set correctly
- Check browser console for CORS errors

### Data not persisting
- Verify database connection is successful
- Check if tables were created properly
- Ensure MySQL credentials in config are correct

## Support

For issues or improvements, check:
1. backend/logs/error.log for detailed errors
2. Browser console (F12) for frontend errors
3. MySQL logs for database errors
