# NMXpert — Complete User Manual & FAQ

## Table of Contents
1. [System Overview](#1-system-overview)
2. [Architecture & Tech Stack](#2-architecture--tech-stack)
3. [User Roles & Portals](#3-user-roles--portals)
4. [System Flow — Step by Step](#4-system-flow--step-by-step)
5. [Admin Portal Guide](#5-admin-portal-guide)
6. [Member Portal Guide](#6-member-portal-guide)
7. [MLM Compensation Plans](#7-mlm-compensation-plans)
8. [Commission Engine — How It Works](#8-commission-engine--how-it-works)
9. [Wallet System](#9-wallet-system)
10. [Withdrawal Process](#10-withdrawal-process)
11. [KYC Verification](#11-kyc-verification)
12. [Rank & Achievement System](#12-rank--achievement-system)
13. [Genealogy / Network Tree](#13-genealogy--network-tree)
14. [Product & Order Management](#14-product--order-management)
15. [Notifications & Support](#15-notifications--support)
16. [API Reference](#16-api-reference)
17. [Troubleshooting](#17-troubleshooting)
18. [FAQs](#18-faqs)

---

## 1. System Overview

NMXpert is a **multi-tenant SaaS MLM & Network Business Management Platform**. It enables companies to run binary, unilevel, matrix, generation, board, breakaway, matching, rank, leadership, pool, and hybrid compensation plans — all from a single platform.

### Tagline
> **SMART NETWORK. SMARTER GROWTH.**

### Key Capabilities
- Multi-company (tenant) support
- 11 MLM compensation plan types
- Automated commission calculation (binary pairs, direct bonuses, level bonuses)
- 5-type wallet system (commission, purchase, cashback, reward, main)
- Full KYC verification with fraud detection
- Auto rank promotion based on BV/team thresholds
- Real-time genealogy tree visualization (sponsor + placement)
- Withdrawal management with bank/UPI support
- Product catalog with BV/PV/CV tracking
- Role-based access control (11 roles)
- Notification system (in-app, email, SMS, push)
- Support ticket system
- Audit logging

---

## 2. Architecture & Tech Stack

```
┌─────────────────────────────────────────────────────────┐
│                    CLIENT BROWSERS                       │
│         Admin Portal │ Member Portal │ Customer Portal   │
│              Bootstrap 5 + Chart.js + Vanilla JS         │
└────────────────────────┬────────────────────────────────┘
                         │  HTTP/HTTPS (JSON API)
┌────────────────────────▼────────────────────────────────┐
│                   PHP 8.3+ BACKEND                       │
│  ┌──────────┐ ┌───────────┐ ┌──────────────────────────┐│
│  │ Auth     │ │Controllers│ │ Services                 ││
│  │ (JWT)    │ │ (13 total)│ │ Commission│Wallet│Rank   ││
│  └──────────┘ └───────────┘ │ PlanEngine│Fraud│Notif   ││
│  ┌──────────┐ ┌───────────┐ │ CurrencyService          ││
│  │Middleware│ │ Helpers   │ └──────────────────────────┘│
│  │Auth│Role │ │Response   │                              │
│  │RateLimit│ │Validator  │                              │
│  └──────────┘ │JwtHelper  │                              │
│               └───────────┘                              │
└────────────────────────┬────────────────────────────────┘
                         │  PDO (MySQL)
┌────────────────────────▼────────────────────────────────┐
│                    MySQL 8+ DATABASE                     │
│              75 tables │ nmxpert database                │
└─────────────────────────────────────────────────────────┘
```

### File Structure
```
NMXpert/
├── backend/
│   ├── config/          # database.php, app.php, constants.php
│   ├── app/
│   │   ├── Controllers/ # 13 controllers (Auth, Dashboard, Member, etc.)
│   │   ├── Services/    # 8 services (Commission, Wallet, Rank, etc.)
│   │   ├── Middleware/   # Auth, Role, RateLimiter
│   │   ├── Helpers/     # Response, Validator, JwtHelper, Logger, FileUploader
│   │   └── Models/      # Database (PDO singleton)
│   ├── public/          # index.php (API entry point), .htaccess
│   └── routes/          # api.php
├── web/
│   ├── admin/           # 16 admin pages
│   ├── member/          # 14 member pages
│   ├── customer/        # 1 customer page
│   ├── includes/        # header, footer, topbar, sidebars
│   └── assets/          # css/, js/, img/
├── database/
│   └── schema.sql       # 75 tables + seed data
├── node/                # Socket.IO server (real-time)
└── NMXpertlogo.png      # Brand logo
```

---

## 3. User Roles & Portals

### Three Portals

| Portal | URL | Purpose |
|--------|-----|---------|
| **Admin** | `/web/admin/` | Company management, member oversight, approvals |
| **Member** | `/web/member/` | MLM distributor self-service |
| **Customer** | `/web/customer/` | Product browsing & purchase |

### 11 Role Types

| # | Role | Slug | Access Level |
|---|------|------|-------------|
| 1 | Super Admin | `super-admin` | Full system access |
| 2 | Company Admin | `company-admin` | Company-level management |
| 3 | Branch Admin | `branch-admin` | Branch-level management |
| 4 | Finance Manager | `finance-manager` | Wallets, withdrawals, reports |
| 5 | Sales Manager | `sales-manager` | Orders, products, members |
| 6 | KYC Manager | `kyc-manager` | KYC review & approval |
| 7 | Warehouse Manager | `warehouse-manager` | Inventory & stock |
| 8 | Support Executive | `support-executive` | Ticket management |
| 9 | Auditor | `auditor` | Audit logs, read-only reports |
| 10 | Member | `member` | MLM distributor |
| 11 | Customer | `customer` | Product purchaser |

### Default Login Credentials
| Role | Email | Password |
|------|-------|----------|
| Super Admin | `admin@nmxpert.com` | `Admin@123` |
| Demo Member | `demo@member.com` | `password` |

---

## 4. System Flow — Step by Step

### 4.1 Registration Flow

```
New Member ──► Visits Registration Page
                │
                ▼
        Enters: Name, Mobile, Email, Password
        Enters: Sponsor Code (required)
        Enters: Position (left/right for binary)
                │
                ▼
        Backend validates input
        → Checks sponsor exists
        → Creates users record (role_id = 10: member)
        → Creates members record with:
          • Unique member_code (MEM000001)
          • Unique referral_code (ABC12345)
          • sponsor_id → links to sponsor
          • placement_id → links to binary tree parent
          • position → left/right/center
        → Creates 5 wallets (commission, purchase, cashback, reward, main)
        → Places in genealogy tree
        → Sends notification to sponsor
                │
                ▼
        Member Status: "inactive"
        KYC Status: "pending"
```

### 4.2 Activation Flow

```
New Member ──► Submits KYC Documents
                │
                ▼
        Uploads: PAN, Aadhaar, Photo, Bank Statement
        → kyc_requests record created
        → kyc_documents records created
                │
                ▼
        Admin Reviews KYC
        → FraudService checks:
          • Duplicate PAN/Aadhaar
          • Duplicate bank account
          • Duplicate UPI ID
          • Multiple accounts from same IP
        → Risk score calculated (0-100)
                │
                ▼
        KYC Approved → Member Status: "active"
        KYC Rejected → Member must resubmit
                │
                ▼
        OR: Member self-activates via product purchase
        (Activation amount from plan settings)
```

### 4.3 Order & Commission Flow

```
Member ──► Places Order (Product Purchase)
            │
            ▼
    Order Created:
    → order_number generated
    → subtotal, tax, discount, shipping calculated
    → total_bv, total_pv, total_cv computed from products
    → payment_method selected (wallet/online/cod/bank/UPI)
            │
            ▼
    Payment Processed:
    → payment_status = "paid"
    → order_status = "confirmed"
            │
            ▼
    CommissionService Triggered:
    → processOrderCommission(orderId)
    → Runs in DB transaction
            │
            ├─── 1. BINARY BONUS
            │    → Updates left_bv or right_bv based on position
            │    → Matches pairs (min(left_bv, right_bv))
            │    → Applies pair_bonus rate
            │    → Respects max_daily_pairs limit
            │    → Creates commission_transactions record
            │    → Credits commission wallet
            │
            ├─── 2. DIRECT BONUS
            │    → % of order BV paid to sponsor
            │    → Creates commission_transactions record
            │    → Credits commission wallet
            │
            └─── 3. LEVEL BONUS
                 → Walks up sponsor chain (up to 5 levels)
                 → Level 1: 10%, Level 2: 5%, Level 3: 3%, etc.
                 → Each level gets its own commission_transactions
                 → Each credited to respective member's wallet
            │
            ▼
    Wallet Transactions Logged:
    → balance_before, balance_after recorded
    → Reference linked to order/commission
            │
            ▼
    Rank Evaluation Triggered:
    → RankService.evaluateMember(memberId)
    → Checks BV, team size, direct members thresholds
    → Auto-promotes if qualified
    → Creates rank_achievements record
            │
            ▼
    Notifications Sent:
    → Order confirmation to buyer
    → Commission earned to each recipient
    → Rank promotion (if applicable)
    → New order alert to admin
```

### 4.4 Withdrawal Flow

```
Member ──► Requests Withdrawal
            │
            ▼
    Input: amount, payment_method (bank/UPI), bank details
            │
            ▼
    Backend Validates:
    → Member has sufficient wallet balance
    → Amount within min/max limits (from plan)
    → KYC status = "approved"
    → No pending withdrawal
            │
            ▼
    Withdrawal Created:
    → withdrawal_number generated
    → fee calculated (% from plan)
    → tax deducted (TDS % from plan)
    → net_amount = amount - fee - tax
    → status = "pending"
    → Wallet balance debited immediately
            │
            ▼
    Admin Reviews:
    → Views withdrawal details
    → Checks member history
    → Approves or Rejects
            │
            ├─── APPROVED
            │    → status = "approved"
            │    → processed_by, processed_at recorded
            │    → Admin processes payment
            │    → status = "paid"
            │    → paid_at recorded
            │
            └─── REJECTED
                 → status = "rejected"
                 → rejection_reason required
                 → Wallet balance credited back
                 → Member notified
```

### 4.5 Rank Promotion Flow

```
RankService.evaluateMember(memberId)
            │
            ▼
    Fetches member's current stats:
    → personal_bv, team_bv
    → direct_members, active_team
    → left_bv, right_bv
    → monthly_sales
            │
            ▼
    Iterates through ranks (ascending level):
    For each rank:
    → Checks min_personal_bv threshold
    → Checks min_team_bv threshold
    → Checks min_direct_members threshold
    → Checks min_left_bv / min_right_bv
    → Checks min_active_members
    → Checks min_qualified_legs
            │
            ▼
    If ALL thresholds met:
    → Updates members.current_rank_id
    → Sets rank_qualified_at = NOW()
    → Creates member_ranks record
    → Creates rank_achievements record
    → Sends rank promotion notification
    → Calculates rank bonus (if enabled)
            │
            ▼
    Returns: { promoted: true/false, currentRank, nextRank, progress }
```

---

## 5. Admin Portal Guide

### 5.1 Dashboard
**URL:** `/web/admin/dashboard.php`

Shows:
- Total Members, Active Members, New Today
- Total Sales, Total Commission
- Pending Withdrawals, Pending KYC
- Total Products
- Sales Trend chart (line)
- Commission Distribution chart (doughnut)
- Recent Members list
- Recent Orders list

### 5.2 Members Management
**URL:** `/web/admin/members.php`

- **List** all members with search, status filter, pagination
- **View** member details (profile, bank accounts, wallets, rank)
- **Create** new member (admin-initiated)
- **Edit** member details
- **Deactivate** member (soft delete)

### 5.3 Products
**URL:** `/web/admin/products.php`

- Product catalog with BV/PV/CV values
- Categories, variants, pricing
- Inventory management
- Product images & descriptions

### 5.4 Orders
**URL:** `/web/admin/orders.php`

- View all orders
- Update order status (pending → confirmed → processing → shipped → delivered)
- View order items, payments
- Process returns

### 5.5 Plans
**URL:** `/web/admin/plans.php`

- Configure compensation plan parameters
- Set binary pair bonus, unilevel levels, matrix dimensions
- Plan simulator (preview commissions)
- Activate/deactivate plans

### 5.6 Commissions
**URL:** `/web/admin/commissions.php`

- View all commission transactions
- Filter by type, date, status
- Approve pending commissions
- Commission summary & leaderboard

### 5.7 Wallets
**URL:** `/web/admin/wallets.php`

- Overview of all member wallets
- Transaction history
- Manual adjustments (credit/debit)

### 5.8 Withdrawals
**URL:** `/web/admin/withdrawals.php`

- Review pending withdrawal requests
- Approve/reject with reasons
- Process payments
- View withdrawal history

### 5.9 Ranks
**URL:** `/web/admin/ranks.php`

- Define rank levels (8 ranks seeded)
- Set thresholds (BV, team size, direct members)
- Rank bonus amounts
- View rank achievements

### 5.10 KYC
**URL:** `/web/admin/kyc.php`

- Review KYC submissions
- View uploaded documents
- Approve/reject with notes
- Fraud detection alerts

### 5.11 Reports
**URL:** `/web/admin/reports.php`

- Member report (registration, activity)
- Sales report (revenue, orders)
- Commission report (by type, by member)
- Wallet report (balances, transactions)

### 5.12 Settings
**URL:** `/web/admin/settings.php`

- Company profile
- Currency settings
- Withdrawal limits
- KYC requirements
- Notification preferences
- Branding (colors, logo)

### 5.13 Support
**URL:** `/web/admin/support.php`

- View support tickets
- Assign to staff
- Reply to tickets
- Update ticket status

### 5.14 Announcements
**URL:** `/web/admin/announcements.php`

- Create announcements (news/promotion/training/event)
- Target by role
- Schedule publish/unpublish

### 5.15 Audit Logs
**URL:** `/web/admin/audit-logs.php`

- Full trail of all system actions
- Filter by user, action, date
- Export capability

---

## 6. Member Portal Guide

### 6.1 Dashboard
**URL:** `/web/member/dashboard.php`

Shows:
- Member name, code, rank, activation status
- Wallet balances (by type + total)
- Today's income, Monthly income, Total income
- Personal BV, Team BV
- Personal PV, Team PV
- Team stats (direct, total, active, inactive)
- Rank progress bar
- Monthly Income chart
- Commission Split chart

### 6.2 My Network
**URL:** `/web/member/network.php`

- Toggle between Sponsor Tree and Placement Tree
- Visual tree showing up to 3 levels
- Click nodes to expand
- Shows member code, name, BV, status

### 6.3 Referrals
**URL:** `/web/member/referrals.php`

- Personal referral link
- Referral code
- Copy-to-clipboard
- Referral stats (clicks, signups, conversions)

### 6.4 Shop
**URL:** `/web/member/shop.php`

- Browse products
- Search by name
- Filter by category
- View product details (price, BV, PV)
- Add to cart & checkout

### 6.5 My Orders
**URL:** `/web/member/orders.php`

- Order history
- Order status tracking
- Order details (items, payments)
- Download invoices

### 6.6 Income
**URL:** `/web/member/income.php`

- Commission history
- Filter by type (direct, binary, level, etc.)
- Filter by date range
- Income summary

### 6.7 Wallet
**URL:** `/web/member/wallet.php`

- Wallet balances (5 types)
- Transaction history
- Transfer between wallets

### 6.8 Withdrawals
**URL:** `/web/member/withdrawals.php`

- Request withdrawal
- View withdrawal history
- Track status (pending → approved → paid)

### 6.9 Ranks
**URL:** `/web/member/ranks.php`

- Current rank & progress
- Next rank requirements
- Rank history
- Leaderboard

### 6.10 KYC
**URL:** `/web/member/kyc.php`

- Upload documents (PAN, Aadhaar, etc.)
- View submission status
- Resubmit if rejected

### 6.11 Profile
**URL:** `/web/member/profile.php`

- Edit personal details
- Change password
- Update bank accounts
- Two-factor authentication

### 6.12 Notifications
**URL:** `/web/member/notifications.php`

- In-app notification center
- Mark as read / mark all read
- Unread count badge

### 6.13 Support
**URL:** `/web/member/support.php`

- Create support ticket
- View ticket history
- Reply to tickets
- Track status

---

## 7. MLM Compensation Plans

NMXpert supports **11 plan types**. A company can configure one or combine multiple.

### 7.1 Binary Plan
```
         Sponsor
        /       \
     Left       Right
    (Leg)      (Leg)

Pair Matching:
  pair_count = min(left_bv, right_bv) / pair_bonus_rate
  commission = pair_count × pair_bonus_rate
  
Rules:
  - Max pairs per day configurable
  - Carry forward option (unmatched BV rolls over)
  - Flush percentage (resets unmatched BV periodically)
  - Minimum personal BV required
```

### 7.2 Unilevel Plan
```
              You
         / | | | \
       L1  L1 L1 L1    ← Level 1: 10%
      /|\  ...
     L2 L2 L2          ← Level 2: 5%
     ...
     L5 L5 L5          ← Level 5: 1%

Up to 10 levels configurable
Each level has its own percentage
```

### 7.3 Matrix Plan
```
Fixed width × depth:
  3×2 matrix = 3 wide × 2 deep = 9 members max
  2×3 matrix = 2 wide × 3 deep = 14 members max

Completion bonus when matrix fills
Re-entry option for earning again
```

### 7.4 Generation Plan
```
Pays on generational depth:
  Gen 1 (personal recruits): 25%
  Gen 2 (their recruits): 15%
  Gen 3: 10%
  Gen 4: 5%
  
Leadership bonus on deep legs
```

### 7.5 Other Plans
| Plan | Description |
|------|-------------|
| **Board** | Cycling boards (2×1, 2×2) with completion bonuses |
| **Breakaway** | Strong legs "break away" as separate businesses |
| **Matching** | Matches earning of personally sponsored members |
| **Rank** | Bonus paid when rank is achieved |
| **Leadership** | Bonus for leadership positions |
| **Pool** | Profit pool shared among top rankers |
| **Hybrid** | Combination of multiple plan types |

---

## 8. Commission Engine — How It Works

### Commission Types

| Type | Trigger | Recipient | Calculation |
|------|---------|-----------|-------------|
| `direct_bonus` | Order placed | Sponsor | % of order BV |
| `binary_bonus` | Binary pair match | Binary parent | Fixed per pair |
| `level_bonus` | Order placed | Upline chain | % per level |
| `pair_bonus` | Binary match | Binary parent | Per matched pair |
| `matching_bonus` | Referral earns | Sponsor | % of referral's commission |
| `rank_bonus` | Rank achieved | Qualified member | Fixed per rank |
| `leadership_bonus` | Monthly | Top performers | Pool distribution |
| `generation_bonus` | Deep leg order | Senior member | % of generation |
| `cashback` | Order placed | Buyer | % of order value |
| `reward_bonus` | Milestone | Achiever | Fixed reward |

### Commission Flow in Code

```
PlanEngine.calculateCommission(memberId, orderId)
        │
        ├── Fetches order details (amount, BV, position)
        ├── Fetches member details (sponsor, placement, rank)
        ├── Fetches plan configuration
        │
        ├── BINARY:
        │   → Updates member's left_bv or right_bv
        │   → Calculates matched pairs
        │   → Creates commission_transactions
        │   → Credits commission wallet
        │
        ├── UNILEVEL:
        │   → Walks sponsor chain (level 1 → 10)
        │   → Each level gets its percentage
        │   → Creates separate commission_transactions per level
        │
        └── COMMON:
            → Tax deduction (TDS % from plan)
            → Wallet credit via WalletService
            → Wallet transaction logged
            → Notification sent
```

---

## 9. Wallet System

### 5 Wallet Types

| Wallet | Purpose | Credits From | Debits For |
|--------|---------|-------------|------------|
| **Commission** | MLM earnings | Commission payments | Withdrawals, transfers |
| **Purchase** | Product buying | Admin credit | Product orders |
| **Cashback** | Cashback rewards | Order cashback | Withdrawals |
| **Reward** | Bonus rewards | Achievements | Withdrawals |
| **Main** | General purpose | Admin credit | Various |

### Wallet Operations

```
WalletService.credit(memberId, companyId, walletType, amount)
→ Creates wallet if not exists
→ Adds to balance
→ Logs wallet_transactions:
  - transaction_type: credit
  - amount, balance_before, balance_after
  - reference_type, reference_id

WalletService.debit(memberId, companyId, walletType, amount)
→ Validates sufficient balance
→ Subtracts from balance
→ Logs wallet_transactions:
  - transaction_type: debit
  - amount, balance_before, balance_after

WalletService.transfer(fromWalletId, toWalletId, amount)
→ Debits from source
→ Credits to destination
→ Logs both transactions
```

---

## 10. Withdrawal Process

### Step-by-Step

1. **Member requests** → Selects wallet type, amount, payment method
2. **Validation** → Balance check, KYC check, limit check
3. **Deductions** → Fee (% from plan) + TDS (% from plan) deducted
4. **Wallet debited** → Balance reduced immediately
5. **Status: pending** → Awaits admin review
6. **Admin reviews** → Approves or rejects
7. **If approved** → Status: approved → Payment processed → Status: paid
8. **If rejected** → Status: rejected → Wallet credited back

### Payment Methods
- Bank Transfer (IFSC + Account Number)
- UPI (UPI ID)
- Cheque

### Withdrawal Limits
- **Minimum:** Configured per plan (e.g., ₹100)
- **Maximum:** Configured per plan (e.g., ₹50,000)
- **Fee:** Percentage of amount (e.g., 2%)
- **TDS:** Tax deducted at source (e.g., 5%)

---

## 11. KYC Verification

### Required Documents
| Document | Type Key | Purpose |
|----------|----------|---------|
| PAN Card | `pan` | Identity & tax |
| Aadhaar Card | `aadhaar` | Address proof |
| Passport | `passport` | Identity |
| Driving License | `driving_license` | Identity |
| Voter ID | `voter_id` | Identity |
| Bank Statement | `bank_statement` | Address proof |
| Address Proof | `address_proof` | Address verification |
| Photo | `photo` | Profile photo |

### KYC Status Flow
```
pending → approved
pending → rejected → resubmission → pending (resubmitted)
```

### Fraud Detection
Before approval, FraudService checks:
- **Duplicate KYC** → Same PAN/Aadhaar used by another member
- **Duplicate Bank** → Same bank account + IFSC used elsewhere
- **Duplicate UPI** → Same UPI ID used elsewhere
- **Multiple Accounts** → >3 registrations from same IP in 30 days
- **Risk Score** → Composite 0-100 (low/medium/high)

---

## 12. Rank & Achievement System

### 8 Rank Levels (Default)

| Level | Rank | Min Personal BV | Min Team BV | Min Direct | Color |
|-------|------|----------------|-------------|------------|-------|
| 1 | Member | 0 | 0 | 0 | #6b7280 |
| 2 | Associate | 500 | 1,000 | 2 | #8b5cf6 |
| 3 | Bronze | 1,000 | 5,000 | 3 | #cd7f32 |
| 4 | Silver | 2,000 | 15,000 | 5 | #c0c0c0 |
| 5 | Gold | 5,000 | 50,000 | 10 | #ffd700 |
| 6 | Platinum | 10,000 | 150,000 | 20 | #e5e4e2 |
| 7 | Diamond | 25,000 | 500,000 | 50 | #b9f2ff |
| 8 | Crown | 50,000 | 1,000,000 | 100 | #ff6b6b |

### Rank Evaluation Triggers
- After every order
- On admin manual trigger
- On periodic batch job (configurable)

### Rank Benefits
- Higher commission percentages
- Rank bonus payments
- Leadership pool eligibility
- Badge/achievement display

---

## 13. Genealogy / Network Tree

### Two Tree Types

**Sponsor Tree (Upline/Downline)**
```
Shows: Who recruited whom
Structure: Hierarchical (your recruits, their recruits, etc.)
Use: Tracking recruitment chain
```

**Placement Tree (Binary Tree)**
```
Shows: Binary position placement
Structure: Left/Right legs
Use: Binary pair matching, BV tracking
```

### Tree Node Data
Each node shows:
- Member code
- Name
- Personal BV
- Team BV
- Activation status
- Rank

### API Endpoints
- `GET /genealogy/sponsor` → Sponsor tree data
- `GET /genealogy/placement` → Placement tree data

---

## 14. Product & Order Management

### Product Attributes
| Field | Description |
|-------|-------------|
| name | Product name |
| sku | Stock keeping unit |
| price | Retail price |
| sale_price | Discounted price |
| bv | Business Volume (for commissions) |
| pv | Point Volume (for rank) |
| cv | Commission Volume |
| tax_percentage | GST/VAT rate |
| is_active | Published/hidden |
| is_subscription | Subscription product flag |

### Order Lifecycle
```
pending → confirmed → processing → shipped → delivered
                                           → cancelled
                                           → returned
```

### Order Financial Breakdown
```
subtotal = sum(item_prices)
tax_amount = sum(item_taxes)
discount_amount = coupon discount
shipping_amount = shipping charge
total_amount = subtotal + tax - discount + shipping
total_bv = sum(item_bv × quantity)
total_pv = sum(item_pv × quantity)
```

---

## 15. Notifications & Support

### Notification Types
| Type | Icon | Use |
|------|------|-----|
| info | ℹ️ | General information |
| success | ✅ | Confirmations |
| warning | ⚠️ | Alerts |
| error | ❌ | Errors |

### Notification Events
registration, new_referral, order, payment, commission,
rank_achievement, kyc, withdrawal, product, subscription,
support_ticket, announcement

### Support Ticket System
```
Ticket Lifecycle:
  open → in_progress → waiting → resolved → closed

Priority Levels:
  low → medium → high → urgent

Features:
  - Threaded messages
  - Internal notes (staff only)
  - File attachments
  - Assignment to staff
  - Status tracking
```

---

## 16. API Reference

### Base URL
```
http://localhost/NMXpert/backend/public/index.php/
```

### Authentication
All authenticated endpoints require:
```
Authorization: Bearer <jwt_token>
```

### Response Format
```json
{
  "success": true,
  "message": "Request successful",
  "data": { ... },
  "errors": []
}
```

### Error Format
```json
{
  "success": false,
  "message": "Invalid credentials",
  "data": null,
  "errors": []
}
```

### Complete Endpoint List

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| POST | `/auth` | No | Login |
| POST | `/auth/register` | No | Register |
| POST | `/auth/refresh` | No | Refresh token |
| POST | `/auth/logout` | Yes | Logout |
| GET | `/auth/me` | Yes | Current user |
| POST | `/auth/forgot-password` | No | Reset password |
| POST | `/auth/send-otp` | No | Send OTP |
| POST | `/auth/verify-otp` | No | Verify OTP |
| GET | `/dashboard` | Admin | Admin stats |
| GET | `/dashboard/member` | Member | Member stats |
| GET | `/members` | Admin | List members |
| GET | `/members/{id}` | Admin | Show member |
| POST | `/members` | Admin | Create member |
| PUT | `/members/{id}` | Admin | Update member |
| DELETE | `/members/{id}` | Admin | Delete member |
| GET | `/products` | Yes | List products |
| GET | `/products/{id}` | Yes | Show product |
| GET | `/products/categories` | Yes | List categories |
| POST | `/products` | Admin | Create product |
| PUT | `/products/{id}` | Admin | Update product |
| GET | `/orders` | Yes | List orders |
| GET | `/orders/{id}` | Yes | Show order |
| POST | `/orders` | Yes | Create order |
| PUT | `/orders/{id}/status` | Admin | Update status |
| GET | `/wallet` | Yes | List wallets |
| GET | `/wallet/transactions` | Yes | Transaction history |
| POST | `/wallet/transfer` | Yes | Transfer funds |
| GET | `/withdrawals` | Yes | List withdrawals |
| POST | `/withdrawals` | Yes | Request withdrawal |
| PUT | `/withdrawals/{id}/status` | Admin | Approve/reject |
| GET | `/genealogy/sponsor` | Member | Sponsor tree |
| GET | `/genealogy/placement` | Member | Placement tree |
| GET | `/kyc` | Yes | List KYC |
| POST | `/kyc` | Member | Submit KYC |
| PUT | `/kyc/{id}/status` | Admin | Review KYC |
| GET | `/reports/members` | Admin | Member report |
| GET | `/reports/sales` | Admin | Sales report |
| GET | `/reports/commissions` | Admin | Commission report |
| GET | `/reports/wallets` | Admin | Wallet report |
| GET | `/notifications` | Yes | List notifications |
| GET | `/notifications/unread-count` | Yes | Unread count |
| PUT | `/notifications/{id}/read` | Yes | Mark read |
| PUT | `/notifications/read-all` | Yes | Mark all read |
| GET | `/support` | Yes | List tickets |
| GET | `/support/{id}` | Yes | Show ticket |
| POST | `/support` | Yes | Create ticket |
| POST | `/support/{id}/reply` | Yes | Reply to ticket |
| PUT | `/support/{id}/status` | Admin | Update ticket |
| GET | `/search` | Yes | Global search |

---

## 17. Troubleshooting

### Common Issues

#### "Network error. Please try again."
**Cause:** API endpoint not reachable
**Fix:**
1. Ensure XAMPP Apache is running
2. Check `http://localhost/NMXpert/backend/public/index.php/` loads
3. Verify `.htaccess` is in `backend/public/`
4. Check Apache `mod_rewrite` is enabled

#### "SQLSTATE[42S02]: Table doesn't exist"
**Cause:** Database not imported
**Fix:**
1. Open phpMyAdmin (`http://localhost/phpmyadmin`)
2. Create database `nmxpert`
3. Import `database/schema.sql`

#### "Invalid credentials"
**Cause:** Wrong email/password or user doesn't exist
**Fix:**
1. Check `users` table has the admin user
2. Verify password hash matches
3. Default: `admin@nmxpert.com` / `Admin@123`

#### "Authentication token is required"
**Cause:** Not logged in or token expired
**Fix:**
1. Login again
2. Token expires based on `app.php` config (default: 24 hours)

#### "Insufficient permissions"
**Cause:** Role doesn't have access
**Fix:**
1. Check user's `role_id` in `users` table
2. Verify role slug in `roles` table
3. Admin pages require roles 1, 2, or 3

#### Dashboard shows loading forever
**Cause:** API returning error silently
**Fix:**
1. Open browser DevTools (F12) → Network tab
2. Click the failing request
3. Check Response tab for error message
4. Check Console for JavaScript errors

#### Commission not calculated
**Cause:** Order not paid or commission already processed
**Fix:**
1. Check `orders.payment_status = 'paid'`
2. Check `orders.commission_processed = 0`
3. Check `commission_rules` has matching rule for the order

#### Wallet balance not updating
**Cause:** Wallet not created for member
**Fix:**
1. Check `wallets` table has record for member
2. Check `wallet_transactions` for the credit/debit record
3. Verify `WalletService::credit()` was called

---

## 18. FAQs

### General

**Q: What MLM plans does NMXpert support?**
A: 11 plan types: Binary, Unilevel, Matrix, Generation, Board, Breakaway, Matching, Rank, Leadership, Pool, and Hybrid. A company can use one or combine multiple.

**Q: Can multiple companies use the same installation?**
A: Yes. NMXpert is multi-tenant. Each company has its own `company_id` that isolates their data. Super Admin manages all companies.

**Q: Is there a mobile app?**
A: The web application is responsive and works on mobile browsers. A React Native mobile app is planned for future development.

**Q: How are commissions calculated?**
A: The `CommissionService` and `PlanEngine` calculate commissions automatically when an order is marked as paid. It processes binary pairs, direct bonuses, and level bonuses in a single database transaction.

**Q: Can I customize the commission percentages?**
A: Yes. Go to Admin → Plans → Edit Plan. You can set percentages for each commission type, level, and plan-specific parameters.

### Registration & Activation

**Q: How does a new member join?**
A: A new member registers with their name, mobile, email, password, and a sponsor code. They are placed in the genealogy tree under their sponsor. Status starts as "inactive" until KYC is approved or they make a qualifying purchase.

**Q: Is the sponsor code required?**
A: Yes. Every member must be sponsored by an existing member. The sponsor code links them in the genealogy tree.

**Q: How does KYC work?**
A: Members upload identity documents (PAN, Aadhaar, etc.) through the KYC page. Admin reviews and approves/rejects. The system runs fraud checks before approval.

**Q: Can a member self-activate?**
A: Yes. If the plan has an `activation_amount` set, purchasing products worth that amount activates the account automatically.

### Commissions & Income

**Q: When are commissions paid?**
A: Commissions are calculated and credited to the member's wallet instantly when an order is confirmed as paid. The commission status starts as "pending" and moves to "approved" then "paid".

**Q: What is BV, PV, and CV?**
A: 
- **BV (Business Volume)** — Used for binary pair matching and commission calculations
- **PV (Point Volume)** — Used for rank qualification
- **CV (Commission Volume)** — Used for commission calculations

**Q: How does the binary bonus work?**
A: Each member has a left leg and right leg. When orders come in on both sides, pairs are matched. Commission is paid for each matched pair up to the daily maximum.

**Q: What is the level bonus?**
A: When a member makes a purchase, their sponsor gets a % (e.g., 10%), the sponsor's sponsor gets a % (e.g., 5%), and so on up to the configured number of levels.

### Wallets & Withdrawals

**Q: How many wallets does each member have?**
A: 5 wallets: Commission, Purchase, Cashback, Reward, and Main. Each serves a different purpose.

**Q: Can I transfer between wallets?**
A: Yes. Members can transfer funds between their own wallets through the Wallet page.

**Q: What are the withdrawal limits?**
A: Minimum and maximum limits are configured per plan. Default: min ₹100, max ₹50,000. A fee (e.g., 2%) and TDS (e.g., 5%) are deducted.

**Q: How long do withdrawals take?**
A: Withdrawals go through: pending → under_review → approved → processing → paid. Admin must manually approve and process the payment.

**Q: What if my withdrawal is rejected?**
A: If rejected, the amount is credited back to your wallet. You'll see the rejection reason. You can fix the issue and request again.

### Ranks

**Q: How do I get promoted?**
A: Ranks are auto-promoted based on meeting thresholds: personal BV, team BV, direct members, and other criteria. The system evaluates after every order.

**Q: What are the benefits of higher ranks?**
A: Higher commission percentages, rank bonus payments, leadership pool eligibility, and achievement badges.

**Q: Can rank be demoted?**
A: The current system only promotes. Demotion rules can be added through the rank configuration.

### Technical

**Q: What technology stack is used?**
A: PHP 8.3+ (backend), MySQL 8+ (database), Bootstrap 5 (frontend), Chart.js (charts), Node.js + Socket.IO (real-time), JWT (authentication).

**Q: How do I reset the admin password?**
A: Run this SQL in phpMyAdmin:
```sql
UPDATE users SET password = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi' WHERE email = 'admin@nmxpert.com';
```
This sets the password to `Admin@123`.

**Q: How do I add a new role?**
A: Insert into the `roles` table:
```sql
INSERT INTO roles (name, slug, description, is_system) VALUES ('Custom Role', 'custom-role', 'Description', 0);
```

**Q: How do I enable dark mode?**
A: Click the moon icon in the topbar. The theme preference is saved in localStorage.

**Q: Can I change the currency?**
A: Yes. Go to Admin → Settings → Company Settings. Change the currency code and symbol. The system supports INR, USD, EUR, GBP, and more.

**Q: How do I backup the database?**
A: In phpMyAdmin, select the `nmxpert` database → Export → Quick → Go. Or use command line:
```bash
mysqldump -u root nmxpert > backup.sql
```

**Q: How do I check if the API is working?**
A: Open browser and navigate to:
```
http://localhost/NMXpert/backend/public/index.php/
```
You should see: `{"success":true,"data":{"name":"NMXpert API","version":"1.0.0"}}`

---

*Document Version: 1.0 | Last Updated: September 2026*
*NMXpert — SMART NETWORK. SMARTER GROWTH.*
