# Subscription Management Module Usage Instructions

> The `feat/admin-sub/subscription-management` branch introduces a comprehensive, production-ready Subscription and Billing system powered by Laravel Cashier (Stripe). This branch merges with `feat/admin` and `base`, adding both the Administrator controls for catalog management and the User-facing dashboard for plan checkout and account management.

---

## Table of Contents

1. [Module Overview](#1-module-overview)
2. [What You Inherit](#2-what-you-inherit)
3. [Deep Dive: Features & Functionality](#3-deep-dive-features--functionality)
4. [File Paths & Architecture](#4-file-paths--architecture)
5. [Step-by-Step Usage Guide](#5-step-by-step-usage-guide)

---

## 1. Module Overview

This branch establishes the full lifecycle for software-as-a-service (SaaS) billing. It provides two distinct environments:
- **Admin Portal**: Allows administrators to create subscription plans, configure pricing and billing intervals, monitor Stripe synchronization, and view user subscription histories.
- **User Portal**: Introduces user authentication (register/login/profile) and a user dashboard where customers can subscribe to plans, switch tiers (upgrade/downgrade), manage billing, and download invoices.

*For an in-depth technical dive into the architecture, webhooks, and Stripe catalog synchronization rules, please refer to the technical documentation at `docs/subscriptions.md`.*

---

## 2. What You Inherit

By merging with the **Base** and **Admin** branches, this feature inherits:
- **UI Components & Layouts:** Built utilizing standard `<x-common.*>` and `<x-forms.*>` components for consistent forms, tables, and alerts.
- **Admin Architecture:** Inherits the secure admin login flow, middleware, and dashboard layout.
- **New User Architecture:** Introduces user-facing authentication traits, profile management, and a dedicated User Dashboard layout separate from the Admin Portal.
- **Stripe & Cashier Base:** Fully configured `Laravel\Cashier\Cashier` engine to handle the heavy lifting for Stripe API interactions and webhook consumption.

---

## 3. Deep Dive: Features & Functionality

This branch brings specialized features for handling recurring payments:

- **Stripe Catalog Synchronization:** 
  Admins create plans and prices locally in the database, and background queues (`SyncPlan`) automatically synchronize these as Products and Prices within Stripe.
- **Hosted Checkout & Polling:** 
  Users are securely redirected to Stripe's Hosted Checkout page. Upon successful payment, they return to a success page that automatically polls until webhooks confirm the subscription is active.
- **Advanced Plan Switching:** 
  Users can upgrade or downgrade plans seamlessly. Upgrades are prorated and applied immediately. Downgrades are scheduled securely for the end of the current billing cycle via webhook listeners.
- **Free Trial Mechanics:** 
  A one-time, 30-day free trial is automatically applied to new subscriptions. Trial statuses are strictly tracked to prevent abuse.
- **Admin Oversight:**
  Administrators can view all active and historical subscriptions, see exact Stripe price identifiers, and force-cancel user subscriptions if necessary.
- **User Authentication & Profile:** 
  Complete implementation of User login, registration, password recovery, and profile update forms (including profile image uploads).

---

## 4. File Paths & Architecture

Here are the key structural areas introduced in this branch:

### Controllers
- **Admin (`app/Http/Controllers/Admin/Subscription/`)**: `PlanController.php` and `SubscriptionController.php`.
- **User Auth (`app/Http/Controllers/User/Auth/`)**: Login, Register, Forgot Password, Reset Password.
- **User Dashboard (`app/Http/Controllers/User/Dashboard/`)**: `DashboardController.php`, `SubscriptionController.php`, `ProfileController.php`.
- **Public (`app/Http/Controllers/`)**: `PlansController.php` (for the public pricing page).

### Services & Support Logic
- **Services (`app/Services/`)**: `PlanService`, `StripeService`, `SubscriptionService` (Admin) and `SubscriptionCheckoutService`, `SubscriptionInvoiceService` (User).
- **Support Logic (`app/Support/`)**: Core business rules for billing logic (`SubscriptionPlanResolver`, `SubscriptionPlanChange`, `SubscriptionTrial`).

### Models & Stripe Integration
- **Models (`app/Models/`)**: `Plan.php`, `Price.php`, `CashierSubscription.php`. The `User` model is updated to use the `Billable` trait.
- **Stripe Jobs (`app/Jobs/`, `app/Listeners/`)**: `SyncPlan.php`, `SyncStripePlanListener.php`, and `ApplyPendingPlanChange.php`.

### Views
- **Admin Views (`resources/views/pages/admin/subscription/`)**: Interfaces for Plans and Subscriptions management.
- **User Views (`resources/views/pages/user/`)**: Auth screens, Dashboard, Profile, and Subscription management.
- **Public Views (`resources/views/pages/`)**: `plans/index.blade.php`, `subscription/success.blade.php`, `subscription/cancel.blade.php`.

---

## 5. Step-by-Step Usage Guide

### 1. Environment & Database Setup
Configure your `.env` file with your Stripe credentials:
```env
STRIPE_KEY=your_stripe_public_key
STRIPE_SECRET=your_stripe_secret_key
CASHIER_WEBHOOK_SECRET=your_stripe_webhook_secret
```
Run migrations and queue workers:
```bash
php artisan migrate
php artisan queue:work --queue=stripe
```

### 2. Setting Up Plans (Admin)
- Log into the Admin Portal (`/behindthescreen`).
- Navigate to **Plans** under the Subscription section.
- Create a new plan, providing a Title, Description, Billing Cycle (e.g., Monthly), and Amount.
- Verify that the background queue processes the sync and a Stripe Product/Price ID is populated in the database.

### 3. Subscribing (User)
- Navigate to the public `/plans` route.
- Select a plan and proceed through the registration/login flow.
- Complete the Stripe Hosted Checkout process.
- Upon returning, you will be redirected to the User Dashboard.

### 4. Managing Subscription (User)
- Inside the User Dashboard, navigate to the **Subscription** tab.
- Here, you can view your current plan details, download past invoices, switch plans (Upgrade/Downgrade), or Cancel your active subscription.
