# System Architecture: Ziad Backend (Multi-Tenant)

This document provides a high-level overview of how the Ziad Backend is structured, its infrastructure, and how we handle multiple schools (tenants) in a single system.

---

## 1. High-Level Infrastructure

The entire system is containerized using **Docker**, which ensures that the development environment exactly matches production.

- **Web Server (Nginx)**: The entry point for all requests. It handles SSL and routes traffic to the application.
- **Application Core (PHP-FPM)**: Powered by Laravel, this handles all the business logic and API requests.
- **Database (MySQL 8.0)**: A single database instance that stores all system data.
- **Background Workers**: Automated tasks like WhatsApp notifications and financial period closings run in the background to keep the API fast.

---

## 2. Multi-Tenancy Strategy

Ziad is a **Single-Database Multi-Tenant** application. This means:

- **Shared Database**: All schools (tenants) share the same database tables.
- **Data Isolation**: We use a `school_id` column in almost every table (Students, Transactions, Bills, etc.) to ensure that School A can never see School B’s data.
- **Centralized Admin**: System-wide settings and super-admin accounts manage the entire infrastructure, while school admins are restricted to their specific `school_id`.

---

## 3. How Data Flows

The backend serves three main "customers":

1.  **Management Dashboard (Web)**: Used by school staff for accounting, student management, and reporting.
2.  **Parent/Student App (Mobile)**: Dedicated mobile APIs (`/api/mobile/...`) provide a fast, optimized experience for checking grades and paying bills.
3.  **Physical Hardware (Smart Readers)**: IOT devices in the schools connect directly to the backend to process tap-and-go attendance and cashless payments.

---

## 4. Key Design Principles

- **Financial Integrity**: Because we handle school money, every financial change creates a "Transaction" and a corresponding "Journal" entry. This ensures we have a perfect audit trail.
- **Modular Services**: Logic is not trapped in the API routes. If you need to fix how a "Payment" works, you find the `PaymentService`, which is used by both the Web and Mobile apps.
- **Atomic Operations**: We use database transactions for everything. If a payment fails halfway through, the system "rolls back" so no data is partially saved.

---

## 5. Getting Started as a Developer

- **The Blueprint**: All database changes are defined in `database/migrations`. Never change the database manually.
- **The Seeders**: Use `database/seeders` to populate your local environment with the basic parameters (like Account Codes and System Roles).
- **The Tools**:
    - Use `artisan` for command-line tasks.
    - Use the provided Docker setup to spin up your environment in one command.

---
*Target Audience: New Backend Engineers*
