# Booking Payment System - Comprehensive Guide

## Overview
This system supports flexible payment options for booking resources, allowing admins to offer one-time payments, subscription-based bookings, or both options simultaneously. This is perfect for scenarios like yoga classes where customers can choose between walk-in payment or subscribing to a package.

## Database Architecture

### 1. `booking_resources` Table (Enhanced)

#### New Fields:
- **`payment_mode`** (string): Determines available payment options
  - `one_time`: Only walk-in/single bookings
  - `subscription`: Only subscription packages
  - `both`: Customer can choose either option

- **`subscription_settings`** (JSON): Flexible configuration storage
  ```json
  {
    "auto_renew_default": true,
    "cancellation_policy": "30_days",
    "prorate_refunds": true,
    "grace_period_days": 3
  }
  ```

- **`allow_trial`** (boolean): Enable trial period for subscriptions
- **`trial_days`** (integer): Number of free trial days
- **`setup_fee`** (decimal): One-time setup fee for subscriptions

### 2. `booking_subscription_packages` Table (New)

Stores subscription pricing tiers/packages for each resource.

#### Key Fields:

**Identity:**
- `id`: Primary key
- `booking_resource_id`: Foreign key to resource
- `name`: Package name (e.g., "Monthly Unlimited", "Annual Pass")
- `slug`: URL-friendly identifier
- `description`: Package details

**Pricing:**
- `price`: Subscription price (e.g., 299.00)
- `billing_period`: `weekly`, `monthly`, `quarterly`, `semi_annually`, `annually`
- `billing_interval`: Multiplier for period (e.g., 2 + monthly = every 2 months)

**Duration & Limits:**
- `duration_months`: Total subscription length (NULL = ongoing)
- `max_bookings_per_period`: Booking limit per billing cycle (e.g., 8 classes/month)
- `booking_credits`: Alternative credit-based system
- `credits_reset_period`: When credits renew (`monthly`, `weekly`, `never`)

**Marketing:**
- `original_price`: For showing savings
- `discount_percentage`: Display % saved
- `is_popular`: Highlight as "Most Popular" option

**Access Control:**
- `included_features`: JSON array of benefits
- `restrictions`: JSON for time/day limits

## Use Case Examples

### Example 1: Yoga Studio (Both Options)

**Resource:** Yoga Class
**Payment Mode:** `both`

**One-Time Option:**
- Base Price: RM 50
- Price Type: `per_session`

**Subscription Packages:**

1. **Monthly Unlimited**
   - Price: RM 299/month
   - Max Bookings: Unlimited
   - Billing: Monthly
   - Duration: Ongoing (auto-renew)

2. **8-Class Package**
   - Price: RM 320/month
   - Max Bookings: 8 per month
   - Billing: Monthly
   - Credits Reset: Monthly

3. **Annual Pass**
   - Price: RM 2,999/year
   - Max Bookings: Unlimited
   - Billing: Annually
   - Savings: RM 589 (16%)
   - Popular: Yes

**Customer Choice:**
- Walk-in: Pay RM 50 per session
- Subscribe: Choose from 3 packages above

### Example 2: Co-Working Space (Subscription Only)

**Resource:** Hot Desk
**Payment Mode:** `subscription`

**Subscription Packages:**

1. **Day Pass**
   - Price: RM 39/day
   - Billing: One-time (but recurring structure)
   - Max Bookings: 1 day

2. **Weekly Pass**
   - Price: RM 199/week
   - Billing: Weekly
   - Max Bookings: 5 days/week

3. **Monthly Membership**
   - Price: RM 699/month
   - Billing: Monthly
   - Max Bookings: Unlimited
   - Trial: 7 days free

### Example 3: Tennis Court (One-Time Only)

**Resource:** Tennis Court
**Payment Mode:** `one_time`

**Pricing:**
- Base Price: RM 80
- Price Type: `per_hour`
- No subscriptions offered

## Implementation Recommendations

### A. Admin Interface (Resource Edit Form)

#### Section 1: Payment Mode Selection
```
┌─────────────────────────────────────────┐
│ Payment Options                          │
├─────────────────────────────────────────┤
│                                          │
│ ⚪ One-Time Payment Only                 │
│    Customers pay per booking             │
│                                          │
│ ⚪ Subscription Only                      │
│    Customers must subscribe              │
│                                          │
│ ⚪ Both Options Available (Recommended)   │
│    Customers can choose                  │
│                                          │
└─────────────────────────────────────────┘
```

#### Section 2A: One-Time Payment Settings
(Shows when payment_mode = 'one_time' or 'both')

```
┌─────────────────────────────────────────┐
│ One-Time Payment Settings                │
├─────────────────────────────────────────┤
│                                          │
│ Base Price: [____] RM                    │
│                                          │
│ Price Type: [Per Hour ▼]                 │
│  • Per Hour                              │
│  • Per Day                               │
│  • Per Session                           │
│  • Fixed                                 │
│                                          │
└─────────────────────────────────────────┘
```

#### Section 2B: Subscription Settings
(Shows when payment_mode = 'subscription' or 'both')

```
┌──────────────────────────────────────────────────────────┐
│ Subscription Settings                                     │
├──────────────────────────────────────────────────────────┤
│                                                           │
│ ☑ Allow Free Trial                                       │
│   Trial Days: [7] days                                   │
│                                                           │
│ Setup Fee (Optional): [____] RM                          │
│                                                           │
│ Advanced Settings:                                        │
│  ☑ Enable auto-renewal by default                        │
│  Cancellation Policy: [30 days notice ▼]                 │
│  ☑ Prorate refunds on cancellation                       │
│  Grace Period: [3] days                                  │
│                                                           │
└──────────────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────────────┐
│ Subscription Packages                     [+ Add Package] │
├──────────────────────────────────────────────────────────┤
│                                                           │
│ Package 1: Monthly Unlimited                      ⚙ Edit │
│ ├─ RM 299/month                                           │
│ ├─ Unlimited bookings                                     │
│ └─ Ongoing subscription                                   │
│                                                           │
│ Package 2: 8-Class Package          ⭐ Popular     ⚙ Edit │
│ ├─ RM 320/month                                           │
│ ├─ 8 bookings per month                                   │
│ └─ Ongoing subscription                                   │
│                                                           │
│ Package 3: Annual Pass                            ⚙ Edit │
│ ├─ RM 2,999/year (Save 16%)                              │
│ ├─ Unlimited bookings                                     │
│ └─ 12 months duration                                     │
│                                                           │
└──────────────────────────────────────────────────────────┘
```

#### Package Edit Modal/Form:
```
┌──────────────────────────────────────────────────────────┐
│ Edit Subscription Package                          [X]    │
├──────────────────────────────────────────────────────────┤
│                                                           │
│ Package Name *: [Monthly Unlimited Pass____________]     │
│                                                           │
│ Description:                                              │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Unlimited access to all yoga classes                │ │
│ │                                                      │ │
│ └─────────────────────────────────────────────────────┘ │
│                                                           │
│ ┌─ PRICING ─────────────────────────────────────────┐   │
│ │                                                     │   │
│ │ Subscription Price *: [299.00] RM                  │   │
│ │                                                     │   │
│ │ Billing Period *: [Monthly ▼]                      │   │
│ │   • Weekly                                         │   │
│ │   • Monthly                                        │   │
│ │   • Quarterly (3 months)                           │   │
│ │   • Semi-Annually (6 months)                       │   │
│ │   • Annually (12 months)                           │   │
│ │                                                     │   │
│ │ Bill Every: [1] period(s)                          │   │
│ │ (e.g., "2" + Monthly = every 2 months)            │   │
│ │                                                     │   │
│ │ ☑ Show Savings                                     │   │
│ │   Original Price: [399.00] RM                      │   │
│ │   OR Discount: [25] %                              │   │
│ │   (Will show: "Save RM 100 (25%)")                │   │
│ │                                                     │   │
│ └─────────────────────────────────────────────────────┘   │
│                                                           │
│ ┌─ DURATION & LIMITS ───────────────────────────────┐   │
│ │                                                     │   │
│ │ Subscription Duration:                             │   │
│ │   ⚪ Ongoing (auto-renew until cancelled)          │   │
│ │   ⚪ Fixed: [12] months                            │   │
│ │                                                     │   │
│ │ Booking Limits:                                    │   │
│ │   ⚪ Unlimited bookings                            │   │
│ │   ⚪ Limited: [8] bookings per [month ▼]          │   │
│ │   ⚪ Credit-based: [20] credits                   │   │
│ │      Reset: [Monthly ▼] / [Never ▼]              │   │
│ │                                                     │   │
│ └─────────────────────────────────────────────────────┘   │
│                                                           │
│ ┌─ FEATURES & RESTRICTIONS ──────────────────────────┐   │
│ │                                                     │   │
│ │ Included Features (optional):                      │   │
│ │ ☑ Priority booking                                 │   │
│ │ ☑ Free class cancellations                         │   │
│ │ ☑ Guest pass (2/month)                            │   │
│ │ ☐ Access to premium classes                       │   │
│ │                                                     │   │
│ │ Time Restrictions (optional):                      │   │
│ │ ☐ Weekdays only (Mon-Fri)                         │   │
│ │ ☐ Peak hours excluded (6-9am, 5-8pm)             │   │
│ │ ☐ Weekends only                                   │   │
│ │                                                     │   │
│ └─────────────────────────────────────────────────────┘   │
│                                                           │
│ ┌─ DISPLAY OPTIONS ──────────────────────────────────┐   │
│ │                                                     │   │
│ │ ☑ Mark as "Most Popular"                           │   │
│ │ ☑ Active (visible to customers)                    │   │
│ │ Display Order: [2]                                 │   │
│ │                                                     │   │
│ └─────────────────────────────────────────────────────┘   │
│                                                           │
│              [Cancel]  [Save Package]                     │
│                                                           │
└──────────────────────────────────────────────────────────┘
```

### B. Frontend Booking Form (Customer View)

#### When payment_mode = 'both':

```
┌──────────────────────────────────────────────────────────┐
│ Book Yoga Class                                          │
├──────────────────────────────────────────────────────────┤
│                                                           │
│ Select Payment Option:                                    │
│                                                           │
│ ┌─────────────────────────────┐ ┌──────────────────────┐│
│ │  💳 Pay Per Session          │ │  📅 Subscribe        ││
│ │                              │ │                      ││
│ │  RM 50 per class             │ │  From RM 299/month   ││
│ │  No commitment               │ │  Save up to 20%      ││
│ │                              │ │                      ││
│ │  [Select This Option]        │ │  [View Packages]     ││
│ └─────────────────────────────┘ └──────────────────────┘│
│                                                           │
└──────────────────────────────────────────────────────────┘
```

#### When customer selects "Subscribe":

```
┌──────────────────────────────────────────────────────────┐
│ Choose Your Subscription Package                         │
├──────────────────────────────────────────────────────────┤
│                                                           │
│ ┌─────────────────┐ ┌───────────────────┐ ┌───────────┐│
│ │ 8-Class Package  │ │ Monthly Unlimited │ │Annual Pass││
│ │                  │ │    ⭐ Popular      │ │           ││
│ │ RM 320          │ │ RM 299            │ │ RM 2,999  ││
│ │ per month        │ │ per month         │ │ per year  ││
│ │                  │ │                   │ │           ││
│ │ • 8 classes/mo   │ │ • Unlimited       │ │ • Unlimited││
│ │ • Credits reset  │ │ • No limits       │ │ • 16% Off ││
│ │   monthly        │ │ • Priority        │ │ • Annual  ││
│ │                  │ │   booking         │ │   billing ││
│ │                  │ │                   │ │           ││
│ │ [     Select   ] │ │ [    Select     ] │ │[  Select ]││
│ └─────────────────┘ └───────────────────┘ └───────────┘│
│                                                           │
│ ✨ 7 days free trial • Cancel anytime • Setup fee: RM 0  │
│                                                           │
└──────────────────────────────────────────────────────────┘
```

## Payment Gateway Integration

### Supported Recurring Payment Gateways:

1. **Stripe**
   - Best for: International payments
   - Features: Full subscription management, proration, webhooks
   - Implementation: Stripe Billing + Customer Portal

2. **PayPal**
   - Best for: Wide adoption
   - Features: PayPal Subscriptions API
   - Considerations: Limited customization

3. **Molpay/Razer (Malaysia)**
   - Best for: Local Malaysian market
   - Features: FPX Direct Debit, recurring billing

4. **Billplz (Malaysia)**
   - Best for: Local businesses
   - Features: Collections API with recurring support

### Implementation Strategy:

```php
// booking_resources table
'payment_mode' => 'both',
'subscription_settings' => [
    'supported_gateways' => ['stripe', 'paypal'],
    'default_gateway' => 'stripe'
]

// When customer subscribes
$subscription = Subscription::create([
    'customer_id' => $customer->id,
    'booking_resource_id' => $resource->id,
    'package_id' => $package->id,
    'gateway' => 'stripe',
    'gateway_subscription_id' => 'sub_xxxxx',
    'status' => 'active',
    'current_period_start' => now(),
    'current_period_end' => now()->addMonth(),
    'credits_remaining' => $package->booking_credits,
]);
```

## Additional Database Tables Needed

### 1. `customer_subscriptions` Table
```php
Schema::create('customer_subscriptions', function (Blueprint $table) {
    $table->id();
    $table->foreignId('customer_id')->constrained()->onDelete('cascade');
    $table->foreignId('booking_resource_id')->constrained()->onDelete('cascade');
    $table->foreignId('package_id')->constrained('booking_subscription_packages');

    // Payment gateway details
    $table->string('gateway'); // stripe, paypal, etc.
    $table->string('gateway_subscription_id')->nullable();
    $table->string('gateway_customer_id')->nullable();

    // Subscription status
    $table->string('status'); // active, cancelled, expired, paused
    $table->timestamp('current_period_start');
    $table->timestamp('current_period_end');
    $table->timestamp('cancelled_at')->nullable();
    $table->string('cancel_reason')->nullable();

    // Credits/limits tracking
    $table->integer('credits_remaining')->nullable();
    $table->integer('bookings_this_period')->default(0);
    $table->timestamp('credits_last_reset')->nullable();

    // Trial
    $table->boolean('on_trial')->default(false);
    $table->timestamp('trial_ends_at')->nullable();

    $table->timestamps();
});
```

## Complete Flow Diagrams

### Admin Flow:
1. Create/Edit Booking Resource
2. Choose Payment Mode: one_time / subscription / both
3. If subscription enabled:
   - Configure trial settings
   - Set setup fee
   - Add subscription packages
   - For each package:
     * Set pricing & billing period
     * Define booking limits
     * Add features & restrictions
4. Activate resource

### Customer Flow (payment_mode = 'both'):
1. Browse booking resources
2. Select resource (e.g., Yoga Class)
3. Choose payment option:
   - Option A: One-Time Payment
     * Select date/time
     * Pay RM 50
     * Booking confirmed

   - Option B: Subscribe
     * View available packages
     * Select package (e.g., Monthly Unlimited - RM 299/mo)
     * Enter payment details
     * Subscribe (7-day trial starts)
     * Can now book classes using subscription

4. For subscribers:
   - Book classes (uses credits/unlimited)
   - Track usage in dashboard
   - Manage subscription (upgrade/downgrade/cancel)

## Key Features Summary

✅ **Flexibility**: One-time, subscription, or both payment options
✅ **Multiple Packages**: Create unlimited subscription tiers
✅ **Booking Limits**: Credit-based or quantity-based limits
✅ **Trial Periods**: Optional free trials for subscriptions
✅ **Savings Display**: Show discounts and savings percentages
✅ **Auto-Renewal**: Configurable auto-renewal settings
✅ **Popular Highlighting**: Mark recommended packages
✅ **Feature Restrictions**: Control access by subscription level
✅ **Gateway Agnostic**: Works with Stripe, PayPal, local gateways

## Next Steps

1. ✅ Database migrations completed
2. ✅ Models created with relationships
3. 🔄 Update UI forms (in progress)
4. ⏳ Controller logic for CRUD operations
5. ⏳ Frontend booking form with package selection
6. ⏳ Payment gateway integration
7. ⏳ Subscription management dashboard
8. ⏳ Credit/usage tracking system
9. ⏳ Webhooks for subscription events

---

**This architecture provides maximum flexibility for any booking scenario while maintaining simplicity for admins and customers.**
