PHP 8.2 / MySQL FCM HTTP v1 Timezone: Asia/Colombo

Salon Eagle Backend Architecture

Production REST API engine supporting the Customer Mobile App, Admin Mobile App, and Web Management Portals. Features multi-service booking, distributed mutex locking, FCM push dispatching, and automated background cron tasks.

34+
RESTful Endpoints
15
Relational Tables
4
Automated Crons
<50ms
Mutex Lock Check

Directory Architecture

Directory / Module Role Key Responsibilities
api/auth/ Authentication Pipeline Registration, Login, Password Change, Token Rotation, Session Invalidation
api/user/ Customer Core Booking Creation, Mutex Overlap Guards, Rescheduling, Cancellations, Reviews
api/admin/ Salon Management Dashboard Metrics, Approval/Rejection, Service Catalog, Closures, Staff RBAC
api/common/ System Utilities Health Check (DB/Disk), App Settings, Multi-type Image Upload, Device Tokens
api/middleware/ Interceptors & Guards CORS Origin Reflection, Atomic Rate Limiting (15 req/min), Maintenance Mode
config/ Core Configuration Database PDO factory, Constants, Helper functions, Kreait Firebase HTTP v1 client
cron/ Scheduled Automation 5-min Countdown Reminder, Daily 24h Advance Push, Session Purging, Auto-Close
database/ Schema & Migrations migration.sql with 15 tables, foreign keys, cascade deletes, and overlap indexes
uploads/ Asset Storage Hardened storage with script execution disabled via .htaccess

System Architecture Blueprint

System Topology & Communications Flow
graph LR
    subgraph Clients["Client Layer"]
        UserApp["Customer Flutter App"]
        AdminApp["Admin Flutter / Web"]
    end

    subgraph Gateways["Security Gateways"]
        CORS["CORS Dynamic Reflection"]
        Rate["Rate Limiter (flock 15r/m)"]
        Maint["Maintenance 503 Guard"]
    end

    subgraph API["PHP REST Engine"]
        Auth["Auth & Session Store"]
        BookingEngine["Booking & Mutex Engine"]
        AdminEngine["Admin & Service Hub"]
    end

    subgraph DataTier["Persistence & Push"]
        MySQL[("MySQL 8.0 InnoDB")]
        FCM["Firebase Cloud Messaging"]
        Storage["Hardened File Storage"]
    end

    Clients --> Gateways
    Gateways --> API
    API --> MySQL
    API --> FCM
    API --> Storage
                    

Core Business Workflows & Concurrency Guarantees

1. Double-Booking Prevention: Distributed Mutex Locking
sequenceDiagram
    autonumber
    actor Customer as Customer App
    participant API as create_booking.php
    participant Mutex as MySQL GET_LOCK()
    participant DB as MySQL InnoDB
    participant FCM as Firebase (FCM)

    Customer->>API: POST /api/user/create_booking.php {service_ids, date, start_time}
    API->>API: Compute cumulative duration & end_time
    API->>API: Verify weekly schedule & partial closures
    API->>Mutex: SELECT GET_LOCK('booking_lock_YYYY-MM-DD', 5)
    Note over Mutex: Serializes reservation evaluations per date
    API->>DB: BEGIN TRANSACTION
    API->>DB: Check overlapping bookings (status in 'pending','approved')
    alt Slot Overlap Detected
        API->>DB: ROLLBACK
        API->>Mutex: SELECT RELEASE_LOCK('booking_lock_YYYY-MM-DD')
        API-->>Customer: 409 Conflict ("Time slot is no longer available")
    else Slot Free
        API->>DB: INSERT INTO bookings (..., status='pending')
        API->>DB: INSERT INTO booking_services (price snapshots)
        API->>DB: COMMIT TRANSACTION
        API->>Mutex: SELECT RELEASE_LOCK('booking_lock_YYYY-MM-DD')
        API->>FCM: Send FCM Push to admin_devices
        API->>DB: INSERT INTO notifications (user_type='admin', ...)
        API-->>Customer: 200 OK ("Booking created successfully")
    end
                    
⚡ 2-Hour Rescheduling Cutoff Rule

Customers can reschedule only pending or approved bookings, provided the original appointment is at least 120 minutes away:

$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);
}
  • Resets booking status to pending for admin confirmation.
  • Resets all reminder flags (reminder_sent=0, reminder_20m_sent=0).
🔒 Transaction Boundary Safety

External network calls (e.g., Firebase Cloud Messaging) are never executed inside a MySQL transaction to prevent holding row locks:

$pdo->beginTransaction();
$stmt->execute([$bookingId]); // Update status to 'approved'
$logStmt->execute([...]);     // Log notification in DB
$pdo->commit();               // COMMIT FIRST! Row lock released.

// Outside transaction: network latency does not block database
sendFCMNotification($tokens, $title, $message);
  • Prevents connection pool starvation during slow network hops.
  • Guarantees atomicity of database updates.

Database Schema Reference (15 Relational Tables)

Table Primary Keys & References Critical Indexes & Constraints Role
users id (INT PK) UNIQUE(phone), UNIQUE(email), INDEX(phone) Customer identity, phone, gender, date_of_birth, BCrypt hash
user_sessions id (PK), user_id (FK → users.id) UNIQUE(token), INDEX(user_id, device_id), INDEX(expires_at, last_used) 30-day auto-login bearer tokens, session rotation & revocation
user_devices id (PK), user_id (FK → users.id) UNIQUE(fcm_token(255)), ENUM('android','ios','web') Active FCM tokens for customer push notifications
admins id (INT PK) UNIQUE(email), ENUM('admin','super_admin') Staff, managers, and super-admin credentials
admin_sessions id (PK), admin_id (FK → admins.id) UNIQUE(token), INDEX(admin_id, device_id) Admin auto-login tokens with rotation capability
admin_devices id (PK), admin_id (FK → admins.id) UNIQUE(fcm_token(255)) FCM tokens for admin push notifications & booking alerts
services id (INT PK) INDEX(status), INDEX(price) Salon services, duration_minutes, price, image_url
bookings id (PK), user_id, service_id UNIQUE(booking_date, start_time, end_time), INDEX(perf_overlap) Customer appointments, start/end time, status ('pending','approved','completed')
booking_services id (PK), booking_id (FK), service_id (FK) UNIQUE(booking_id, service_id), price DECIMAL(10,2) Multi-service pivot table with price snapshot at booking time
salon_schedule id (PK), day_of_week UNIQUE ENUM('Mon'..'Sun'), open_time, close_time, is_closed Weekly recurring salon opening and closing operating hours
closed_dates id (PK), closed_date DATE UNIQUE INDEX(closed_date) Full-day holiday or emergency closures
closed_time_slots id (PK) INDEX(closed_date, start_time, end_time) Partial closure windows (lunch breaks, salon maintenance)
notifications id (PK) INDEX(user_type, user_id), INDEX(is_read) In-app notification records for customer and admin history
app_settings id (PK=1 Single Row) maintenance_*, min_app_version_*, slot_interval_minutes Dynamic platform settings and operational toggles
reviews id (PK), booking_id (FK), user_id (FK) UNIQUE(booking_id), rating TINYINT (1-5) Customer ratings and reviews on completed appointments
promotions id (PK) valid_until DATE, is_active BOOLEAN Marketing discount cards and special offer banners

Authentication & Session APIs

POST /api/auth/register.php Customer Registration with Sri Lankan Phone Validation
Public

Validates phone against regex ^(?:0|\+94)[0-9]{9}$, generates 64-char crypto token, creates 30-day session.

{
  "name": "Jane Perera",
  "phone": "0771234567",
  "gender": "female",
  "password": "secretPassword123",
  "email": "jane@example.com",
  "date_of_birth": "1998-05-14",
  "device_id": "uuid_v4_device_id",
  "device_type": "android",
  "fcm_token": "fcm_token_string"
}
POST /api/auth/login.php Customer Login & Session Rotation
Public

Deletes old session for the given device_id, creates fresh token, upserts FCM token.

{
  "phone": "0771234567",
  "password": "secretPassword123",
  "device_id": "uuid_v4_device_id",
  "device_type": "android",
  "fcm_token": "fcm_token_string"
}
POST /api/auth/change_password.php Unified Password Change
Bearer Token

Verifies existing password hash and updates BCrypt hash. Works for both Customer and Admin.

{
  "old_password": "currentPassword",
  "new_password": "newStrongPassword"
}
POST /api/auth/logout.php Token Invalidation
Bearer Token

Deletes bearer token from active sessions in user_sessions and admin_sessions.

Customer APIs (/api/user/)

GET /api/user/get_available_times.php Dynamic Availability Calculator
Public

Calculates available bookable slots checking schedule, closed dates, partial closures, and existing bookings.

GET /api/user/get_available_times.php?date=2026-11-05&service_ids=1,3&interval=60

Response:
{
  "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 Mutex-Protected Multi-Service Reservation
Customer Token

Acquires MySQL mutex lock booking_lock_<date>, checks overlaps, saves price snapshots into booking_services, dispatches FCM to all admins.

{
  "service_ids": [1, 4],
  "booking_date": "2026-11-05",
  "start_time": "14:00:00"
}
POST /api/user/reschedule_booking.php Reschedule Appointment (2-Hour Cutoff Guard)
Customer Token

Validates 2-hour cutoff rule, acquires date mutex lock, resets status to pending, alerts admins.

{
  "booking_id": 45,
  "new_date": "2026-11-10",
  "new_time": "11:00"
}
POST /api/user/cancel_booking.php Customer Cancellation
Customer Token

Sets status to cancelled, writes in-app user notification, dispatches push alert to admin devices.

{
  "booking_id": 45,
  "reason": "Family emergency"
}
GET /api/user/my_bookings.php Customer Appointment History with Multi-Service Rollup
Customer Token

Returns bookings with aggregated service names, total price, total duration, and cast types for Flutter.

POST /api/user/submit_review.php Submit 1-5 Star Review
Customer Token

Permitted only on completed appointments. Upserts review into reviews table.

{
  "booking_id": 42,
  "rating": 5,
  "comment": "Master stylist delivered exceptional results!"
}

Admin Management APIs (/api/admin/)

POST /api/admin/admin_login.php Admin Credential Verification & Session Initialization
Public
{
  "email": "admin@saloneagle.com",
  "password": "adminPassword123",
  "device_id": "device_uuid",
  "device_type": "android",
  "fcm_token": "fcm_token_string"
}
GET /api/admin/dashboard_stats.php Live Dashboard Metrics & Revenue Analytics
Admin Token

Returns today's booking counts, pending approvals, total users, and optional date-range revenue analytics.

GET /api/admin/dashboard_stats.php?start_date=2026-10-01&end_date=2026-10-31

Response:
{
  "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,
    "total_revenue": 345000.00
  }
}
POST /api/admin/approve_booking.php Confirm Appointment & Dispatch Customer Push
Admin Token

Updates status to approved, commits transaction, and sends high-priority FCM notification to customer devices.

{
  "booking_id": 45
}
POST /api/admin/reject_booking.php Reject/Cancel Appointment
Admin Token
{
  "booking_id": 45
}
POST /api/admin/complete_booking.php Finalize Service Delivery
Admin Token

Marks approved appointment as completed. Unlocks customer review eligibility.

POST /api/admin/staff.php Staff Accounts Management (Super Admin Guarded)
Super Admin Only

Full CRUD on staff members. Prevents self-deletion. Enforces 403 Forbidden on standard admin tokens.

Common & System Diagnostics (/api/common/)

GET /api/common/health.php Full System Health Ping (Database, Storage, Memory)
Public
{
  "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 }
  }
}
POST /api/common/upload_image.php Secure Multipart File Upload
Bearer Token

Strict MIME validation (image/jpeg, image/png, image/webp), cryptographically random UUID filename, max 5MB, executes under hardened .htaccess.

Automated Scheduled Background Tasks (Cron Engine)

Cron Script Schedule CLI Command Description
cron/send_reminders.php */5 * * * * php cron/send_reminders.php Checks today's approved bookings starting in 15–25 minutes. Sends countdown push notifications to customer & all admins. Sets reminder_20m_sent=1.
cron/booking_reminder.php 0 18 * * * php cron/booking_reminder.php Runs daily at 6:00 PM for tomorrow's approved bookings. Sends 24h advance reminder push to customer. Sets reminder_daily_sent=1.
cron/cleanup_sessions.php 0 3 * * * php cron/cleanup_sessions.php Runs daily at 3:00 AM. Deletes expired records from user_sessions and admin_sessions.
cron/daily_close_check.php 0 0 * * * php cron/daily_close_check.php Runs daily at midnight. Automatically transitions past approved appointments to 'completed'.

Production Security Architecture

🛡️ Upload Execution Hardening

The uploads/.htaccess file explicitly disables the PHP engine and prevents execution of all scripts in user-uploaded media directories:

<FilesMatch "\.(php|phtml|php3|php4|php5|php7|php8|phps|cgi|pl|py|sh|inc|htaccess)$">
    Order Deny,Allow
    Deny from all
</FilesMatch>
php_flag engine off
Options -ExecCGI -Indexes
⚡ Atomic File-Locked Rate Limiter

rate_limit.php protects authentication endpoints by managing sliding timestamp windows via non-blocking atomic file locks (flock(LOCK_EX)):

  • Limits requests to 15 per minute per client IP.
  • Extracts real client IP via Cloudflare / X-Forwarded-For headers.
  • Returns HTTP 429 Too Many Requests with Retry-After.
Copied to clipboard!