# ABC Core Architecture (Phase 1.1)

## Design Philosophy

ABC Core is built around **separation of concerns**, **modular encapsulation**, and **event-driven decoupling**. Every component has a single responsibility and communicates through well-defined contracts.

## Layers

### 1. Entry Layer
- `public/index.php` — Single entry point. Loads bootstrap and runs the application.
- `.htaccess` — URL rewriting to index.php for clean routing.

### 2. Bootstrap Layer
- `app/bootstrap.php` — PSR-4 compatible autoloader. Loads helpers. Defines `BASE_PATH`, `APP_PATH`, `LOG_PATH`.
- `app/Helpers/functions.php` — Global helpers (env, config, logger, encrypt, array utilities).

### 3. Kernel Layer (Core)
The Core is the engine. It is framework-agnostic and owns infrastructure concerns.

- **Application** — Singleton. Bootstraps and runs the request lifecycle.
- **Router** — Route registration, parameter extraction, dispatch.
- **Route** — Route definition DTO.
- **Request** — HTTP request wrapper, input sanitization, Bearer token extraction.
- **Response** — JSON response wrapper with status, headers, and body.
- **Database** — PDO manager with nestable transactions, prepared statements, query builder basics.
- **Config** — Dot-notation configuration loader from PHP files.
- **Environment** — `.env` file parser with type casting.
- **Validator** — Rule-based validation engine.
- **Logger** — File-based logger with levels and context.
- **ExceptionHandler** — Global error/exception handler with JSON responses.
- **MiddlewarePipeline** — Onion-pattern middleware execution.
- **Session** — Secure session management with CSRF tokens and periodic ID regeneration.
- **Auth** — Authentication foundation (password hashing, token generation).
- **SecurityHeaders** — HTTP security headers helper.
- **Event** — Abstract base class for all domain events.
- **EventDispatcher** — Publish/subscribe event bus. Decouples services.
- **Queue** — File-based queue system for shared hosting (no Redis required).
- **UuidGenerator** — UUID v4 generation and validation.
- **Ledger** — Core ledger engine. All financial movement MUST pass through this.

### 4. Contract Layer (Interfaces)
- `MiddlewareInterface` — `handle(Request, callable $next)`
- `RepositoryInterface` — Standard CRUD + `findBy`, `exists`, `count`
- `ServiceInterface` — Marker interface for domain services

### 5. Base Class Layer
- **BaseController** — Injects Request/Response, provides `validate()` helper.
- **BaseRepository** — Implements `RepositoryInterface` with `Database` dependency. The ONLY place SQL is allowed.
- **BaseService** — Injects `Database` and `Logger`, provides `executeInTransaction()` helper.
- **BaseModel** — Property casting, fillable attributes, dirty state tracking.

### 6. Constants Layer
Centralized, typed-safe constants. Never use raw strings in business logic.

- `AccountTypes` — SAVINGS, CURRENT, FIXED_DEPOSIT, etc.
- `Currencies` — NGN, USD, EUR, etc.
- `TransactionTypes` — DEPOSIT, WITHDRAWAL, TRANSFER, etc.
- `NotificationTypes` — TRANSACTION_ALERT, LOGIN_ALERT, etc.
- `ApprovalStatus` — PENDING, APPROVED, DECLINED, etc.
- `UserStatus` — ACTIVE, PENDING_KYC, SUSPENDED, etc.
- `LoanStatus` — DRAFT, APPROVED, DISBURSED, etc.
- `CardStatus` — ACTIVE, FROZEN, BLOCKED, etc.
- `Countries` — ISO 3166-1 alpha-2 codes.

### 7. Shared Layer
Reusable traits and interfaces across modules.

- `HasUuid` trait — UUID generation for models.
- `UuidAwareInterface` — Contract for UUID-exposing models.
- `QueueableInterface` — Contract for background jobs.
- `AuditableInterface` — Contract for audit-logged services.

### 8. Middleware Layer
- **AuthMiddleware** — Enforces Bearer token presence.
- **RateLimitMiddleware** — File-based IP rate limiting.
- **CsrfMiddleware** — Validates CSRF tokens for state-changing requests.
- **SecurityHeadersMiddleware** — Applies X-Frame-Options, CSP, etc.

### 9. Configuration Layer
- `app/Config/app.php` — Application name, environment, debug, key, timezone.
- `app/Config/database.php` — DB host, port, name, credentials, charset.
- `app/Config/security.php` — Rate limits, session settings, password rules, CORS.
- `app/Config/logging.php` — Log level, path, rotation.

### 10. Exception Layer
- `AppException` — Base exception with context support.
- `ValidationException` — 422 with field-level errors.
- `NotFoundException` — 404.
- `AuthenticationException` — 401.
- `DatabaseException` — 500 database errors.

### 11. Module Layer
Each module is self-contained and owns its own:
- Controllers
- Services
- Repositories
- Models
- Routes
- Validation Rules

Modules:
- **Authentication** — Login, register, tokens, password management.
- **Customers** — Customer profiles, KYC, verification.
- **Accounts** — Account creation, balance inquiry, status.
- **Transactions** — Transfers, deposits, withdrawals.
- **Notifications** — Email and in-app notification dispatch.
- **Loans** — Loan application, approval, disbursement, repayment.
- **Cards** — Card issuance, activation, blocking, replacement.
- **Reports** — Statements, exports, analytics.
- **Ledger** — Module-level ledger extensions (Core Ledger lives in Core/Ledger.php).

### 12. Storage Layer
- `storage/logs/` — Application logs
- `storage/cache/` — File-based cache
- `storage/queue/` — File-based job queue
- `storage/exports/` — Generated CSV/PDF exports
- `storage/receipts/` — Generated receipt PDFs
- `storage/uploads/` — Uploaded files
- `storage/temp/` — Temporary files

## Request Lifecycle

1. `public/index.php` loads `bootstrap.php`.
2. `Application::boot()` initializes environment, config, session, DB, router, middleware.
3. `Application::run()` creates `Request` and `Response`.
4. `Router::resolve()` matches URI + HTTP method to a `Route`.
5. All module route files are loaded into the router.
6. `MiddlewarePipeline::then()` executes middleware stack (onion pattern).
7. Controller method is invoked with `Request` and route parameters.
8. Controller calls `Service` (business logic).
9. Service calls `Repository` (data access).
10. Service may publish `Event` via `EventDispatcher`.
11. Event listeners may queue jobs via `Queue`.
12. Controller returns data or a `Response`.
13. `Response::send()` outputs JSON and terminates.

## Event-Driven Decoupling

Services communicate via events instead of direct calls:

```
TransferService
  ↓
  dispatches TransferCompletedEvent
  ↓
  EventDispatcher
  ↓
  NotificationListener → queues EmailNotificationJob
  ↓
  AuditListener → writes AuditLog
  ↓
  ReceiptListener → queues ReceiptGenerationJob
```

Benefits:
- TransferService does not know about notifications, audit, or receipts.
- Listeners can be added or removed without changing the service.
- Events never fail the main transaction. Exceptions are caught and logged.

## Database & Transactions

- `Database` uses PDO with `ERRMODE_EXCEPTION` and `FETCH_ASSOC`.
- `beginTransaction()` is nestable (counter-based).
- Only `commit()` or `rollBack()` at counter 0 actually execute.
- `BaseRepository` enforces all SQL to live in repository subclasses.
- `BaseService::executeInTransaction()` wraps callbacks in safe transaction blocks.
- Financial operations MUST use `executeInTransaction()`.

## API Versioning

All routes are prefixed with `/api/v1/`.

Example:
```
GET /api/v1/auth/login
POST /api/v1/customers
GET /api/v1/accounts/{uuid}
POST /api/v1/transfers
```

Future versions are added as new module route files or route groups:
```
GET /api/v2/customers
```

The core router, services, and repositories do not change. Only controllers and route files are versioned.

## Ledger-First Architecture

Money must NEVER be modified directly.

Forbidden:
```sql
UPDATE accounts SET balance = balance - 100
```

Required flow:
```
Transaction Request
  ↓
Service validates
  ↓
Ledger.recordEntry(debit, credit, amount, currency, type)
  ↓
Ledger verifies balance
  ↓
Balance updated via ledger recalculation
  ↓
Audit log written
  ↓
Receipt queued
  ↓
Notification event dispatched
  ↓
Database commit
```

## Security

- Prepared statements only.
- `password_hash()` with BCRYPT cost 12.
- `hash_equals()` for token comparison.
- `AES-256-CBC` for data encryption (requires `APP_KEY`).
- CSRF tokens bound to sessions.
- Rate limiting per IP (file-based, no Redis).
- Security headers applied by default.
- Session ID regeneration every 5 minutes.
- UUIDs exposed in API responses (no sequential IDs).

### 13. Module Dependencies (Phase 2)

**Authentication Module**
- Uses Users Repository for user data access
- Owns: Sessions, Login History, Password Resets, Password History
- Provides: Register, Login, Logout, Password Management

**Users Module**
- Owns: User data, Roles
- Provides: CRUD operations, Search, Status Management, Role Assignment
- Used by: Authentication, Accounts, and future modules

**Accounts Module**
- Uses Users Repository for user validation
- Owns: Account data
- Provides: Account creation, Freeze/Unfreeze, Close
- Does NOT: Modify balances, Process transactions, Access Ledger

### 14. Audit Integration

All Phase 2 services call `AuditService` for every significant action:
- User registration → `USER_REGISTERED`
- Login success → `LOGIN_SUCCESS`
- Login failure → `LOGIN_FAILED`
- Password change → `PASSWORD_CHANGED`
- User creation → `USER_CREATED`
- User update → `USER_UPDATED`
- User activation → `USER_ACTIVATED`
- User suspension → `USER_SUSPENDED`
- Account creation → `ACCOUNT_CREATED`
- Account freeze → `ACCOUNT_FROZEN`
- Account close → `ACCOUNT_CLOSED`

Audit failures are logged but never break the main transaction.

### 15. Testing Structure

```
tests/
  Unit/           # Model, utility, and constant tests
  Integration/    # API endpoint tests
```

Tests use the existing database connection and clean up after each run.

### 16. Financial Core (Phase 3)

The Financial Core consists of four engines and two services in `app/Core/` and `app/Modules/Financial/`:

- **ReferenceGenerator** (`app/Core/ReferenceGenerator.php`) — Unique reference generation
- **BalanceEngine** (`app/Core/BalanceEngine.php`) — Balance calculation and updates
- **Ledger** (`app/Core/Ledger.php`) — Double-entry ledger management
- **TransactionService** (`app/Modules/Transactions/Services/TransactionService.php`) — Transaction orchestration
- **FinancialValidationService** (`app/Modules/Financial/Services/FinancialValidationService.php`) — Pre-movement validation
- **ReceiptService** (`app/Modules/Financial/Services/ReceiptService.php`) — Receipt foundation

**Financial Events:**
- `LedgerEntryCreated` — Dispatched after ledger entry creation
- `TransactionCreated` — Dispatched after transaction completion
- `BalanceUpdated` — Dispatched after balance update
- `TransactionReversed` — Dispatched after transaction reversal
- `ReceiptCreated` — Dispatched after receipt creation

**Flow:**
```
TransactionService
  ↓ validate via FinancialValidationService
  ↓ create transaction record
  ↓ Ledger::recordEntry() / recordDoubleEntry()
  ↓ Ledger::verifyDoubleEntry()
  ↓ BalanceEngine::updateBalance()
  ↓ ReceiptService::create()
  ↓ AuditService::log()
  ↓ EventDispatcher::dispatch()
```

No banking APIs (Transfer, Deposit, Withdrawal) are exposed in Phase 3.

## Extensibility

To add a new banking module (e.g., Insurance):

1. Create `app/Modules/Insurance/` with Controllers, Services, Repositories, Models, Routes, Validation.
2. Create `app/Modules/Insurance/Routes/routes.php`.
3. Add route file to `app/routes.php` module route loader.
4. Create `InsuranceRepository` extending `BaseRepository`.
5. Create `InsuranceService` extending `BaseService`.
6. Create `InsuranceController` extending `BaseController`.
7. Register events in a bootstrap or service provider (Phase 2+).

No changes to `Core` are required.
