# Salon Eagle Backend - System Architecture & Comprehensive Engineering Guide

## 1. System Overview & Technology Stack

The **Salon Eagle Backend** is a production RESTful API and scheduled background services engine engineered for the Salon Eagle booking platform (supporting Customer Mobile Apps, Admin Mobile Apps, and Web Management Portals).

### Key Architectural Characteristics
- **Language & Runtime**: PHP 7.4+ / 8.x (Runs under Apache/XAMPP or Nginx with PHP-FPM)
- **Database Engine**: MySQL 5.7+ / 8.0+ (InnoDB with foreign keys, full indexes, and transaction support)
- **Authentication**: Stateless Bearer token architecture backed by `user_sessions` and `admin_sessions` with automatic token rotation, multi-device tracking, and instant revocation capability.
- **Push Notification Service**: Firebase Cloud Messaging (FCM) via official `kreait/firebase-php` (HTTP v1 API using Google Service Account JSON).
- **Concurrency & Double-Booking Protection**: Two-phase reservation safety:
  1. **Distributed Mutex Lock**: MySQL `GET_LOCK('booking_lock_<date>', 5)` prevents race conditions during slot validation.
  2. **Authoritative Overlap Checking**: `(start_time < newEndTime AND end_time > newStartTime)` inside isolated transactions.
  3. **Unique Database Constraint**: `UNIQUE KEY unique_booking (booking_date, start_time, end_time)`.
- **Timezone**: Strictly localized to `Asia/Colombo` (+05:30) across all operations, timestamps, and crons.
- **Client Compatibility**: Explicit integer and float type-casting in responses for seamless Flutter/Dart deserialization without runtime cast exceptions.

---

## 2. Directory Layout & Module Responsibilities

```
d:\xampp\htdocs\backend/
├── api/
│   ├── admin/               # Administrative APIs (requires admin Bearer token)
│   │   ├── admin_login.php         # Admin credential verification & session initialization
│   │   ├── all_bookings.php        # Chronological multi-service booking list with user details
│   │   ├── approve_booking.php     # Transactional approval & asynchronous FCM push
│   │   ├── close_days.php          # Full-day holiday/closure management & conflict checks
│   │   ├── closed_time_slots.php   # Partial slot closure management (lunch, maintenance)
│   │   ├── complete_booking.php    # Finalize appointment after service delivery
│   │   ├── dashboard_stats.php     # Live metrics, date-range revenue analytics, day toggle
│   │   ├── get_working_hours.php   # Weekly recurring schedule (Mon-Sun)
│   │   ├── manage_services.php     # Service catalog CRUD with image upload & cascade guards
│   │   ├── pending_bookings.php    # Actionable queue of bookings requiring review
│   │   ├── profile.php             # Admin profile retrieval and password modification
│   │   ├── reject_booking.php      # Booking rejection/cancellation with reason & customer FCM
│   │   ├── staff.php               # Super-admin staff management (RBAC enforced)
│   │   ├── update_working_hours.php# Update weekly opening/closing times per day
│   │   └── users.php               # Customer management, search, history, & block/unblock
│   ├── auth/                # Public Authentication APIs
│   │   ├── change_password.php     # Unified password change (supports user & admin)
│   │   ├── login.php               # Customer authentication, token rotation, & device sync
│   │   ├── logout.php              # Invalidation of active token in session store
│   │   └── register.php            # Sri Lankan phone validation, registration, & auto-login
│   ├── common/              # Shared Utilities & System Checks
│   │   ├── app_status.php          # Maintenance mode, min app versions, & force update flags
│   │   ├── get_profile.php         # Dynamic session resolution (user or admin)
│   │   ├── health.php              # Comprehensive health check (DB, Storage, Environment)
│   │   ├── save_fcm_token.php      # FCM token registration endpoint
│   │   └── upload_image.php        # Secure multipart upload with MIME & size validation
│   ├── middleware/          # Guard and Processing Interceptors
│   │   ├── cors.php                # CORS headers, origin reflection, & OPTIONS preflight
│   │   ├── maintenance.php         # 503 Service Unavailable check against app_settings
│   │   ├── rate_limit.php          # Atomic file-locked IP rate limiter (15 req/min)
│   │   └── version_check.php       # Semantic version enforcement (426 Upgrade Required)
│   ├── notifications/       # Notification Center APIs
│   │   ├── get_admin_notifications.php # Paginated notifications for admin staff
│   │   ├── get_user_notifications.php  # Customer notification history
│   │   ├── save_token.php              # Device FCM token registrar
│   │   └── send_admin_notification.php # Admin broadcast push dispatcher
│   └── user/                # Customer APIs (requires customer Bearer token)
│       ├── cancel_booking.php      # Customer cancellation with admin notification
│       ├── create_booking.php      # Mutex-locked multi-service booking engine
│       ├── get_available_times.php # Dynamic slot generator (hours, bookings, closures)
│       ├── get_promotions.php      # Special offers with graceful fallback
│       ├── get_salon_info.php      # Weekly schedule & upcoming 90-day closures
│       ├── get_services.php        # Active service catalog with absolute image URLs
│       ├── get_user_stats.php      # Customer statistics (bookings, unique services, rating)
│       ├── my_bookings.php         # Customer booking history with multi-service rollup
│       ├── reschedule_booking.php  # Atomic rescheduling with 2-hour cutoff rule
│       ├── submit_review.php       # Post-service ratings & reviews (1-5 stars)
│       └── update_profile.php      # Profile details & password update with unique guards
├── config/
│   ├── constants.php        # Global environment constants, paths, and URLs
│   ├── db.php               # PDO database connection factory with UTF8MB4
│   ├── fcm.php              # Kreait Firebase HTTP v1 push notification wrapper
│   └── functions.php        # Core helper library (security, auth, tokens, files, response)
├── cron/
│   ├── booking_reminder.php # Daily 24-hour advance booking notification
│   ├── cleanup_sessions.php # Automated purge of expired tokens
│   ├── daily_close_check.php# Auto-close past bookings to completed
│   └── send_reminders.php   # 5-minute countdown reminder (20 mins before slot)
├── database/
│   ├── migration.sql        # Authoritative database DDL schema and upgrade scripts
│   └── seeds.sql            # Optional seed data
├── uploads/                 # Static asset storage
│   ├── .htaccess            # Hardened execution blocker (disables PHP script execution)
│   ├── services/            # Service catalog photos
│   └── users/               # Customer avatar photos
├── composer.json            # Dependency manifest (kreait/firebase-php: ^7.0)
└── saloneagleuser-firebase-adminsdk-fbsvc-b8298372e5.json # Firebase service credentials
```

---

## 3. Database Architecture & Relational Schema

### Entity Relationship Map

```
  +------------------+           +------------------+
  |      users       |1        * |  user_sessions   |
  +------------------+-----------+------------------+
  | id (PK)          |           | id (PK)          |
  | phone (UQ)       |           | user_id (FK)     |
  | email (UQ, Null) |           | token (UQ)       |
  | password (Hash)  |           | device_id        |
  | date_of_birth    |           | expires_at       |
  | gender           |           | revoked          |
  | status           |           +------------------+
  +--------+---------+
           | 1
           |
           | *
  +--------v---------+           +------------------+
  |   user_devices   |           |     reviews      |
  +------------------+           +------------------+
  | id (PK)          |           | id (PK)          |
  | user_id (FK)     |           | booking_id (FK)  |
  | fcm_token (UQ)   |           | user_id (FK)     |
  | device_type      |           | rating (1-5)     |
  | last_active      |           | comment          |
  +------------------+           +--------^---------+
                                          | 1
                                          | 1
  +------------------+           +--------+---------+
  |     services     |1        * |     bookings     |
  +------------------+-----------+------------------+
  | id (PK)          |           | id (PK)          |
  | name             |           | user_id (FK)     |
  | duration_minutes |           | service_id (FK)  |
  | price            |           | booking_date     |
  | image_url        |           | start_time       |
  | status           |           | end_time         |
  +--------+---------+           | status           |
           | 1                   | reminder_sent    |
           |                     | reminder_20m_sent|
           | *                   +--------+---------+
  +--------v---------+                    | 1
  | booking_services |*                   |
  +------------------+--------------------+
  | id (PK)          |
  | booking_id (FK)  |
  | service_id (FK)  |
  | price (Snapshot) |
  +------------------+

  +------------------+           +------------------+           +------------------+
  |      admins      |1        * |  admin_sessions  |           |  admin_devices   |
  +------------------+-----------+------------------+           +------------------+
  | id (PK)          |           | id (PK)          |           | id (PK)          |
  | email (UQ)       |           | admin_id (FK)    |           | admin_id (FK)    |
  | role             |           | token (UQ)       |           | fcm_token (UQ)   |
  | password         |           | device_id        |           | device_type      |
  +------------------+           +------------------+           +------------------+

  +-----------------------+   +----------------------+   +----------------------+
  |    salon_schedule     |   |     closed_dates     |   |  closed_time_slots   |
  +-----------------------+   +----------------------+   +----------------------+
  | day_of_week (Mon..Sun)|   | closed_date (Date UQ)|   | closed_date (Date)   |
  | open_time             |   | reason               |   | start_time           |
  | close_time            |   +----------------------+   | end_time             |
  | is_closed             |                              | reason               |
  +-----------------------+                              +----------------------+

  +-----------------------+   +----------------------+   +----------------------+
  |     notifications     |   |     app_settings     |   |      promotions      |
  +-----------------------+   +----------------------+   +----------------------+
  | user_type (user/admin)|   | maintenance_user/adm |   | title, discount      |
  | user_id               |   | min_app_version_*    |   | subtitle, image_url  |
  | title, message, type  |   | force_update_*       |   | valid_until          |
  | is_read, sent_at      |   | slot_interval_minutes|   | is_active            |
  +-----------------------+   +----------------------+   +----------------------+
```

### Table Specifications

| Table | Description | Critical Constraints & Indexes |
|---|---|---|
| `users` | Customer profiles | `idx_phone (phone UNIQUE NOT NULL)`, `idx_email (email UNIQUE NULL)` |
| `user_sessions` | Auto-login customer tokens | `token UNIQUE`, `idx_user_device (user_id, device_id)`, `idx_expires_last_used` |
| `user_devices` | Customer FCM push tokens | `fcm_token(255) UNIQUE`, `device_type ENUM('android', 'ios', 'web')` |
| `admins` | Staff and Owners | `email UNIQUE`, `role ENUM('admin', 'super_admin')` |
| `admin_sessions`| Admin auto-login tokens | `token UNIQUE`, `idx_admin_device (admin_id, device_id)` |
| `admin_devices` | Admin FCM push tokens | `fcm_token(255) UNIQUE`, `device_type ENUM('android', 'ios')` |
| `services` | Salon service catalog | `status ENUM('active', 'inactive')`, `price DECIMAL(10,2)` |
| `bookings` | Customer appointments | `UNIQUE KEY unique_booking (booking_date, start_time, end_time)`, `idx_perf_overlap (booking_date, status, start_time, end_time)` |
| `booking_services` | Multi-service pivot | `UNIQUE KEY uq_booking_service (booking_id, service_id)`, `price DECIMAL(10,2)` (Snapshot price at booking time) |
| `salon_schedule`| Weekly working hours | `day_of_week ENUM('Mon'..'Sun') UNIQUE` |
| `closed_dates` | Full-day holidays | `closed_date DATE UNIQUE` |
| `closed_time_slots`| Partial day closures | `idx_closed_date_time (closed_date, start_time, end_time)` |
| `notifications`| In-app notification log| `idx_user_type_id (user_type, user_id)`, `idx_type`, `idx_is_read` |
| `app_settings` | Platform runtime toggles | Single row `id = 1` |
| `reviews` | Customer ratings & reviews| `UNIQUE KEY uk_booking_review (booking_id)`, rating 1 to 5 |
| `promotions` | Marketing banner cards | `is_active BOOLEAN`, `valid_until DATE` |

---

## 4. Core Business Workflows

### 4.1 Authentication & Multi-Device Token Lifecycle

```
Client App                                                    Backend Server
   |                                                                |
   |-- POST /api/auth/login (phone, password, device_id, fcm_token) ->
   |                                                                |-- Rate Limit Check (rate_limit.php)
   |                                                                |-- Verify BCrypt hash
   |                                                                |-- Generate 64-char crypto token
   |                                                                |-- DELETE old tokens for (user_id, device_id)
   |                                                                |-- INSERT into user_sessions (+30 days)
   |                                                                |-- UPSERT into user_devices (FCM token)
   |<- 200 OK (token, expires_at, user profile) --------------------|
   |
   |-- Any Authenticated Request (Header: Authorization: Bearer <token>) ->
   |                                                                |-- getUserFromToken():
   |                                                                |   SELECT FROM user_sessions
   |                                                                |   WHERE token = ? AND expires_at > NOW()
   |                                                                |   AND revoked = 0 [AND device_id = ?]
   |<- 200 OK / 401 Unauthorized -----------------------------------|
   |
   |-- POST /api/auth/logout (Header: Authorization: Bearer <token>) ->
   |                                                                |-- DELETE FROM user_sessions & admin_sessions
   |<- 200 OK ------------------------------------------------------|
```

### 4.2 Multi-Service Booking Creation with Distributed Mutex Lock

To prevent race conditions where two customers attempt to book overlapping time slots simultaneously:

```
Customer App                                                   MySQL Database
     |                                                               |
     |-- POST /api/user/create_booking ----------------------------->|
     |   { service_ids: [1, 3], booking_date: "2026-11-01",          |
     |     start_time: "10:00:00" }                                  |
     |                                                               |-- Calculate total duration & end_time
     |                                                               |-- Verify salon_schedule (day open/close)
     |                                                               |-- Verify closed_time_slots
     |                                                               |
     |                                                               |-- [PHASE 1: Mutex Acquisition]
     |                                                               |   SELECT GET_LOCK('booking_lock_2026-11-01', 5)
     |                                                               |   If timeout -> return 409 Conflict
     |                                                               |
     |                                                               |-- [PHASE 2: Isolated Transaction]
     |                                                               |   START TRANSACTION
     |                                                               |   SELECT COUNT(*) FROM bookings
     |                                                               |   WHERE booking_date = '2026-11-01'
     |                                                               |     AND status IN ('pending', 'approved')
     |                                                               |     AND (start_time < end_time AND end_time > start_time)
     |                                                               |   If overlap > 0 -> ROLLBACK & release lock -> 409
     |                                                               |
     |                                                               |   INSERT INTO bookings (..., status='pending')
     |                                                               |   INSERT INTO booking_services (price snapshots)
     |                                                               |   COMMIT TRANSACTION
     |                                                               |
     |                                                               |-- [PHASE 3: Mutex Release]
     |                                                               |   SELECT RELEASE_LOCK('booking_lock_2026-11-01')
     |                                                               |
     |                                                               |-- [PHASE 4: Async Admin Push]
     |                                                               |   Send FCM to admin_devices
     |                                                               |   Insert in-app notification row
     |<- 200 OK ("Booking created successfully") --------------------|
```

### 4.3 Slot Availability Engine (`get_available_times.php`)

Computes real-time bookable slots based on 5 rigorous checks:
1. **Full-Day Closure Check**: Verifies `closed_dates` (returns empty slots if holiday).
2. **Day Schedule Check**: Looks up `salon_schedule` for the day of week.
3. **Dynamic Interval Stepping**: Iterates from `open_time` to `close_time` using `slot_interval_minutes` (default 60 min, or custom query param 15-120 min).
4. **Aggregate Duration**: Sums `duration_minutes` of all requested `service_ids` to determine required slot length.
5. **Slot Qualification Filters**:
   - `isBooked`: Overlaps with existing `pending` or `approved` booking (`exclude_booking_id` supported for reschedule).
   - `isClosed`: Overlaps with `closed_time_slots`.
   - `isPast`: Slot start timestamp < current timestamp (if date is today).
   - `isExceedsClose`: Slot start + duration exceeds salon `close_time`.

### 4.4 Booking Rescheduling with 2-Hour Cutoff (`reschedule_booking.php`)

Enforces strict salon operations rules:
- **Ownership Verification**: Must belong to authenticated customer.
- **Allowed Statuses**: Only `pending` or `approved`.
- **2-Hour Rule**:
  ```php
  $minutesUntilCurrent = ($currentBookingDateTime->getTimestamp() - $now->getTimestamp()) / 60;
  if ($minutesUntilCurrent < 120 && $minutesUntilCurrent > 0) {
      sendResponse(['status' => 'error', 'message' => 'Rescheduling is not permitted within 2 hours of the original appointment time.'], 400);
  }
  ```
- Cannot reschedule to a past date/time.
- Acquires `GET_LOCK('booking_lock_' . newDate, 5)` to verify slot availability without race conditions.
- Updates booking, resets status to `pending`, and resets all notification reminder flags (`reminder_sent=0`, `reminder_daily_sent=0`, `reminder_20m_sent=0`).
- Dispatches FCM push to notify admins.

### 4.5 Admin Approval & Notification Dispatching (`approve_booking.php`)

**Critical Pattern**: DB transactions must never wrap external network calls (such as FCM requests).
1. `START TRANSACTION`
2. Update booking status from `pending` to `approved`.
3. Fetch user details and active user device FCM tokens.
4. Insert in-app notification into `notifications` table.
5. `COMMIT TRANSACTION` (Database locks released immediately).
6. Dispatches FCM push notification using `Kreait\Firebase\Messaging` outside transaction.

---

## 5. Background Scheduled Tasks (Cron Engine)

| Cron Script | Recommended Schedule | Responsibilities |
|---|---|---|
| `cron/send_reminders.php` | `*/5 * * * *` (Every 5 mins) | Scans for today's approved bookings starting in 15–25 minutes (`reminder_20m_sent = 0`). Dispatches high-priority countdown push notifications to both the customer and salon admins. |
| `cron/booking_reminder.php` | `0 18 * * *` (Daily at 6 PM) | Finds tomorrow's approved bookings (`reminder_daily_sent = 0`). Sends friendly 24-hour reminder push notification to customer. |
| `cron/daily_close_check.php`| `0 0 * * *` (Daily Midnight)| Auto-updates past approved bookings (`booking_date < yesterday`) to `completed`. |
| `cron/cleanup_sessions.php` | `0 3 * * *` (Daily at 3 AM) | Purges expired sessions (`expires_at < NOW()`) from `user_sessions` and `admin_sessions`. |

---

## 6. Complete API Reference

### 6.1 Authentication Endpoints

#### `POST /api/auth/register.php`
- **Auth**: Public
- **Headers**: `Content-Type: application/json`
- **Payload**:
  ```json
  {
    "name": "Jane Doe",
    "phone": "0771234567",
    "gender": "female",
    "password": "secretPassword123",
    "email": "jane@example.com",
    "date_of_birth": "1998-05-14",
    "device_id": "device_uuid_here",
    "device_type": "android",
    "fcm_token": "fcm_token_string"
  }
  ```
- **Response** (201):
  ```json
  {
    "status": "success",
    "token": "64_char_hex_token",
    "expires_at": "2026-11-25 20:00:00",
    "user": { "id": 12, "name": "Jane Doe", "phone": "0771234567", "gender": "female" }
  }
  ```

#### `POST /api/auth/login.php`
- **Auth**: Public
- **Payload**:
  ```json
  {
    "phone": "0771234567",
    "password": "secretPassword123",
    "device_id": "device_uuid_here",
    "device_type": "android",
    "fcm_token": "fcm_token_string"
  }
  ```

#### `POST /api/auth/change_password.php`
- **Auth**: Bearer Token (User or Admin)
- **Payload**:
  ```json
  {
    "old_password": "currentPassword",
    "new_password": "newStrongPassword"
  }
  ```

#### `POST /api/auth/logout.php`
- **Auth**: Bearer Token
- **Action**: Deletes session from both `user_sessions` and `admin_sessions`.

---

### 6.2 Customer Endpoints (`/api/user/`)

#### `GET /api/user/get_services.php`
- **Auth**: Public
- **Response**: List of active services with absolute image URLs (`BASE_URL . 'uploads/services/' . image_url`).

#### `GET /api/user/get_available_times.php`
- **Auth**: Public
- **Query Params**:
  - `date`: `YYYY-MM-DD` (Required)
  - `service_ids`: Comma-separated IDs (e.g., `1,2`)
  - `exclude_booking_id`: Integer ID (Optional, used during rescheduling)
  - `interval`: Integer minutes (15–120, Optional)
- **Response**:
  ```json
  {
    "status": "success",
    "slots": [
      { "time": "09:00 AM", "is_available": true, "reason": null },
      { "time": "10:00 AM", "is_available": false, "reason": "Booked" },
      { "time": "01:00 PM", "is_available": false, "reason": "Closed" }
    ]
  }
  ```

#### `POST /api/user/create_booking.php`
- **Auth**: Customer Bearer Token
- **Payload**:
  ```json
  {
    "service_ids": [1, 4],
    "booking_date": "2026-11-05",
    "start_time": "14:00:00"
  }
  ```

#### `POST /api/user/reschedule_booking.php`
- **Auth**: Customer Bearer Token
- **Payload**:
  ```json
  {
    "booking_id": 45,
    "new_date": "2026-11-10",
    "new_time": "11:00"
  }
  ```

#### `POST /api/user/cancel_booking.php`
- **Auth**: Customer Bearer Token
- **Payload**:
  ```json
  {
    "booking_id": 45,
    "reason": "Family emergency"
  }
  ```

#### `GET /api/user/my_bookings.php`
- **Auth**: Customer Bearer Token
- **Response**: All user bookings with aggregated service names, total price, and total duration.

#### `POST /api/user/submit_review.php`
- **Auth**: Customer Bearer Token
- **Payload**:
  ```json
  {
    "booking_id": 42,
    "rating": 5,
    "comment": "Exceptional styling by the senior stylist!"
  }
  ```

#### `GET /api/user/get_user_stats.php`
- **Auth**: Customer Bearer Token
- **Response**: `{ "booking_count": 8, "service_count": 4, "rating": "5.0" }`

#### `POST /api/user/update_profile.php`
- **Auth**: Customer Bearer Token
- **Payload**: `{ "name": "Jane", "email": "new@email.com", "phone": "0771234567" }`

---

### 6.3 Administrative Endpoints (`/api/admin/`)

#### `POST /api/admin/admin_login.php`
- **Auth**: Public
- **Payload**: `{ "email": "admin@saloneagle.com", "password": "...", "device_id": "...", "device_type": "android", "fcm_token": "..." }`

#### `GET /api/admin/dashboard_stats.php`
- **Auth**: Admin Bearer Token
- **Query Params**: `start_date`, `end_date` (Optional for range analytics)
- **Response**:
  ```json
  {
    "status": "success",
    "today_bookings": 14,
    "pending_approvals": 3,
    "total_users": 280,
    "is_closed_today": false,
    "range_stats": {
      "total_bookings": 120,
      "completed_bookings": 105,
      "cancelled_bookings": 10,
      "approved_bookings": 5,
      "total_revenue": 345000.00
    }
  }
  ```
- **POST**: `{ "is_closed": true }` to quick-toggle salon closure for today.

#### `GET /api/admin/pending_bookings.php`
- **Auth**: Admin Bearer Token
- **Response**: List of pending bookings ordered by date ASC, time ASC with user phone and name.

#### `GET /api/admin/all_bookings.php`
- **Auth**: Admin Bearer Token
- **Response**: Complete booking history ordered by date DESC.

#### `POST /api/admin/approve_booking.php`
- **Auth**: Admin Bearer Token
- **Payload**: `{ "booking_id": 45 }`

#### `POST /api/admin/reject_booking.php`
- **Auth**: Admin Bearer Token
- **Payload**: `{ "booking_id": 45 }`

#### `POST /api/admin/complete_booking.php`
- **Auth**: Admin Bearer Token
- **Payload**: `{ "booking_id": 45 }`

#### `GET / POST / PUT / DELETE /api/admin/manage_services.php`
- **Auth**: Admin Bearer Token
- **Actions**:
  - `action=list` (GET)
  - `action=add` (POST multipart: name, description, duration_minutes, price, image)
  - `action=update` (POST/PUT: id, name, description, duration_minutes, price, status, image)
  - `action=delete` (POST/DELETE: id) -> Returns 400 if service is used in past/active bookings.

#### `GET / POST /api/admin/closed_time_slots.php`
- **Auth**: Admin Bearer Token
- **Actions**:
  - `GET ?date=YYYY-MM-DD`: Lists partial closure slots
  - `POST { "action": "add", "closed_date": "...", "start_time": "12:30", "end_time": "13:30", "reason": "Staff Lunch" }`
  - `POST { "action": "delete", "id": 12 }`

#### `POST /api/admin/close_days.php`
- **Auth**: Admin Bearer Token
- **Payload**: `{ "action": "add", "date": "2026-12-25", "reason": "Christmas Day" }`
- **Returns**: Number of conflicting bookings that may require admin rescheduling!

#### `GET / POST / PUT / DELETE /api/admin/staff.php`
- **Auth**: Super Admin Bearer Token (`role === 'super_admin'`)
- **Actions**: Full CRUD for salon administrators and staff accounts.

#### `GET / PUT /api/admin/users.php`
- **Auth**: Admin Bearer Token
- **Actions**:
  - `GET ?search=query&limit=50&offset=0`: Search customer database
  - `GET ?id=25`: Customer profile with full multi-service booking history
  - `PUT { "id": 25, "status": "blocked" }`: Blocks customer and immediately revokes all active sessions.

---

### 6.4 Common & Utility Endpoints (`/api/common/`)

#### `GET /api/common/health.php`
- **Auth**: Public
- **Response** (200 / 503):
  ```json
  {
    "status": "healthy",
    "timestamp": "2026-10-26 21:00:00",
    "components": {
      "database": { "status": "up", "latency_ms": 0 },
      "storage": { "logs_writable": true, "uploads_writable": true },
      "environment": { "php_version": "8.2.12", "timezone": "Asia/Colombo", "memory_usage": 2097152 }
    }
  }
  ```

#### `GET /api/common/app_status.php`
- **Auth**: Public
- **Response**: `{ "success": true, "data": { "maintenance_user": false, "maintenance_admin": false, "min_app_version_user": "1.0.0", "force_update_user": false } }`

#### `POST /api/common/upload_image.php`
- **Auth**: Bearer Token
- **Payload**: Multipart form with `image` file
- **Security**: Validates MIME type (`image/jpeg`, `image/png`, `image/webp`), verifies allowed extensions, enforces max 5MB, writes random UUID filename, blocks script execution via `.htaccess`.

---

## 7. Security Hardening & Defenses

1. **Upload Execution Prevention**:
   The `/uploads/.htaccess` file explicitly disables the PHP engine (`php_flag engine off`) and denies access to all script extensions (`.php`, `.phtml`, `.cgi`, `.pl`, `.py`, `.sh`, `.htaccess`), preventing any remote code execution from uploaded media.
2. **Atomic IP Rate Limiting**:
   `/api/middleware/rate_limit.php` enforces a sliding window rate limit per client IP using atomic file locks (`flock(LOCK_EX)`). Abusers receive `429 Too Many Requests` with a `Retry-After` header.
3. **Session Revocation & Anti-Stale Checks**:
   `user_sessions` and `admin_sessions` feature `revoked` and `expires_at` flags. In addition, blocking a user immediately wipes active sessions from the database.
4. **SQL Injection Defense**:
   100% of SQL queries utilize prepared statements (`$pdo->prepare()`) with positional or named parameters.
5. **CORS Hardening**:
   `/api/middleware/cors.php` handles dynamic origin reflection with `Access-Control-Allow-Credentials: true` and cleanly terminates HTTP `OPTIONS` preflight requests with `204 No Content`.
