# ═══════════════════════════════════════════════════════════════
# PHASE 1: MEMBERS & DEPENDENTS MODULE
# Module directory: /modules/members/
# ═══════════════════════════════════════════════════════════════
# READ THE MASTER PROMPT FIRST. Follow ALL conventions exactly.

## YOUR TABLES (read/write)
members, member_dependents, member_families, member_addresses, member_contacts,
member_documents, member_photos, member_education, member_employment,
member_notes, member_tags, member_status_history, dependent_status_history,
dependent_documents, dependent_relationship_types, dependent_age_policies,
membership_types, membership_categories, membership_type_fees,
membership_type_benefits, membership_type_documents_required,
membership_type_age_rules, membership_type_capacity,
member_endorsements, endorsement_types, member_custom_fields,
member_custom_field_values, member_balances, member_ledger (READ ONLY),
member_loyalty (READ ONLY)

## REFERENCE TABLES (read only)
sys_nationalities, sys_countries, sys_cities, sys_districts, sys_currencies, auth_users

## PAGES TO BUILD

### 1. Member Listing (`GET /members`)
- Server-side DataTable with columns: Membership #, Photo (thumbnail), Full Name (EN), National ID, Phone, Type, Status, Actions
- Filters bar above table: Status dropdown, Membership Type dropdown, Gender, Date range (join date), Search text
- Action buttons: View, Edit, Print Card
- Toolbar: Add Member, Export (CSV/Excel/PDF), Print
- Stats cards above table: Total Active, New This Month, Frozen, Suspended
- Color-coded status badges

### 2. Create Member (`GET /members/create` and `POST /members`)
- Tabbed form: Personal Info | Contact Details | Address | Employment & Education | Additional Info | Documents
- Tab 1 - Personal: Title, First/Second/Third/Last Name (EN + AR), National ID, Passport #, Nationality (Select2), DOB (Flatpickr), Gender, Marital Status, Blood Type, Photo Upload (with preview)
- Tab 2 - Contact: Primary Phone, Secondary Phone, WhatsApp, Primary Email, Secondary Email, Communication Preference, Language Preference
- Tab 3 - Address: Address Line 1 & 2, Country (Select2), City (Select2 dependent on country), District, Postal Code
- Tab 4 - Employment: Occupation, Employer, Employer Address, Job Title, Education Level
- Tab 5 - Additional: Membership Type (Select2), Sponsors (member lookup Select2), Emergency Contact (name, phone, relation), Medical Conditions, Allergies, VIP checkbox, Notes
- Tab 6 - Documents: Dynamic document upload based on membership_type_documents_required
- On save: Generate membership_number via SequenceGenerator, create member_balances record, create member_families record if family membership, audit log
- AJAX submit

### 3. View Member (`GET /members/{id}`)
- Left column: Photo (large), basic info card (name, number, type, status, QR code placeholder)
- Right column with tabs:
  - **Overview**: All personal details in read-only format, status timeline from member_status_history
  - **Family & Dependents**: List of dependents with add/edit/remove buttons (inline or modal). Show family_code. Add dependent form: name, relationship type, DOB, gender, national ID, photo, phone, documents
  - **Financial**: member_balances summary card, recent invoices table (from invoices table), recent payments table, outstanding balance, credit balance. Link to full financial view.
  - **Documents**: List with upload capability. Each doc shows: type, name, expiry, verified status. Verify button (for authorized users).
  - **Subscriptions**: List from member_subscriptions. Current active subscription highlighted.
  - **Cards**: List from member_cards. Issue new card button.
  - **Freezes**: History from member_freezes.
  - **Violations**: History from violations table.
  - **Notes**: member_notes with add/pin/delete. Confidential notes only visible to authorized users.
  - **Tags**: member_tags with add/remove (autocomplete from existing tags).
  - **Activity**: member_access_log (recent entries), visit_count, last_visit.
  - **Endorsements**: member_endorsements list.
  - **Audit**: Recent audit_log entries for this member.

### 4. Edit Member (`GET /members/{id}/edit` and `POST /members/{id}`)
- Same tabbed form as create, pre-filled with existing data
- Track changes for audit log (old vs new values)

### 5. Change Member Status (`POST /api/members/{id}/status`)
- Modal with: new status, reason, effective date
- Call appropriate stored procedure: sp_activate_member, sp_suspend_member, sp_terminate_member
- Audit log the change

### 6. Member Quick Search (`GET /api/members/search?q=term`)
- Returns JSON array for Select2 AJAX. Search by: membership_number, full_name_en, full_name_ar, national_id, primary_phone.
- Used by OTHER modules (finance, sports, etc.) to look up members.
- Format: `[{"id": 1, "text": "MEM-000001 - John Doe", "membership_number": "MEM-000001", "name": "John Doe", "phone": "..."}]`

### 7. Dependent Management (sub-routes under members)
- `GET /members/{id}/dependents/create` — Add dependent modal/page
- `POST /members/{id}/dependents` — Store dependent
- `GET /members/{id}/dependents/{depId}/edit` — Edit dependent
- `POST /members/{id}/dependents/{depId}` — Update dependent
- `POST /members/{id}/dependents/{depId}/delete` — Remove dependent (soft)
- Validate: relationship type max count, age limits, gender restrictions per dependent_relationship_types

### 8. Membership Types Management
- `GET /membership-types` — List all types with DataTable
- `GET /membership-types/create` — Create form
- `POST /membership-types` — Store
- `GET /membership-types/{id}/edit` — Edit form
- `POST /membership-types/{id}` — Update
- Form includes: All fields from membership_types table, fee configuration (membership_type_fees), benefits (membership_type_benefits), required documents (membership_type_documents_required), age rules

### 9. Membership Categories Management
- Simple CRUD for membership_categories

### 10. Print Member Profile
- `GET /members/{id}/print` — Print-friendly view using print layout

### 11. Endorsement Management
- `GET /members/{id}/endorsements` — List endorsements
- `POST /members/{id}/endorsements` — Create endorsement

## BUSINESS LOGIC
- Member number auto-generated via sp_generate_next_sequence('member_number')
- Family auto-created for family membership types
- Dependent count validated against membership_type.max_dependents
- full_name_en/ar auto-concatenated (the DB trigger handles this, but also set it in PHP)
- Soft delete only (set is_deleted = 1)
- VIP flag visual indicator throughout
- Blacklist flag blocks certain operations

## DASHBOARD WIDGETS
1. **Active Members Count** — Total active members with trend
2. **Membership Distribution** — Pie/donut chart by membership type
3. **New Members This Month** — Count with list of recent additions

## PERMISSIONS USED
members.view, members.create, members.edit, members.delete, members.status, members.financial,
dependents.view, dependents.manage