# Event Ticket Purchase Flow

## Overview
This document outlines the complete flow for purchasing event tickets in the Event Management System.

---

## Flow Diagram

```
1. Browse Events → 2. View Event Details → 3. Select Ticket Type → 4. Checkout → 5. Payment → 6. Order Confirmation → 7. Ticket Delivery
```

---

## Detailed Step-by-Step Flow

### **Step 1: Browse Events**
- **Route**: `/events` (public)
- **Controller**: `EventController@index` or `HomeController`
- **View**: `resources/views/events/index.blade.php`
- **Action**: Customer browses available events
- **Features**:
  - View event listings with filters
  - Search by event name, location, date
  - Filter by category, date range
  - View event cards with basic info

---

### **Step 2: View Event Details**
- **Route**: `/events/{slug}`
- **Controller**: `EventShowController@show` or `EventController@show`
- **View**: `resources/views/events/show.blade.php`
- **Action**: Customer views full event details
- **Features**:
  - Event information (title, description, date, venue)
  - Available ticket types with prices
  - Ticket availability status
  - Event organizer info
  - Share/save event functionality

---

### **Step 3: Select Ticket Type & Quantity**
- **Location**: Event detail page
- **Action**: Customer selects:
  - Ticket type (VIP, Regular, Early Bird, etc.)
  - Quantity (within min/max limits per ticket type)
  - Clicks "Buy Tickets" or "Get Tickets" button

**Validation Checks**:
- Ticket type must be active and visible
- Ticket must be on sale (within sale start/end dates)
- Quantity available > 0
- Quantity within min_per_order and max_per_order limits

---

### **Step 4: Checkout Process**
- **Route**: `/checkout/{event}/{ticketType}`
- **Controller**: `CheckoutController@show` → `CheckoutController@store`
- **View**: `resources/views/checkout/show.blade.php`

#### **4a. Checkout Page (GET)**
- Display:
  - Event information
  - Selected ticket type details
  - Quantity selector
  - Price breakdown (subtotal, platform fee, total)
  - Attendee information form:
    - Name (required)
    - Email (required)
    - Phone (optional)
  - Promo code input (optional)
  - Terms & conditions checkbox

#### **4b. Process Checkout (POST)**
**Validations**:
- Quantity: `required|integer|min:{min_per_order}|max:{max_per_order}`
- Attendee name: `required|string|max:255`
- Attendee email: `required|email|max:255`
- Attendee phone: `nullable|string|max:20`

**Process**:
1. Verify ticket type belongs to event
2. Check ticket availability
3. Check if ticket is on sale
4. Calculate totals:
   - Subtotal = ticket_price × quantity
   - Platform fee (if applicable)
   - Discount (if promo code applied)
   - Total = subtotal + platform_fee - discount
5. Create Order record:
   - Generate order_number (format: `ORD-XXXXXXXXXX`)
   - Set status: `pending`
   - Set payment_status: `pending`
   - Store customer info (snapshot)
6. Reserve tickets (update ticket_type quantities):
   - Increment `quantity_sold`
   - Decrement `quantity_available`
7. **If Free Tickets (total = 0)**:
   - Create tickets immediately
   - Generate ticket numbers
   - Set order status: `completed`
   - Set payment_status: `paid`
   - Redirect to dashboard with success message
8. **If Paid Tickets (total > 0)**:
   - Redirect to payment page

---

### **Step 5: Payment Process**
- **Route**: `/payment/{order}`
- **Controller**: `PaymentController@show` → `PaymentController@initialize`

#### **5a. Payment Method Selection**
**Available Payment Methods**:
1. **Paystack** (Online card payment)
   - Direct payment gateway
   - Redirects to Paystack payment page
   - Returns callback after payment

2. **Bank Transfer**
   - Manual payment verification
   - Customer uploads proof of payment
   - Admin verifies and confirms

3. **Cryptocurrency**
   - Manual payment verification
   - Customer uploads transaction proof
   - Admin verifies and confirms

#### **5b. Paystack Payment Flow**
1. **Initialize Payment**:
   - Generate unique transaction reference: `TXN_XXXXXXXXXX_TIMESTAMP`
   - Create Payment record:
     - status: `pending`
     - gateway: `paystack`
     - transaction_reference
   - Call Paystack API to initialize transaction
   - Get authorization URL
   - Redirect customer to Paystack payment page

2. **Customer Pays on Paystack**:
   - Enter card details
   - Complete payment

3. **Payment Callback** (Return from Paystack):
   - **Route**: `/payment/callback?reference=XXX`
   - Verify transaction with Paystack API
   - **If Successful**:
     - Update Payment:
       - status: `successful`
       - gateway_transaction_id
       - paid_at
       - payment_method (card, bank, etc.)
       - card_last4, card_brand
     - Update Order:
       - status: `completed`
       - payment_status: `paid`
       - completed_at
     - **Generate Tickets** (if not already generated)
     - Send confirmation email
     - Redirect to order confirmation page
   - **If Failed**:
     - Update Payment:
       - status: `failed`
       - failure_reason
       - failed_at
     - Return tickets to inventory (decrement sold, increment available)
     - Redirect with error message

4. **Webhook** (Paystack server-to-server):
   - **Route**: `/payment/webhook`
   - Verifies signature
   - Handles `charge.success` event
   - Updates payment and order status
   - Generates tickets if needed

#### **5c. Bank Transfer Flow**
1. Customer selects bank transfer
2. View bank account details
3. Make transfer offline
4. Upload proof of payment (image)
5. Submit payment confirmation:
   - Create Payment record:
     - status: `pending`
     - gateway: `bank_transfer`
   - Store proof of payment file
   - Show message: "Payment will be verified within 2-4 hours"
6. **Admin Verifies** (manual process):
   - Admin reviews payment proof
   - Confirms payment received
   - Updates Payment: status → `successful`
   - Updates Order: status → `completed`, payment_status → `paid`
   - Generates tickets
   - Sends confirmation email

#### **5d. Cryptocurrency Flow**
Similar to bank transfer but with crypto-specific details

---

### **Step 6: Order Confirmation**
- **Route**: `/dashboard/orders/{order}` or `/orders/{order}`
- **Controller**: `CustomerOrderController@show`
- **View**: `resources/views/customer/orders/show.blade.php`

**Displays**:
- Order number and status
- Event details
- Ticket details (if generated)
- Payment information
- Order total breakdown
- Download receipt option
- Request refund option (if applicable)

---

### **Step 7: Ticket Generation & Delivery**

#### **Ticket Creation** (After successful payment):
1. **Generate Tickets**:
   - Loop through order quantity
   - Create Ticket records:
     - ticket_code/ticket_number (unique)
     - QR code generation
     - Link to order, event, ticket_type
     - Set attendee info
     - Status: `valid`
     - Generate PDF ticket (optional)

2. **Email Confirmation**:
   - Send order confirmation email
   - Include:
     - Order details
     - Ticket download links
     - QR codes (if applicable)
     - Event reminder information

3. **Customer Access**:
   - View tickets in dashboard: `/dashboard/tickets`
   - Download individual tickets
   - Transfer tickets (if enabled)
   - View QR codes

---

## Database Tables Involved

1. **events** - Event information
2. **ticket_types** - Available ticket types per event
3. **orders** - Order records
4. **tickets** - Individual ticket records
5. **payments** - Payment transaction records
6. **payment_methods** - Available payment methods
7. **promo_codes** - Discount codes (if applicable)

---

## Key Models & Relationships

### Order
- `belongsTo(User)` - Customer who placed order
- `belongsTo(Event)` - Event being purchased
- `hasMany(Ticket)` - Tickets in the order
- `hasOne(Payment)` - Payment transaction

### Ticket
- `belongsTo(Order)` - Parent order
- `belongsTo(Event)` - Event
- `belongsTo(TicketType)` - Ticket type
- `belongsTo(User)` - Ticket owner

### Payment
- `belongsTo(Order)` - Related order

---

## Important Business Logic

### Ticket Availability
- Check `quantity_available > 0`
- Check `is_active = true`
- Check `is_visible = true`
- Check sale dates: `sale_starts_at` and `sale_ends_at`
- Check if event is published

### Inventory Management
- When order created: Reserve tickets (decrement available)
- When payment fails: Return tickets (increment available)
- When payment successful: Tickets are sold (keep quantities updated)

### Order States
- **pending**: Order created, payment not completed
- **completed**: Payment successful, tickets generated
- **cancelled**: Order cancelled
- **refunded**: Order refunded

### Payment States
- **pending**: Payment initiated, not confirmed
- **successful**: Payment confirmed, order completed
- **failed**: Payment failed
- **refunded**: Payment refunded

---

## Error Handling

### Common Scenarios:
1. **Ticket sold out** → Redirect with error, don't create order
2. **Payment timeout** → Order remains pending, tickets reserved for limited time
3. **Payment failure** → Return tickets to inventory, allow retry
4. **Invalid promo code** → Show error, allow re-entry
5. **Quantity exceeds available** → Show available quantity, adjust

---

## Security Considerations

1. **Authorization**: Users can only access their own orders
2. **Verification**: Order belongs to authenticated user
3. **Validation**: All inputs validated before processing
4. **Transaction Safety**: Database transactions ensure data consistency
5. **Payment Security**: Paystack handles sensitive payment data
6. **Ticket Uniqueness**: Unique ticket codes prevent duplicates

---

## Email Notifications

1. **Order Confirmation** - After successful payment
2. **Payment Pending** - For bank transfer/crypto payments
3. **Payment Received** - When admin confirms manual payment
4. **Ticket Delivery** - With ticket download links
5. **Event Reminder** - Before event date (if configured)

---

## Testing the Flow

### Test Scenarios:
1. ✅ Purchase free tickets (immediate completion)
2. ✅ Purchase paid tickets with Paystack
3. ✅ Purchase with bank transfer
4. ✅ Purchase with promo code
5. ✅ Handle payment failure
6. ✅ Handle sold-out tickets
7. ✅ Handle expired sale dates
8. ✅ Verify ticket generation after payment


