Not logged in

Overview

A PHP + MySQL JSON API. Login returns a signed token (JWT, HS256) which is sent on later requests in the Authorization header. Every response is JSON.

Base URL http://localhost/Long_Term_Project/Horlicks_School_Tribes/API/
Content type Send requests as application/x-www-form-urlencoded or application/json. Responses are application/json.
Timezone Asia/Kolkata (IST, +05:30), configurable in .env
CORS Controlled by CORS_ALLOWED_ORIGIN in .env. OPTIONS preflight requests return 200.
Adjust the base URL to match your server (for example a Laragon .test domain). The bar above is also the Try it console: log in under Login and the token is kept for every other Try it panel on this page. Panels send real requests, so create, update and disable actions change real data.

Authentication

Call Login to get a token, then send it on every protected request:

Authorization: Bearer <token>

A protected endpoint returns 401 in this format when authentication fails:

{
  "Authentication": false,
  "Message": "Invalid Credentials"
}
Message Meaning
Authorization token is required in the Authorization header No Bearer token was sent.
Invalid token format The token is malformed or uses an unsupported algorithm.
This Session is Expired or Invalid Token Signature mismatch, usually because the user logged in elsewhere or logged out.
Session has expired The token's expiry time has passed.
Invalid Credentials The user is inactive, has no active session, or the token does not belong to them.

Errors & status codes

Code Meaning
200 Success
400 Missing or invalid input
401 Wrong credentials, or missing/invalid/expired token
403 Forbidden (for example setup.php when disabled)
405 Unsupported method or action
429 Too many login attempts
500 Server or database error (details are in logs/, never in the response)

Error bodies from auth.php look like { "Status": false, "Message": "..." }.

Rate limiting

Login is limited per IP address: 3 failed attempts within 60 seconds blocks that IP for 120 seconds. A successful login resets the counter. While blocked, login returns 429 with the seconds remaining. If the API runs behind a proxy you control, set TRUST_PROXY=true so the real client IP is used.

Endpoints

Login

POST/auth.php

Checks the username and password, and issues a new token. Any earlier session for the user is signed out.

Field Type Required Description
username string Yes The user's Username (for example EMP001)
password string Yes The user's password
curl -X POST "http://localhost/Long_Term_Project/Horlicks_School_Tribes/API/auth.php" \
  -d "username=EMP001" \
  -d "password=your-password"
const res = await fetch(`${BASE_URL}/auth.php`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ username: "EMP001", password: "your-password" }),
});
const data = await res.json();
if (data.Status) localStorage.setItem("token", data.Token);
200 Success
{
  "Status": true,
  "Message": "Logged in successfully for user EMP001",
  "Token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.…",
  "Username": "EMP001",
  "Full_Name": "Pratham Kamble",
  "Role": "Admin"
}
Errors
Status Message When
400 username is required / password is required Field missing or empty
401 Invalid credentials Unknown user, inactive user, or wrong password. Counts toward the rate limit.
429 Too many login attempts. Please try again in N seconds. IP is blocked
500 Login failed due to a server error Database or server problem

Logout

POST/auth.php?do=logout

Ends the current session. The user's stored secret key is cleared, so the token stops working immediately. The username is read from the token, so no other fields are needed.

Input Where Required Description
Authorization: Bearer <token> Header Yes* The token returned by login
token Body Alternative *Only used if the header is absent
curl -X POST "http://localhost/Long_Term_Project/Horlicks_School_Tribes/API/auth.php?do=logout" \
  -H "Authorization: Bearer <token>"
await fetch(`${BASE_URL}/auth.php?do=logout`, {
  method: "POST",
  headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
});
localStorage.removeItem("token");
200 Success
{
  "Status": true,
  "Message": "Logout successful"
}
Errors
Status Response When
400 { "Status": false, "Message": "Token is required" } No token, or it cannot be read
401 { "Status": false, "Authentication": false, "Message": "Invalid Credentials" } Token invalid, expired, or already logged out
500 { "Status": false, "Message": "Error occurred during logout" } Database or server problem
Any other method or do value on auth.php returns 405 with "Invalid request method".

Admin · Users

All user management lives at /Admin/user.php. Admins only: a valid token whose user has the Admin role is required, otherwise the API returns 403 "Access denied. Only Admins can perform this action." Users are never deleted. Disable them instead. Responses never include Password or Secret_Key.

Every user object looks like this:

{
  "Username": "EMP003",
  "Full_Name": "Asha Patil",
  "Role": "Staff",
  "Status": "Active",
  "Has_Session": false,
  "Created_AT": "2026-11-17 11:20:05",
  "Updated_AT": "2026-11-17 11:20:05"
}

Has_Session is true while the user is logged in.

Field rules

Field Rule
username 3-30 characters: letters, numbers, . _ -. Must be unique. Cannot be changed after creation.
full_name 1-20 characters (matches the VARCHAR(20) column)
password 8-72 characters. Stored as a bcrypt hash.
role Admin, Staff or Client
status Active (default on create) or Inactive

Validation failures return 400 with a per-field breakdown:

{
  "Status": false,
  "Message": "Validation failed",
  "Errors": { "password": "Must be 8-72 characters" }
}

List / get users

GET/Admin/user.php

With username it returns that one user. Without it, it returns a filtered, paged list.

Query param Description
username Return only this user (404 if not found)
search Matches part of Username or Full_Name
role Admin, Staff or Client
status Active or Inactive
limit Page size, 1-200 (default 50)
offset Rows to skip (default 0)
curl "BASE/Admin/user.php?status=Active&limit=20" \
  -H "Authorization: Bearer <token>"
200 Success
{
  "Status": true,
  "Total": 2,
  "Limit": 50,
  "Offset": 0,
  "Data": [ { "Username": "EMP001", "Full_Name": "Pratham Kamble", "Role": "Admin", "Status": "Active", "Has_Session": true, "Created_AT": "…", "Updated_AT": "…" } ]
}

A single-user request returns { "Status": true, "Data": { … } }.

Create user

POST/Admin/user.php
Field Required Notes
username Yes
full_name Yes
password Yes
role Yes Admin, Staff or Client
status No Defaults to Active
curl -X POST "BASE/Admin/user.php" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"username":"EMP003","full_name":"Asha Patil","password":"Str0ngPass!","role":"Staff"}'
201 Created
{
  "Status": true,
  "Message": "User created successfully",
  "Data": { "Username": "EMP003", "Full_Name": "Asha Patil", "Role": "Staff", "Status": "Active", "Has_Session": false, "Created_AT": "…", "Updated_AT": "…" }
}
Status When
400 Validation failed (see Errors)
409 Username already exists

Update user

PUT/Admin/user.php

Send username to pick the user, plus only the fields you want to change: full_name, password, role, status. At least one is required.

curl -X PUT "BASE/Admin/user.php" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"username":"EMP003","full_name":"Asha P.","password":"NewPass#2026"}'
200 Success
{
  "Status": true,
  "Message": "User updated successfully",
  "Session_Ended": true,
  "Data": { "Username": "EMP003", "Full_Name": "Asha P.", "Role": "Staff", "Status": "Active", "Has_Session": false, "Created_AT": "…", "Updated_AT": "…" }
}
Status When
400 username is required, validation failed, self-disable or self-demote, or nothing to update
404 User not found

Disable / enable user

PUT/Admin/user.php with status

Disabling is an update that sets status to Inactive. The user is signed out immediately and cannot log in until re-enabled with Active. Their data is kept.

# Disable
curl -X PUT "BASE/Admin/user.php" -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" -d '{"username":"EMP003","status":"Inactive"}'

# Enable
curl -X PUT "BASE/Admin/user.php" -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" -d '{"username":"EMP003","status":"Active"}'

The response is the same as Update user. When disabling, Session_Ended is true.

Admin · Dashboard

GET/Admin/dashboard.php

One call with the numbers for the admin home screen, for the current month or any month you ask for. Admins only (Staff get 403). GET only.

Query param Description
month Optional, YYYY-MM (for example 2026-10). Empty means the current month. Any other format returns 400. A month with no visits returns zeros.
curl "BASE/Admin/dashboard.php?month=2026-10" \
  -H "Authorization: Bearer <admin token>"
200 Success
{
  "Status": true,
  "Month": "2026-11",
  "Total_Unique_Person_Count": 20,
  "Total_Face_Count": 28,
  "Total_Visits": 7,
  "Cities": [
    { "City": "Mumbai", "This_Month_Visits": 4, "Total_Visits": 5 },
    { "City": "Pune",   "This_Month_Visits": 2, "Total_Visits": 3 },
    { "City": "Delhi",  "This_Month_Visits": 1, "Total_Visits": 1 }
  ],
  "Recent_Visits": [
    { "Visit_ID": 7, "Visit_Date": "2026-11-07", "City": "Mumbai", "School_Name": "…", "Total_Face_Count": 7,
      "Normal_Photos": [ … ], "AI_Photos": [ … ], "…": "same visit object as Staff / Create visit" }
  ]
}
Field Meaning
Month The month the numbers are for
Total_Visits Visits completed in that month, by all staff
Total_Unique_Person_Count Sum of each visit's Unique_Person_Count for that month (visits without a count add 0)
Total_Face_Count Sum of the faces detected in each AI photo of that month's visits (a person in several photos is counted each time; failed photos are skipped)
Cities Every city from config.php, including those with 0 visits. This_Month_Visits is the number of visits in the selected month (so it follows month). Total_Visits is all time. The This_Month_Visits values add up to the top Total_Visits.
Recent_Visits The 5 most recent visits of that month (newest visit date first), as full visit objects with their photos (S3 photo links are temporary, see Photo storage). Fewer than 5 when the month has fewer visits.
Targets on the dashboard. The dashboard also returns Targets: every city target with its progress and the overall total, exactly as GET /Admin/target.php returns them. Targets are always "as of today"; the month parameter does not change them.
AI queue on the dashboard. "AI_Queue": { "Pending": 3, "Working": 1, "Done": 120, "Failed": 0 } counts the AI batches in each state (all time). A Pending number that keeps growing means the worker is not running or the counting service is down.
"Targets": {
  "As_Of": "2026-11-25",
  "Overall": { "Target": 4380, "Done": 1291, "Percent_Done": 29.47, "Run_Rate": 35.86, "Needed_Rate": 102.97,
               "Start_Date": "2026-10-21", "Finish_Date": "2026-12-25", "Days_Left": 30,
               "Projected_Finish_Date": "2027-02-20", "Status": "At Risk", "Visits_Total": 1291, "Cities_With_Target": 2, "…": "…" },
  "Cities": [ { "City": "Mumbai", "Target": 4000, "Done": 1206, "Percent_Done": 30.15, "…": "see Targets" } ]
}

Admin · Targets

A visit target per city, for example Mumbai: 4000 visits by 25-12-2026. Endpoint: /Admin/target.php. Admins read and change targets. Clients can only read them (GET, same numbers, without Updated_By / Updated_AT); POST, PUT and DELETE return 403 "Clients can only read targets." Staff get 403. Only cities from VISIT_CITIES in config.php can have a target, one target per city.

Get targets and progress

GET/Admin/target.php optional ?city=Mumbai
{
  "Status": true,
  "As_Of": "2026-11-25",
  "Overall": { "Target": 4380, "Done": 1291, "Remaining": 3089, "Percent_Done": 29.47, "Run_Rate": 35.86,
               "Needed_Rate": 102.97, "Start_Date": "2026-10-21", "Finish_Date": "2026-12-25", "Days_Elapsed": 36,
               "Days_Left": 30, "Projected_Finish_Date": "2027-02-20", "Status": "At Risk",
               "Visits_Total": 1291, "Cities_With_Target": 2 },
  "Cities": [
    { "City": "Mumbai", "Target": 4000, "Done": 1206, "Remaining": 2794, "Percent_Done": 30.15,
      "Run_Rate": 33.5, "Needed_Rate": 93.13, "Start_Date": "2026-10-21", "Finish_Date": "2026-12-25",
      "Days_Elapsed": 36, "Days_Left": 30, "Projected_Finish_Date": "2027-02-17", "Status": "At Risk",
      "Updated_By": "EMP001", "Updated_AT": "2026-11-25 10:15:00" }
  ]
}

With ?city= the response is { "Status": true, "As_Of": "…", "Data": { one city } }, or 404 when that city has no target. Overall is null when no city has a target.

Field Meaning
Target, Done, Remaining Target visits; visits made in the city from Start_Date to today (Rejected visits do not count, Pending and Approved do); what is still left
Percent_Done Done / Target x 100, 2 decimals (e.g. 30.15). Can pass 100.
Run_Rate Visits per day so far: Done / Days_Elapsed (e.g. 34.2 = 34/day). null before the start date.
Needed_Rate Visits per day needed from now to finish on time: Remaining / Days_Left (a finish date of today counts as 1 day). null when done or overdue.
Days_Elapsed Days from Start_Date to today, both included (starting today = 1)
Days_Left Days from today to Finish_Date. Today 25-11-2026 and finish 25-12-2026 = 30. 0 once the date has passed.
Projected_Finish_Date When the target is reached at the current run rate: today + Remaining / Run_Rate days (rounded up). null when completed or nothing done yet.
Status Completed (target reached), Not Started (start date in the future), Overdue (finish date passed, not reached), On Track (projected finish on or before the finish date), At Risk (projected finish after it, or no visits yet)

Overall adds all targets up, from the earliest Start_Date to the latest Finish_Date, with the same fields. In Overall each city counts only up to its own target, so a city that is over its target does not hide another city's shortfall; Visits_Total is the plain number of visits, and Cities_With_Target the number of cities.

Set, change or remove a target

Request Body (JSON or form) Result
POST /Admin/target.php city, target_visits, finish_date required; start_date optional (default today) 201 with the city's progress. 409 if the city already has a target.
PUT /Admin/target.php city plus any of target_visits, start_date, finish_date 200 with the updated progress. 404 if the city has no target.
DELETE /Admin/target.php?city=Mumbai (or city in the body) 200. Visits are not touched. 404 if there was no target.

Rules: target_visits is a whole number from 1 to 1,000,000; dates are YYYY-MM-DD; finish_date must be on or after start_date. Errors return 400 with Errors per field. Who changed a target last is kept in Updated_By, and every change is in the activity log.

curl -X POST "BASE/Admin/target.php" -H "Authorization: Bearer <admin token>" \
  -H "Content-Type: application/json" \
  -d '{"city":"Mumbai","target_visits":4000,"start_date":"2026-10-21","finish_date":"2026-12-25"}'

Staff · Visits

A visit records a school visit: date, city, school name, GPS location and photos. Endpoint: /Staff/visit.php. Available to Staff, Admin and Client users.

Create visit

POST/Staff/visit.php

Send as multipart/form-data (needed for the photo files).

Field Type Required Rules
visit_date text Yes YYYY-MM-DD, a real date, not in the future
city text Yes Must exactly match one of the cities returned in Cities (from config.php)
school_name text Yes 2-150 characters
poc_name text Yes Point of contact at the school, 2-100 characters
poc_contact text Yes Contact number: 7-15 digits, may start with +. Spaces, hyphens, dots and brackets are allowed and removed before saving (+91 98765-43210 is saved as +919876543210).
latitude number Yes -90 to 90
longitude number Yes -180 to 180
normal_photos[] files * Stored only
ai_photos[] files * Stored and counted together by the unique-count service. JPG, PNG or WEBP only.

*At least one photo in total is required (either list may be empty). Normal photos may be JPG, PNG, WEBP or BMP; AI photos must be JPG, PNG or WEBP (the counting service cannot read BMP). Each photo can be up to MAX_PHOTO_MB MB, and each list is limited to MAX_PHOTOS_PER_TYPE photos (see .env).

curl -X POST "BASE/Staff/visit.php" \
  -H "Authorization: Bearer <token>" \
  -F "visit_date=2026-11-17" \
  -F "city=Mumbai" \
  -F "school_name=Sunrise Public School" \
  -F "poc_name=Mrs. Asha Rao" -F "poc_contact=+91 98765 43210" \
  -F "latitude=19.0760" -F "longitude=72.8777" \
  -F "normal_photos[]=@gate.jpg" -F "normal_photos[]=@classroom.jpg" \
  -F "ai_photos[]=@assembly.jpg"
const fd = new FormData();
fd.append("visit_date", "2026-11-17");
fd.append("city", "Mumbai");
fd.append("school_name", "Sunrise Public School");
fd.append("poc_name", "Mrs. Asha Rao");
fd.append("poc_contact", "+91 98765 43210");
fd.append("latitude", "19.0760");
fd.append("longitude", "72.8777");
normalFiles.forEach(f => fd.append("normal_photos[]", f));
aiFiles.forEach(f => fd.append("ai_photos[]", f));

const res = await fetch(`${BASE_URL}/Staff/visit.php`, {
  method: "POST",
  headers: { Authorization: `Bearer ${token}` },   // no Content-Type: the browser sets it
  body: fd,
});
201 Created
{
  "Status": true,
  "Message": "Visit created successfully",
  "Data": {
    "Visit_ID": 12,
    "Username": "EMP003",
    "Staff_Name": "Asha Patil",
    "Visit_Date": "2026-11-17",
    "City": "Mumbai",
    "School_Name": "Sunrise Public School",
    "POC_Name": "Mrs. Asha Rao",
    "POC_Contact": "+919876543210",
    "Latitude": 19.076,
    "Longitude": 72.8777,
    "Status": "Pending",
    "AI_Count_Status": "Pending",
    "AI_Attempts": 0,
    "AI_Error": null,
    "Normal_Photos": [
      { "Photo_ID": 31, "Storage": "s3", "Path": "prod/visits/12/9f2c….jpg", "Url": "https://…signed link…", "Is_Approved": false, "Is_Best": false }
    ],
    "AI_Photos": [
      { "Photo_ID": 33, "Storage": "local", "Path": "uploads/visits/12/c41a….jpg", "Url": "http://…", "Face_Count": null, "AI_Status": "Pending" },
      { "Photo_ID": 34, "Storage": "local", "Path": "uploads/visits/12/77d0….jpg", "Url": "http://…", "Face_Count": null, "AI_Status": "Pending" }
    ],
    "Unique_Person_Count": null,
    "Total_Face_Count": 0,
    "Created_AT": "2026-11-17 11:45:10"
  }
}
Count field Meaning
Unique_Person_Count (visit) Unique people across all the visit's AI photos, from /unique-count's unique_person_count. null when the visit has no AI photos or counting failed. In the example, one person is in both photos, so 3 + 17 faces = 18 unique people.
Face_Count (AI photo) Faces detected in that one photo (faces_detected)
Total_Face_Count (visit) Sum of the photos' Face_Count. A person in several photos is counted each time. Use Unique_Person_Count for "how many people".
Counts arrive a little later. Right after creation the AI photos are Pending and the counts are null (as in the example). When the worker has counted the batch, the same visit shows "AI_Count_Status": "Done", each AI photo's Face_Count (e.g. 3 and 17) and the visit's Unique_Person_Count (e.g. 18, when one person is in both photos). Poll GET ?visit_id= or refresh the list to see them. If the counting service is down, the batch waits and is retried; see AI count worker.
Where photos are stored. If S3_BUCKET, S3_ACCESS_KEY and S3_SECRET_KEY are set in .env, new photos upload to S3 automatically. If they are empty, photos are saved in the local uploads/ folder. If an S3 upload fails (wrong keys, bucket down, network), that photo is saved in uploads/ instead, the visit still succeeds, and Warnings says which photos fell back. Every photo reports where it lives in Storage ("s3" or "local"), so a visit can mix both. Photos are not moved when S3 is switched on later. See Photo storage.
Errors
Status When
400 Validation failed with an Errors object. Keys are the field names (visit_date, city, school_name, latitude, longitude, photos, normal_photos, ai_photos).
413 The upload is bigger than PHP's post_max_size
500 Server error. Nothing is saved: the visit row and its files are rolled back.

List / get visits

GET/Staff/visit.php

Staff get only their own visits. Admins get everyone's. Clients get only Approved visits, with only the approved normal photos (all AI photos are included).

Query param Description
visit_id Return only this visit (404 if it does not exist, is not yours, or, for a Client, is not Approved)
city Only visits in this city
date_from, date_to Date range, YYYY-MM-DD, both inclusive
username Admin only. Only this user's visits (ignored for Staff)
status Pending, Approved or Rejected. For Admin and Staff, e.g. ?status=Pending lists the visits waiting for approval. Ignored for Clients.
limit, offset Paging. limit is 1-100 (default 20).
curl "BASE/Staff/visit.php?city=Mumbai&date_from=2026-11-01" \
  -H "Authorization: Bearer <token>"
200 Success
{
  "Status": true,
  "Month": "2026-11",
  "Cities": [
    { "City": "Mumbai",    "This_Month_Visits": 4, "Total_Visits": 19 },
    { "City": "Pune",      "This_Month_Visits": 0, "Total_Visits": 7 },
    { "City": "Delhi",     "This_Month_Visits": 0, "Total_Visits": 0 }
  ],
  "Totals": { "This_Month_Visits": 4, "Total_Visits": 26 },
  "Total": 4,
  "Limit": 20,
  "Offset": 0,
  "Data": [ { "Visit_ID": 12, "…": "same visit object as in Create visit" } ]
}

Approve visit (Admin)

PUT/Staff/visit.php

An Admin sets a visit's status, chooses which of its normal photos Clients may see, and marks the best ones. Admins only (Staff and Clients get 403). Send JSON (or form fields) with visit_id plus at least one of the other fields.

Field Required Rules
visit_id Yes The visit to change
status * Pending, Approved or Rejected. Only Approved visits are shown to Clients.
approved_normal_photo_ids * The complete list of this visit's normal photos that Clients may see, as an array ([31, 32]) or text ("31,32"). Photos not in the list are hidden from Clients. An empty list ([]) hides all of them. Leave the field out to keep the current selection. AI photos are always shown and cannot be listed here.
best_normal_photo_ids * The complete list of this visit's best normal photos (Is_Best: true), as an array or text like approved_normal_photo_ids. Any number of photos can be best. A best photo must also be approved (after this update), otherwise 400. An empty list clears them; leave the field out to keep the current ones. When a photo is un-approved it stops being best automatically.
retry_ai_count * true puts the visit's AI photos back in the worker queue (attempts start again at 1). Allowed when AI_Count_Status is Failed or Done; otherwise 400.
curl -X PUT "BASE/Staff/visit.php" \
  -H "Authorization: Bearer <admin token>" \
  -H "Content-Type: application/json" \
  -d '{"visit_id":12,"status":"Approved","approved_normal_photo_ids":[31,32],"best_normal_photo_ids":[31]}'
200 Success
{
  "Status": true,
  "Message": "Visit updated. Status: Approved, approved normal photos: 2 of 3, best: 1",
  "Data": { "Visit_ID": 12, "Status": "Approved", "Normal_Photos": [ { "Photo_ID": 31, "Is_Approved": true, "Is_Best": true, "…": "…" } ], "…": "full visit" }
}
Status When
400 visit_id is required, neither status nor approved_normal_photo_ids sent, an unknown status, or a photo ID that is not a normal photo of this visit (Errors lists them)
403 Caller is not an Admin
404 Visit not found

Every change is written to the activity log (who, which visit, old and new status, photo IDs).

Setup

GET/setup.php

One-time installer. It creates the database and login_tbl, and inserts the default users (EMP001 and EMP002, both Admin) with passwords from .env. It is safe to run again, because existing users are not overwritten. The response is plain text.

Set SETUP_ENABLED=false in .env once setup is done. While disabled it returns 403.
Database upgrades are automatic. When a code update needs new columns, the first API request after the update adds them (migrations.php), even with SETUP_ENABLED=false. The applied version is kept in logs/schema_version.txt, so later requests skip the check. If an upgrade fails, the API answers 500 "Database upgrade failed" and the reason is in the error log.

Configuration (.env)

All settings live in .env next to config.php. The file is blocked from web access by .htaccess.

Key Default Description
APP_DEBUG false Show PHP errors and database error details
TIMEZONE Asia/Kolkata PHP timezone
MYSQL_TIME_ZONE +05:30 MySQL session timezone offset
DB_HOST localhost MySQL host
DB_USER root MySQL user
DB_PASS (empty) MySQL password
DB_NAME horlicks_school_tribes Database name
CORS_ALLOWED_ORIGIN * * or a comma-separated list of origins. Cookies and credentials are only allowed with a specific list.
TOKEN_TTL_SECONDS 2592000 Token lifetime (30 days)
TRUST_PROXY false Trust X-Forwarded-For style headers for the client IP
PERSON_COUNTER_API_URL - Base URL of the external Person Counter service, e.g. http://192.168.1.14:8000. It must have the /unique-count endpoint (check <url>/docs). Used by the AI count worker.
S3_BUCKET, S3_ACCESS_KEY, S3_SECRET_KEY (empty) Fill all three to store visit photos in S3. Leave empty to use the local uploads/ folder. See Photo storage.
S3_REGION us-east-1 Region of the bucket, e.g. ap-south-1
S3_ENDPOINT (empty) Only for S3-compatible services (MinIO, DigitalOcean Spaces, Cloudflare R2). Empty means AWS S3.
S3_PATH_STYLE auto true: endpoint/bucket/key. false: bucket.endpoint/key. Empty = true when S3_ENDPOINT is set, otherwise false.
S3_PREFIX (empty) Optional folder inside the bucket, e.g. horlicks
S3_PUBLIC_URL (empty) Optional public or CDN base URL. Empty means the bucket is private and the API returns signed links.
S3_URL_EXPIRY 3600 Lifetime of signed links in seconds (60-604800)
PERSON_COUNTER_TIMEOUT 60 Seconds to wait for the /unique-count request (one request per visit, covering all its AI photos)
AI_WORKER_POLL_SECONDS 5 How often the worker checks for new batches when the queue is empty
AI_WORKER_MAX_ATTEMPTS 3 Tries per batch before it is marked Failed (waiting 1, 2, 4... minutes between tries)
REPORT_MAX_VISITS 50 Most visits in one PDF report
REPORT_WORKER_POLL_SECONDS 5 How often the report worker checks for new reports when it has nothing to do
REPORT_WORKER_MAX_ATTEMPTS 2 Tries per report before it is marked Failed (1 minute between tries)
MAX_PHOTOS_PER_TYPE 10 Max photos in each of normal_photos and ai_photos
MAX_PHOTO_MB 10 Max size of one photo. PHP's upload_max_filesize and post_max_size must be at least as large.
SETUP_ENABLED true Allow setup.php to run
SEED_EMP001_PASSWORD, SEED_EMP002_PASSWORD - Initial passwords used by setup.php

Database

login_tbl

Column Type Notes
Username VARCHAR(30) Primary key. The only login identifier.
Full_Name VARCHAR(20)
Password VARCHAR(200) bcrypt hash (password_hash)
Secret_Key VARCHAR(100) Per-session signing key (hex). NULL when logged out.
Role ENUM Admin, Staff or Client
Status ENUM Active (default) or Inactive. Inactive users cannot log in.
Updated_AT, Created_AT DATETIME Maintained automatically

visit_tbl

Column Type Notes
Visit_ID INT UNSIGNED Primary key, auto-increment
Username VARCHAR(30) Staff member who made the visit. Foreign key to login_tbl.
Visit_Date DATE
City VARCHAR(50) One of VISIT_CITIES at the time of the visit
School_Name VARCHAR(150)
POC_Name, POC_Contact VARCHAR(100), VARCHAR(20) Point of contact and contact number. NULL for visits created before 2026-11-25. Never returned to Clients.
Latitude, Longitude DECIMAL(10,7)
Unique_Person_Count INT UNSIGNED Unique people across the visit's AI photos. NULL if none, not counted yet, or failed.
AI_Count_Status ENUM None (no AI photos), Pending, Working, Done, Failed. The worker queue.
AI_Attempts, AI_Next_Try_AT TINYINT, DATETIME Tries so far, and when a waiting retry is due
AI_Started_AT, AI_Finished_AT, AI_Error DATETIME, DATETIME, VARCHAR(500) When the last try started and finished, and the last problem (never shown to Clients)
Status ENUM Pending (default), Approved or Rejected. Set by an Admin.
Created_AT DATETIME Set automatically

visit_photo_tbl

Column Type Notes
Photo_ID INT UNSIGNED Primary key, auto-increment
Visit_ID INT UNSIGNED Foreign key to visit_tbl (photos are deleted with their visit)
Photo_Type ENUM Normal or AI
File_Path VARCHAR(255) Local: relative to the API root, e.g. uploads/visits/12/<random>.jpg. S3: the object key, e.g. prod/visits/12/<random>.jpg.
Storage ENUM local (default) or s3: where this photo was saved
Face_Count INT UNSIGNED AI photos only: faces detected in the photo. NULL if the count failed.
AI_Status ENUM AI photos only: Pending, Working, Done or Failed
Is_Approved TINYINT(1) Normal photos: 1 when an Admin lets Clients see it (default 0)
Is_Best TINYINT(1) Normal photos: 1 when an Admin marks it as a best photo (only approved photos; default 0)

target_tbl

Column Type Notes
City VARCHAR(50) Primary key: one target per city
Target_Visits INT UNSIGNED
Start_Date, Finish_Date DATE Visits are counted from Start_Date; Finish_Date is the deadline
Updated_By VARCHAR(30) Admin who set or last changed it
Updated_AT, Created_AT DATETIME Maintained automatically

report_tbl

Column Type Notes
Report_ID INT UNSIGNED Primary key
Requested_By, Requested_Role VARCHAR(30), ENUM Who asked; the role decides what the PDF may contain
Visit_IDs, Skipped_Visit_IDs VARCHAR(2000) JSON lists
Status, Attempts, Next_Try_AT, Error ENUM, TINYINT, DATETIME, VARCHAR(500) The queue: Pending / Working / Done / Failed
Storage, File_Path, File_Size, Pages ENUM, VARCHAR(255), INT, SMALLINT Where the finished PDF is (local = reports/ folder, or s3)
Download_Token CHAR(40) Random, unique; the secret part of Pdf_Url
Started_AT, Finished_AT, Created_AT, Updated_AT DATETIME
Existing installs are upgraded automatically on the first request after an update (see Setup).

AI count worker

AI photos are counted in the background by worker/ai_worker.php, so creating a visit is fast and never fails because the counting service is slow or down. Each visit with AI photos is one batch (all its AI photos, one /unique-count request).

Pending ──(worker takes it)──► Working ──► Done
   ▲                                │
   └──── retry in 1, 2, 4… min ◄────┤  (service down / error)
                                    └──► Failed  (after AI_WORKER_MAX_ATTEMPTS tries)

Running it

From the API folder (the worker uses the same .env as the API):

Command Use
php worker/ai_worker.php Keep running and process batches as they arrive. Leave this running all the time (stop with Ctrl+C).
php worker/ai_worker.php --drain Process every batch that is due now, then exit
php worker/ai_worker.php --once Process at most one batch, then exit
If no worker is running, new AI photos simply stay Pending; nothing is lost. The dashboard's AI_Queue shows how many are waiting.

Reports (PDF)

Send a list of visit IDs and get back a full PDF report: a summary page, then for every visit its details, the best photos, the other normal photos and the AI count photos (with faces detected). The PDF is built in the background by the report worker, so the request returns straight away with a Report_ID; ask for the status until it is Done, then open Pdf_Url.

Pending ──(worker takes it)──► Working ──► Done   (Pdf_Url ready)
                                    └──► Failed (after REPORT_WORKER_MAX_ATTEMPTS tries; retry with PUT)

Request a report

POST/Report/report.php
Field Rules
visit_ids Array ([12, 15, 18]) or text ("12,15,18"), in the order you want them in the PDF. Duplicates are ignored. Every visit must exist and be visible to you, otherwise 400 lists the ones that are not.
curl -X POST "BASE/Report/report.php" -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" -d '{"visit_ids":[12,15,18]}'
201 Created
{
  "Status": true,
  "Message": "Report queued. Check its status with GET Report/report.php?report_id=7",
  "Data": { "Report_ID": 7, "Status": "Pending", "Visit_IDs": [12, 15, 18], "Pdf_Url": null, "…": "…" }
}

Status and PDF link

GET/Report/report.php?report_id=7
{
  "Status": true,
  "Data": {
    "Report_ID": 7,
    "Status": "Done",
    "Visit_IDs": [12, 15, 18],
    "Requested_By": "EMP001",
    "Attempts": 1,
    "Error": null,
    "Pdf_Url": "http://…/API/Report/download.php?token=e61e39a5129404387ce4573a32b136d5b8fc4bf4",
    "File_Size": 211832,
    "Pages": 8,
    "Skipped_Visit_IDs": [],
    "Created_AT": "2026-11-25 16:32:58",
    "Started_AT": "2026-11-25 16:33:00",
    "Finished_AT": "2026-11-25 16:33:01"
  }
}
Status Meaning
Pending Waiting for the worker (or waiting 1 minute before a retry; Error says why)
Working The worker is creating the PDF now
Done PDF ready: open Pdf_Url. Skipped_Visit_IDs lists visits that were no longer visible when the PDF was made (e.g. a visit un-approved in the meantime, for a Client).
Failed Could not be created after REPORT_WORKER_MAX_ATTEMPTS tries; Error says why
About Pdf_Url. The link works without logging in (in a browser, email or WhatsApp): the long random token in it is the permission, like a shared-document link. Anyone who has the link can open that one PDF, so share it only with the right people. Wrong or unfinished links return 404. When S3 is configured the PDF is stored in S3 and the link redirects to a 5-minute S3 link; otherwise it is stored in the reports/ folder, which is never served directly.

Report worker

Works exactly like the AI count worker: one report at a time, oldest first, only one report worker can run, a report left Working by a stopped worker is picked up again, and every report is logged (Report created in the activity log).

Command (from the API folder) Use
php worker/report_worker.php Keep running and build reports as they are requested
php worker/report_worker.php --drain Build every report that is due, then exit (for Task Scheduler / cron every minute)
php worker/report_worker.php --once Build at most one report, then exit
Run it next to the AI worker (two terminals, or two scheduled tasks). If it is not running, reports stay Pending.

Photo storage (S3 or local)

Visit photos are saved by storage.php. No AWS SDK or Composer is needed.

Situation What happens
S3 keys are set in .env Photos upload to the bucket as [S3_PREFIX/]visits/<Visit_ID>/<random>.<ext>. Storage is s3.
S3 keys are empty Photos are saved in uploads/visits/<Visit_ID>/. Storage is local.
S3 is set but an upload fails That photo is saved locally, Storage is local, the response has a Warnings entry, and the real S3 error is written to logs/error_*.log.
The visit fails after some photos were saved The database rows are rolled back and every photo already saved (S3 or local) is deleted.

Adding protected endpoints

Include function.php and call verifyTokenAndGetData(). It sends the 401 response and stops by itself if the token is bad, and otherwise returns the verified user.

<?php
require_once 'function.php';

$user = verifyTokenAndGetData();   // ['username' => 'EMP001', 'role' => 'Admin']

if ($user['role'] !== 'Admin') {
    http_response_code(403);
    echo json_encode(["Status" => false, "Message" => "Admin access required"]);
    exit;
}

Logging helpers: logAccess, logAuth, logError, logActivity, logCampaignAction. Daily files are written to logs/. Passwords, tokens and secrets are redacted automatically. Read them in the browser with the Log viewer.

Log viewer

GET/logs/ (opens logs/index.php in the browser)

A web page to read the daily log files, for Admins only. Open BASE/logs/, log in with an Admin account (the same username and password as the API), and pick a file.

Security. Staff accounts get 403. The raw files (*.log, login_attempts.json) are blocked by logs/.htaccess and are only readable through the viewer, which needs an Admin token for every request. File names are checked against <type>_YYYY-MM-DD.log, so nothing else on the server can be read. The login on that page uses the normal login limit (3 failed attempts blocks the IP for 2 minutes).

The page talks to two calls, both needing Authorization: Bearer <admin token>:

Request Returns
GET /logs/index.php?action=files { "Status": true, "Files": [ { "name", "type", "date", "size", "modified" } ] }
GET /logs/index.php?action=read&file=error_2026-11-17.log
optional: q (search), page, limit 10-500 (default 100)
{ "Status": true, "File", "Size", "Truncated", "Total", "Page", "Pages", "Limit", "Entries": [ { "Time", "Message", "Data" } ] }, newest first. 404 for any file name that is not a log file.
Keep this page current. Whenever an endpoint, field, response, error or .env setting changes, update this document and add a line to the changelog below.

Changelog

Date Version Change
2026-11-25 1.12.0 New PDF reports: POST /Report/report.php with a list of visit IDs queues a report; worker/report_worker.php builds it (summary, then per visit: details, best photos, normal photos, AI count photos); GET shows Pending / Working / Done / Failed and, when done, a Pdf_Url (Report/download.php). Reports follow the requester's role (Clients: approved only, no point of contact). New table report_tbl (schema v8), reports/ folder, .env keys REPORT_MAX_VISITS, REPORT_WORKER_POLL_SECONDS, REPORT_WORKER_MAX_ATTEMPTS.
2026-11-25 1.11.0 Normal photos have an Is_Best flag, set by an Admin with best_normal_photo_ids on Approve visit (best photos must be approved; un-approving clears it). Shown to Admin, Staff and Clients. Clients can now read targets (GET /Admin/target.php), read only. Schema v7.
2026-11-25 1.10.0 AI counting moved to a background worker (worker/ai_worker.php). Creating a visit now only queues its AI photos (AI_Count_Status: Pending) and returns immediately. The worker takes one batch at a time (Pending → Working → Done, or retry → Failed), only one worker can run, and stopped batches are recovered. New visit fields AI_Count_Status, AI_Attempts, AI_Error (the last two not for Clients), retry_ai_count on Approve visit, AI_Queue on the dashboard, .env keys AI_WORKER_POLL_SECONDS and AI_WORKER_MAX_ATTEMPTS. Schema v6: existing visits with AI photos but no unique count were queued.
2026-11-25 1.9.0 New Admin/target.php (Admins only): set, change, remove and read a visit target per city (target visits, start date, finish date). Each target reports done, percent done, run rate, needed rate, days left, projected finish date and status (On Track / At Risk / Completed / Overdue / Not Started), plus an overall total. The dashboard now includes the same Targets block. New table target_tbl, created automatically (schema v5).
2026-11-25 1.8.0 Create visit now requires poc_name (point of contact) and poc_contact (contact number). Returned as POC_Name / POC_Contact to Admin and Staff (visit list, single visit, approve response, dashboard), never to Clients. Database upgraded automatically (schema v4).
2026-11-25 1.7.0 New Client role (Admins create it in Admin/user.php). Visits now have a Status (Pending / Approved / Rejected) and normal photos an Is_Approved flag. New PUT /Staff/visit.php (Admin) sets both. Clients see only Approved visits, with all AI photos and only the approved normal photos. New status filter on the visit list. Database upgrades now run automatically (migrations.php).
2026-11-18 1.6.0 AI photos are counted with the Person Counter's /unique-count (all of a visit's AI photos in one request) instead of the single-photo /number-count. New Unique_Person_Count on every visit and Total_Unique_Person_Count on the dashboard. Face_Count is now faces detected per photo. AI photos must be JPG, PNG or WEBP. PERSON_COUNTER_API_URL is port 8001.
2026-11-18 1.5.0 Added GET /Admin/dashboard.php (Admins only): total visits and total face count for a month (?month=YYYY-MM, default current month), the Cities array, and the 5 most recent visits of that month. The visit read helpers moved from Staff/visit.php into the shared visit_helpers.php (no behaviour change). Try it panel added.
2026-11-17 1.4.0 Added the Admin-only web Log viewer at /logs/ (logs/index.php): browse, search and expand all log files after an Admin login. logs/.htaccess now blocks every file except index.php (logger.php creates the same rule on a fresh install).
2026-11-17 1.3.0 Visit photos now go to S3 automatically when S3_BUCKET, S3_ACCESS_KEY and S3_SECRET_KEY are set in .env; otherwise, or if an S3 upload fails, they are saved in uploads/. New storage.php (AWS Signature V4 over cURL, no SDK), new S3_* keys in .env, new Storage column on visit_photo_tbl (run setup.php again), and a Storage field on every photo in the responses. S3 photo links are temporary signed links unless S3_PUBLIC_URL is set.
2026-11-17 1.2.0 Added Staff/visit.php: create a visit (date, city, school, latitude/longitude, normal photos and AI photos with face count from the Person Counter service) and list/get visits (Staff see their own, Admin sees all) with a Cities array of this-month and total visit counts. City list lives in config.php (VISIT_CITIES). New tables visit_tbl and visit_photo_tbl, new uploads/ folder, new .env keys PERSON_COUNTER_TIMEOUT, MAX_PHOTOS_PER_TYPE, MAX_PHOTO_MB. Try it panels now support file uploads and a date picker. Shared helpers respond() and dbExec() moved to function.php.
2026-11-17 1.1.1 Added PERSON_COUNTER_API_URL to .env (external Person Counter service).
2026-11-17 1.1.0 Added Admin/user.php: list/get, create, update (details, password, role) and enable/disable users, Admins only. Added the interactive Try it console. Added getRequestInput() so PUT bodies are read. .htaccess now passes the Authorization header through.
2026-11-17 1.0.0 Initial documentation. Login and logout use Username only. Config moved to .env. Tokens accepted only in the Authorization header. Logout reachable at POST auth.php?do=logout. Proper HTTP status codes. Logs redact secrets.