# FaceLogX Backend API Documentation

## Overview

FaceLogX is a facial recognition-based attendance system built with Node.js, Express, and MySQL. This document provides comprehensive information about the backend API, setup, and usage.

## Table of Contents

1. [Installation](#installation)
2. [Configuration](#configuration)
3. [Running the Server](#running-the-server)
4. [API Documentation](#api-documentation)
5. [Authentication](#authentication)
6. [Error Handling](#error-handling)
7. [Database Schema](#database-schema)
8. [Deployment](#deployment)
9. [Troubleshooting](#troubleshooting)

## Installation

### Prerequisites

- Node.js v14+ 
- MySQL 5.7+ or MariaDB
- Python 3.7+ (for face recognition)

### Setup Steps

1. **Clone and navigate to server directory:**
```bash
cd server
```

2. **Install dependencies:**
```bash
npm install
```

3. **Create `.env` file:**
```bash
cp .env.example .env
```

4. **Configure environment variables:**
Edit `.env` with your settings:
```
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=your_password
DB_NAME=facelogx
DB_PORT=3306
JWT_SECRET=your_secret_key_here
PORT=5000
NODE_ENV=development
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173
FACELOGX_PYTHON_CMD=python
```

5. **Initialize database:**
```bash
node seed.js
```

## Configuration

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `DB_HOST` | MySQL host | localhost |
| `DB_USER` | MySQL user | root |
| `DB_PASSWORD` | MySQL password | (empty) |
| `DB_NAME` | Database name | facelogx |
| `DB_PORT` | MySQL port | 3306 |
| `JWT_SECRET` | JWT signing secret | (required) |
| `PORT` | API server port | 5000 |
| `NODE_ENV` | Environment | development |
| `ALLOWED_ORIGINS` | CORS allowed origins | (comma-separated) |
| `FACELOGX_PYTHON_CMD` | Python executable path | python |
| `FACELOGX_MIN_RECOGNITION_CONFIDENCE` | Minimum confidence required for Pi-recognized faces to be accepted for attendance | 0.55 |

## Running the Server

### Development Mode

With file watching and auto-reload:
```bash
npm run dev
```

### Production Mode

```bash
npm start
```

## API Documentation

### Base URL

```
http://localhost:5000/api
```

### Quick Reference

Access API documentation at:
```
GET /api/status/api-docs
```

### Authentication

#### Bearer Token (User Authentication)

Include in all authenticated requests:
```
Authorization: Bearer <token>
```

#### API Key (Pi Device Authentication)

Include for Raspberry Pi endpoints:
```
X-API-Key: <api-key>
```

### Main Endpoints

#### Authentication (`/auth`)
- `POST /login` - User login
- `POST /register` - Student registration
- `POST /change-password` - Change user password
- `POST /request-password-reset` - Request password reset
- `POST /reset-password` - Reset password with token
- `GET /me` - Get current user info

#### Students (`/students`)
- `GET /` - List students (with optional folder filter)
- `GET /:id` - Get student details
- `POST /` - Create student (admin only)
- `PUT /:id` - Update student
- `DELETE /:id` - Delete student (admin only)

#### Attendance (`/attendance`)
- `GET /` - Get attendance records
- `GET /today` - Get today's attendance
- `GET /sessions` - List attendance sessions
- `GET /stats` - Get statistics
- `GET /student-stats/:id` - Get student stats
- `POST /session` - Create/manage attendance session
- `PUT /override` - Manually override attendance

#### Payments (`/payments`)
- `GET /` - Get payment records
- `GET /student-summary/:id` - Get student fine summary
- `POST /` - Record payment
- `GET /total-collected` - Get total collected

#### Face Recognition (`/face-recognition`)
- `POST /register-pi` - Register Raspberry Pi (admin only)
- `GET /pi-devices` - List Pi devices (admin only)
- `POST /encode` - Store face encoding
- `POST /encode-from-image` - Extract encoding from image
- `GET /encodings` - Get all encodings (Pi auth)
- `POST /recognize` - Recognize face (Pi auth)
- `POST /heartbeat` - Pi heartbeat (Pi auth)
- `GET /logs` - Get recognition logs
- `GET /stats` - Get recognition stats

#### System (`/status`)
- `GET /` - System health and statistics
- `GET /health` - Simple health check
- `GET /api-docs` - API documentation

## Authentication

### User Authentication Flow

1. **Login:**
```bash
POST /api/auth/login
{
  "identifier": "admin@facelogx.com",  // or student ID
  "password": "password123"
}
```

Response:
```json
{
  "token": "eyJhbGciOiJIUzI1NiIs...",
  "role": "admin",  // or "student"
  "user": {
    "id": "1",
    "name": "Admin User",
    "email": "admin@facelogx.com"
  }
}
```

2. **Use Token:**
Include token in subsequent requests:
```
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
```

3. **Token Expiration:**
Tokens expire after 24 hours. User must log in again to get a new token.

### Raspberry Pi Authentication

1. **Register Device:**
```bash
POST /api/face-recognition/register-pi
Authorization: Bearer <admin-token>
{
  "device_name": "Entrance Camera 1",
  "ip_address": "192.168.1.100"
}
```

Response:
```json
{
  "api_key": "abc123def456...",
  "message": "Pi device registered successfully"
}
```

2. **Use API Key:**
Include API key in Pi requests:
```
X-API-Key: abc123def456...
```

## Error Handling

### Error Response Format

All errors follow this format:
```json
{
  "error": "Error message describing what went wrong"
}
```

### HTTP Status Codes

| Code | Meaning | Example |
|------|---------|---------|
| 200 | OK | Successful request |
| 201 | Created | Resource created |
| 400 | Bad Request | Invalid input parameters |
| 401 | Unauthorized | Missing or invalid token |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource doesn't exist |
| 409 | Conflict | Duplicate entry |
| 500 | Server Error | Internal server error |

### Common Errors

**Missing Authentication:**
```json
{
  "error": "Access denied"
}
```

**Invalid Token:**
```json
{
  "error": "Invalid token"
}
```

**Insufficient Permissions:**
```json
{
  "error": "Admin access required"
}
```

**Rate Limited:**
```json
{
  "error": "Too many requests from this IP, please try again later."
}
```

## Database Schema

### Key Tables

#### `admins`
- `id` (INT) - Primary key
- `name` (VARCHAR) - Admin name
- `email` (VARCHAR) - Email address (unique)
- `password` (VARCHAR) - Hashed password
- `created_at` (TIMESTAMP) - Creation time

#### `students`
- `id` (VARCHAR) - Student ID (primary key)
- `first_name` (VARCHAR)
- `last_name` (VARCHAR)
- `email` (VARCHAR) - Email address (unique)
- `phone` (VARCHAR)
- `year_level` (VARCHAR) - 1st/2nd/3rd/4th Year
- `folder_id` (VARCHAR) - Reference to student_folders
- `face_registered` (BOOLEAN) - Face enrollment status
- `password` (VARCHAR) - Hashed password

#### `attendance_records`
- `id` (INT) - Primary key
- `student_id` (VARCHAR) - Foreign key to students
- `date` (DATE)
- `morning` (ENUM: 'Present'/'Absent')
- `afternoon` (ENUM: 'Present'/'Absent')

#### `face_encodings`
- `id` (INT) - Primary key
- `student_id` (VARCHAR) - Foreign key
- `encoding` (TEXT) - JSON array of 128 numbers
- `created_at` (TIMESTAMP)

#### `pi_devices`
- `id` (INT) - Primary key
- `device_name` (VARCHAR) - Device name
- `ip_address` (VARCHAR) - IP address
- `api_key` (VARCHAR) - Unique API key
- `is_active` (BOOLEAN)
- `last_seen` (TIMESTAMP)

## Deployment

### Production Setup

1. **Set environment to production:**
```
NODE_ENV=production
```

2. **Use a process manager (PM2):**
```bash
npm install -g pm2
pm2 start index.js --name "facelogx"
pm2 save
pm2 startup
```

3. **Set up reverse proxy (Nginx):**
```nginx
server {
  listen 80;
  server_name api.facelogx.com;

  location / {
    proxy_pass http://localhost:5000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
  }
}
```

4. **Enable HTTPS:**
Use Let's Encrypt with Certbot for free SSL certificates.

5. **Database backups:**
```bash
mysqldump -u root -p facelogx > backup.sql
```

## Troubleshooting

### Common Issues

**Database Connection Error:**
```
Error: connect ECONNREFUSED 127.0.0.1:3306
```
- Check MySQL is running
- Verify DB credentials in `.env`
- Check database exists

**"Cannot find module" Error:**
```bash
npm install
```

**Port already in use:**
```bash
# Find process on port 5000
lsof -i :5000
# Kill the process
kill -9 <PID>
```

**Python script errors:**
- Verify Python path in `FACELOGX_PYTHON_CMD`
- Check face_recognition library is installed:
```bash
pip install face_recognition
```

### Debug Mode

Enable detailed logging:
```
NODE_ENV=development
```

Check server logs for detailed error messages.

## Support

For issues, questions, or contributions, please refer to the project README.
