# FaceML Backend API

A Node.js/Express backend API for the FaceML Attendance System with MySQL database.

## Features

- **Multi-tenant Architecture**: Superadmin → Shop Admin → Branches → Staff
- **JWT Authentication**: Secure token-based authentication
- **Role-based Access Control**: Superadmin and Shop Admin roles
- **Complete CRUD Operations**: For shops, branches, staff, and attendance
- **Attendance Tracking**: Clock in/out, manual attendance, reports

## Prerequisites

- Node.js (v14 or higher)
- MySQL (v5.7 or higher)
- npm or yarn

## Installation

1. **Navigate to backend directory:**
   ```bash
   cd backend
   ```

2. **Install dependencies:**
   ```bash
   npm install
   ```

3. **Configure environment:**
   ```bash
   cp .env.example .env
   ```
   
   Then edit `.env` with your MySQL credentials:
   ```
   DB_HOST=localhost
   DB_USER=root
   DB_PASSWORD=your_password
   DB_NAME=faceml_db
   JWT_SECRET=your_secret_key
   ```

4. **Initialize database:**
   ```bash
   npm run init-db
   ```

   This will create all necessary tables and a default superadmin account.

## Running the Server

**Development mode (with auto-reload):**
```bash
npm run dev
```

**Production mode:**
```bash
npm start
```

The server will start on `http://localhost:3000`

## Default Credentials

After initializing the database:

- **Email:** admin@faceml.com
- **Password:** Admin@123

⚠️ **Important:** Change the default password after first login!

## API Endpoints

### Authentication
- `POST /api/auth/login` - User login
- `GET /api/auth/profile` - Get current user profile
- `POST /api/auth/change-password` - Change password

### Shop Admins (Superadmin only)
- `POST /api/shop-admins` - Create shop admin
- `GET /api/shop-admins` - Get all shop admins
- `PUT /api/shop-admins/:id` - Update shop admin
- `DELETE /api/shop-admins/:id` - Delete shop admin

### Branches (Shop Admin only)
- `POST /api/branches` - Create branch
- `GET /api/branches/shop/:shop_id` - Get branches by shop
- `GET /api/branches/:id` - Get single branch
- `PUT /api/branches/:id` - Update branch
- `DELETE /api/branches/:id` - Delete branch

### Staff (Shop Admin only)
- `POST /api/staff` - Create staff
- `GET /api/staff/branch/:branch_id` - Get staff by branch
- `GET /api/staff/:id` - Get single staff
- `PUT /api/staff/:id` - Update staff
- `DELETE /api/staff/:id` - Delete staff
- `PUT /api/staff/:id/face-embeddings` - Update face embeddings

### Attendance (Shop Admin only)
- `POST /api/attendance/clock-in` - Clock in
- `POST /api/attendance/clock-out` - Clock out
- `POST /api/attendance/manual` - Mark manual attendance
- `GET /api/attendance/branch/:branch_id` - Get attendance by branch
- `GET /api/attendance/staff/:staff_id` - Get staff attendance
- `GET /api/attendance/branch/:branch_id/summary` - Get attendance summary

## API Usage Examples

### Login
```bash
curl -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "admin@faceml.com",
    "password": "Admin@123"
  }'
```

### Create Shop Admin
```bash
curl -X POST http://localhost:3000/api/shop-admins \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{
    "email": "shop1@example.com",
    "password": "password123",
    "full_name": "Shop 1 Admin",
    "shop_name": "Shop 1",
    "shop_address": "123 Main St",
    "contact_phone": "1234567890"
  }'
```

### Create Branch
```bash
curl -X POST http://localhost:3000/api/branches \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{
    "shop_id": 1,
    "name": "Branch 1",
    "address": "456 Branch St"
  }'
```

### Create Staff
```bash
curl -X POST http://localhost:3000/api/staff \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{
    "branch_id": 1,
    "staff_code": "EMP001",
    "full_name": "John Doe",
    "email": "john@example.com",
    "position": "Cashier"
  }'
```

### Clock In
```bash
curl -X POST http://localhost:3000/api/attendance/clock-in \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{
    "staff_id": 1,
    "branch_id": 1,
    "location": "Branch Office"
  }'
```

## Database Schema

### Tables
- `users` - User accounts (superadmin, shop_admin)
- `shops` - Shop information
- `branches` - Branch information
- `staff` - Staff members
- `attendance` - Attendance records
- `work_sessions` - Detailed work session tracking

## Security

- Passwords are hashed using bcrypt
- JWT tokens for authentication
- Role-based access control
- SQL injection prevention using parameterized queries
- CORS enabled for cross-origin requests

## Error Handling

All API responses follow a consistent format:

**Success:**
```json
{
  "message": "Success message",
  "data": { }
}
```

**Error:**
```json
{
  "error": "Error message"
}
```

## Development

**Run with auto-reload:**
```bash
npm run dev
```

**Check database connection:**
```bash
node -e "require('./config/database')"
```

## Troubleshooting

### Database connection failed
- Check MySQL is running
- Verify credentials in `.env`
- Ensure database exists

### JWT token errors
- Check JWT_SECRET is set in `.env`
- Verify token is included in Authorization header

### Permission errors
- Ensure user has correct role
- Check token is valid and not expired

## License

MIT

