# TimeOffice Biometric API — Integration Setup Guide

This document is for the team member responsible for deploying this integration for a new client.
All configuration is done in a single section at the top of `timeoffice-api.php`.

---

## What This Script Does

- Connects to the **TimeOffice API** and pulls biometric punch records for all employees.
- Saves each punch record into the `biometric_punches` table in the client's MSSQL database.
- Uses a local state file (`timeoffice_state.json`) to track the last fetched record so that each run only pulls **new data** (incremental sync).
- Is designed to be run via a **cron job every 5 minutes**.

---

## Step 1 — Configure the Script

Open `timeoffice-api.php` and update the values inside the `Config` block (lines 7–28).

### 1.1 TimeOffice API Credentials

```php
$corporateId = "corporateId";   // Client's Corporate ID from TimeOffice
$username    = "username";      // API username provided by TimeOffice
$password    = "password";      // API password provided by TimeOffice
```

> These three values are provided by the client or the TimeOffice account admin.
> They are combined and Base64-encoded automatically to form the Authorization header:
> `CorporateID:Username:Password:true`

### 1.2 Database Credentials

```php
$serverName   = 'localhost';    // MSSQL server hostname or IP
$uid          = '';             // Database username
$pwd          = '';             // Database password
$databaseName = '';             // Target database name
```

> Use the client's MSSQL connection details. The script uses the `sqlsrv` PHP driver.

---

## Step 2 — Verify the Target Table

Ensure the `biometric_punches` table exists in the target database with at least these columns:

| Column | Type | Notes |
|---|---|---|
| `emp_code` | VARCHAR | Employee code from TimeOffice |
| `log_date` | DATE | Date portion of the punch (YYYY-MM-DD) |
| `punch_time` | TIME | Time portion of the punch (HH:MM:SS) |
| `device_serial_number` | VARCHAR | Hardcoded as `TIMEOFFICE001` |
| `device_name` | VARCHAR | Hardcoded as `TimeOffice` |
| `log_date_time` | DATETIME | Full punch timestamp |
| `created_date` | DATETIME | Row insertion timestamp |

---

## Step 3 — Deploy Files to Apache

The script needs to be placed inside the Apache web root so it can be triggered via a URL.

### 3.1 Copy the Files

On the same server as Apache:

```bash
cp -r /source/path/biometric-timeoffice /var/www/html/biometric-timeoffice
```

If deploying from a remote machine, use `scp`:

```bash
scp -r ./biometric-timeoffice user@your-server-ip:/var/www/html/biometric-timeoffice
```

### 3.2 Set Folder Permissions

The script writes `timeoffice_state.json` to its own directory. Apache's user (`www-data`) must have write permission:

```bash
chown -R www-data:www-data /var/www/html/biometric-timeoffice
chmod -R 755 /var/www/html/biometric-timeoffice
```

> **Warning:** Without write permission, the state file cannot be saved and the script will re-pull all data on every run, causing duplicate inserts.

### 3.3 Verify the URL is Accessible

```bash
curl -I http://your-domain.com/biometric-timeoffice/timeoffice-api.php
```

You should receive an `HTTP/1.1 200 OK` response. If you get a 403 or 404, check the folder path and Apache permissions.

---

## Step 4 — Set Up the Cron Job

Open the crontab editor:

```bash
crontab -e
```

### 4.1 Trigger via wget (Recommended for Apache)

```
*/5 * * * * wget -q -O /var/log/timeoffice.log http://your-domain.com/biometric-timeoffice/timeoffice-api.php 2>&1
```

> `-q` suppresses wget's download progress output.
> `-O /var/log/timeoffice.log` writes the script's output (inserted count, errors) to a log file.
> Replace `your-domain.com` with your actual domain or server IP.

### 4.2 Alternative: Trigger via PHP CLI

If you prefer not to use a public URL:

```
*/5 * * * * php /var/www/html/biometric-timeoffice/timeoffice-api.php >> /var/log/timeoffice.log 2>&1
```

> Both approaches produce identical results. The `wget` method is preferred when running on Apache as it goes through the same execution environment as a normal web request.

---

## Step 5 — First Run

On the first run, there is **no state file** yet. The script will default to pulling from the start of the current month.

Trigger manually once to verify:

```bash
wget -q -O - http://your-domain.com/biometric-timeoffice/timeoffice-api.php
```

Expected output on success:
```
State updated — next LastRecord: 032026$489
Done. Inserted: 150 | Failed: 0
```

If there is an error, the output will show either:
- `DB Connection failed.` — check database credentials (Step 1.2)
- `API returned error: ...` — check API credentials (Step 1.1)
- `cURL Error: ...` — check network/firewall access to `api.etimeoffice.com`
- `HTTP 403 / 404` — check Apache folder path and permissions (Step 3.2 & 3.3)
- State file not updating — Apache user lacks write permission on the folder, re-run Step 3.2

---

## State File

The file `timeoffice_state.json` is created automatically after the first successful run in the same directory as the script. It looks like:

```json
{
    "last_record": "032026$489"
}
```

**Do not delete this file** once the integration is live — deleting it will cause the next run to re-pull from the start of the current month, resulting in duplicate inserts.

If you need to **re-sync from a specific point**, edit `last_record` manually using the format `MMYYYY$LastID` (e.g., `012026$1` to re-pull from January 2026).

---

## Summary Checklist

- [ ] Set `$corporateId`, `$username`, `$password` from the client's TimeOffice account
- [ ] Set `$serverName`, `$uid`, `$pwd`, `$databaseName` for the client's MSSQL database
- [ ] Confirm `biometric_punches` table exists with the correct columns
- [ ] Copy files to `/var/www/html/biometric-timeoffice/` on the Apache server
- [ ] Set folder ownership and permissions (`chown` / `chmod`)
- [ ] Verify the script URL returns HTTP 200
- [ ] Run the script manually via `wget` and confirm records are inserted
- [ ] Add the cron job with the `wget` entry
