# Family Accounts, Self-Service Portal & Stripe Billing Plan

## Goals & Constraints
- Support members without email addresses (e.g., young children) while keeping them searchable on the reception check-in kiosk.
- Support non-training parents/guardians who log in, manage their children's details, and receive renewal/grading payment links.
- Support mixed family billing:
  - A parent paying for children (and/or a training spouse)
  - A 14-year-old in a family who pays for themselves
  - A husband and wife who both train, where one pays for both
- Provide simple admin workflows to link existing members or create guardian accounts directly from `/members/{id}/edit` (Contact Details).
- **Zero breakage on live production data:** all existing foreign keys (`attendance_sessions`, `gradings`, `member_notes`, `member_group_user`, `logs`) and existing member workflows must remain intact.

---

## 1. Database & Model Architecture (Option B: Evolve `users` + Direct Links)

Rather than splitting `users` and `members` into separate tables or contriving a separate `families` table, we evolve `users` non-destructively and infer families from direct user-to-user relationships.

### `users` table additions
- `email`: make **nullable** (keep the `unique` index; SQLite/MySQL/Postgres allow multiple `NULL` values).
- `role`: add `'guardian'` alongside `'member'`, `'club_manager'`, `'admin'`.
- `is_training_member` (boolean, default `true` for existing `member` rows, `false` for `guardian`—allows a non-training parent to start training later without changing their role).
- `payer_id` (nullable FK → `users.id`) — who receives invoices/renewals for this user (`null` = pays for themselves).

### `user_guardians` pivot table
Links a member (`user_id`) to any parent/guardian/partner (`guardian_id`) who is allowed to view and manage them in the self-service portal:
- `id`
- `user_id` (FK → `users.id`, cascade delete)
- `guardian_id` (FK → `users.id`, cascade delete)
- `relationship` (nullable string, e.g., `'parent'`, `'guardian'`, `'partner'`)
- `can_manage` (boolean, default `true`)
- `timestamps`
- Unique constraint on `['user_id', 'guardian_id']`.

*(Being listed in `user_guardians` with `can_manage = true` grants portal management access, removing the need for a separate `can_manage_family` flag on `users`.)*

### Query Scoping (`User::scopeTrainingMembers`)
- Add `scopeTrainingMembers($query)` (`where('is_training_member', true)`).
- Apply `trainingMembers()` across:
  - `DashboardController` (active member counts, rank distribution, gender split, renewals, missing info)
  - `MemberController` (index, search, missing info, renewals)
  - `CheckInController` (kiosk search—children without emails still appear)
  - `SessionController`, `EngagementController`, and `ReportController`
- Result: non-training `guardian` accounts never appear in attendance, check-in, rank charts, engagement, or active member counts.

### Payer Resolution & Inferred Family
- **Effective Payer (`$user->effectivePayer()`):**
  ```text
  $user->payer ?? $user (self)
  ```
  *(Guard: verify the resolved payer has an `email` before sending invoices or renewal emails.)*
- **Inferred Family / Household (`$user->relatedFamilyMembers()`):**
  Computed directly from relationships without a `families` table:
  - `$user->guardians` (who manages me)
  - `$user->dependants` (who I manage)
  - `$user->payer` (who pays for me)
  - `$user->payingFor` (who I pay for)
  - Co-guardians / siblings (anyone sharing the same guardian or dependant)

### Scenario Mapping
| Scenario | `payer_id` | `user_guardians` | Outcome |
| :--- | :--- | :--- | :--- |
| **1. 7yo, no email + non-training parent** | Child → Parent | `(Child, Parent)` | Parent gets payment links and manages Child in portal. |
| **2. 6yo + 11yo, no email, non-training parent** | Both kids → Parent | `(6yo, Parent)`, `(11yo, Parent)` | Parent logs in once and sees both kids under "My Dependants". |
| **3. 14yo + member parent, 14yo pays for self** | `null` on both | `(14yo, Parent)` *(optional, `can_manage`)* | 14yo gets their own payment links; Parent gets their own. |
| **4. 2 kids + 2 training parents** | Kids → Payer Parent | Both kids linked to both Mom & Dad | Both parents manage both kids in portal; Payer Parent gets the bills. |
| **5. Husband & wife, both training, one pays** | Spouse → Payer Spouse | *(Optional partner link if shared portal access is wanted)* | Payer Spouse receives renewal/grading links for both and sees both in "Paying For". |
| **6. Single adult member** | `null` | *(none)* | Completely untouched. |

---

## 2. Admin UX: Linking Members & `/members/{id}/edit`

### On `/members/{id}/edit` (Contact Details / Family & Billing)
Add a **Family & Billing** panel inside or alongside the Contact Details tab:
1. **Billing / Payer Selector:**
   - *"Pays for themselves"* (`payer_id = null`) or *"Paid by another user"* (searchable dropdown of club members/guardians with an email).
   - Handles children, spouses (husband/wife), and self-paying teens cleanly.
2. **Create New Parent / Guardian Inline:**
   - Modal/drawer pre-filled with the member's `parent_guardian_name`, `emergency_contact_telephone`, and address (`address_1`, `postcode`, etc.).
   - Admin confirms Name + Email, ticks *"Set as Payer"* and/or *"Can manage in portal"*, and optionally ticks *"Clear member's fake email"*.
   - Creates the `guardian` user, attaches `user_guardians`, and sets `payer_id` in one submit.
3. **Link Existing Guardian / Partner / Dependant:**
   - Searchable picker to attach an existing adult member or guardian to `user_guardians` (or link a dependant).
4. **Inferred Family Summary Card:**
   - Shows everyone connected via `payer_id` and `user_guardians` (parents, children, spouse/partner) with one-click navigation between their profiles.
   - Quick **"Add Child / Dependant"** button that creates a new member pre-filled with the same address and `payer_id` / `user_guardians` link.

### Bulk Cleanup / Family Builder Helper
- A lightweight admin tool (e.g., on `/members/missing-info` or a dedicated `/members/family-links` view) to quickly search/select existing members, assign `payer_id` / `user_guardians`, and clear legacy fake emails on children.

---

## 3. Self-Service Portal (`member` & `guardian` Logins)

- **Separate Layout:** Keep `layouts.admin` for `admin` and `club_manager`; route `member` and `guardian` logins to a dedicated `layouts.portal` dashboard.
- **Portal Invites:** **"Send Portal Invite"** button on any member/guardian with an email address, sending a signed password-setup link (reusing Laravel's password reset token mechanics).
- **Portal Features:**
  - **My Profile** (if `is_training_member`): rank, attendance history, gradings, renewal date, and open invoices.
  - **My Dependants / Managed Members** (anyone in `$auth->dependants` where `can_manage = true`): view attendance/gradings and update contact/medical details.
  - **Billing / Invoices:** View and pay any open invoices where `payer_id = auth()->id()`.
- **Authorization:** Enforced via a `MemberPolicy` so users can only view/edit themselves or users linked via `user_guardians` (`can_manage = true`).

---

## 4. Stripe Payment Links & Renewals

Use **`stripe/stripe-php`** directly for one-off renewal and grading payment links (simpler and better suited than Laravel Cashier for non-subscription links).

### `invoices` table
- `id`
- `club_id` (FK → `clubs.id`)
- `member_id` (FK → `users.id` — the student the fee is for)
- `payer_id` (FK → `users.id` — the resolved payer)
- `type` (`'renewal'` | `'grading'`)
- `reference_id` (nullable, e.g., `grading_id`)
- `description` (string)
- `amount` (integer, in pence/cents)
- `currency` (string, e.g., `'gbp'`)
- `status` (`'pending'` | `'paid'` | `'cancelled'`)
- `token` (unique random string for `/pay/{token}`)
- `stripe_checkout_session_id` (nullable string)
- `stripe_payment_intent_id` (nullable string)
- `paid_at` (nullable timestamp)
- `timestamps`

### Payment Link Flow
1. Admin triggers a renewal email (from `/members/renewals` or a member profile) or a grading fee link.
2. System resolves `$payer = $member->effectivePayer()`, creates an `Invoice`, and emails `https://app/pay/{token}` to `$payer->email`.
3. When the payer clicks `/pay/{token}`, the app creates a fresh Stripe Checkout Session on the fly and redirects them to Stripe (avoiding Stripe's 24-hour Checkout URL expiry).
4. Optional enhancement: in the portal or `/pay/{token}`, offer **"Pay all pending invoices"** (e.g., both kids + spouse) in a single Stripe Checkout session.
5. Stripe webhook (`checkout.session.completed`) verifies the signature, marks the `Invoice` as `paid`, extends `$member->renewal_date` (or marks the grading paid), and records an entry in `logs`.

---

## 5. Phased Implementation Roadmap

1. **Phase 1 — Foundation (Non-breaking):**
   - Migrations for `users` (`email` nullable, `is_training_member`, `payer_id`) and `user_guardians` pivot.
   - `User` relationships (`payer`, `payingFor`, `guardians`, `dependants`, `effectivePayer()`, `relatedFamilyMembers()`) and `scopeTrainingMembers()` applied across existing controllers.
2. **Phase 2 — Family & Contact Details UI:**
   - Family & Billing panel on `/members/{id}/edit` (payer selector, inline guardian creation pre-filled from emergency contact/address fields, link existing guardian/partner/dependant).
   - Bulk family-linking & fake-email cleanup helper for existing live members.
3. **Phase 3 — Self-Service Portal:**
   - `layouts.portal`, portal dashboard, invite/password-setup emails, `MemberPolicy`, and dependant profile management.
4. **Phase 4 — Stripe & Renewal Emails:**
   - `invoices` table, `stripe/stripe-php` integration, `/pay/{token}` checkout redirect, webhook handler, and renewal/grading email triggers.
