```markdown
# Showprima Ticketing System - Seat State Machine Analysis

## Overview
This document maps the complete seat lifecycle from selection to check-in, identifying all state transitions, controller methods, database writes, and guard conditions in the Showprima ticketing system.

## Seat State Machine

### Core Database Tables
- **`carts`**: Temporary seat reservations during user session
- **`order_items`**: Final booked seats after payment
- **`event_wise_seat_categories`**: Seat configuration and special states
- **`orders`**: Payment and booking metadata

### Seat States Overview

```
AVAILABLE → IN_CART → BOOKED → CHECKED_IN
     ↓        ↓         ↓
  BLOCKED   VIP_ONLY   RESERVED
     ↓        ↓
 BOOKED_ONLY_MBS
```

## State Transitions Analysis

### 1. AVAILABLE → IN_CART
**Trigger Method:** `Frontend\EventController@TicketAddToCart`
**Route:** `GET /add_to_cart`
**View Trigger:** JavaScript click handler in `event-stage-ticket.blade.php`

**Guard Conditions:**
- ✅ **DB Level:** Check if seat already booked (`OrderItem` with `status=1`)
- ✅ **DB Level:** Check if seat reserved (`OrderItem` with `status=2`) 
- ✅ **DB Level:** Check if seat in another user's cart (`Cart` where `user_id != current_user`)
- ⚠️ **View Only:** Visual color coding shows seat availability (red=selected, yellow=booked)
- ⚠️ **View Only:** Selling period validation (only in `FinalEventBooking` method)

**DB Writes:**
```php
// Table: carts
INSERT INTO carts (
    user_id, event_id, seat_id, seat, amount, 
    seat_color, category, ip, created_at
)
```

**Guard Logic:**
```php
$OrderItems = OrderItem::where('event_id', $request->event_id)
    ->where('seat', $request->seat)->where('status', 1)->first();
if($OrderItems) return response()->json(['status'=>300]);

$CartBooked = Cart::where('user_id', '!=',$user_id)
    ->where('event_id', $request->event_id)
    ->where('seat_id', $request->id)->get()->count();
if($CartBooked>0) return response()->json(['status'=>501]);
```

### 2. IN_CART → AVAILABLE  
**Trigger Method:** `Frontend\EventController@CartItemDelete`
**Route:** `GET /Cart_item_delete`
**View Trigger:** Delete button click in cart widget

**Guard Conditions:**
- ✅ **DB Level:** Verify cart item belongs to current user
- ❌ **No Concurrency Protection:** No locks during deletion

**DB Writes:**
```php
// Table: carts
DELETE FROM carts WHERE id = ?
```

### 3. IN_CART → BOOKED
**Trigger Method:** `Frontend\EventController@EventCheckoutForm` → `Frontend\EventController@thankyou`
**Route:** `POST /cart/checkout/payment` → Payment Success
**Payment Integration:** Stripe Checkout Session

**Guard Conditions:**
- ✅ **DB Level:** Price validation against cart totals
- ✅ **DB Level:** Database transaction for atomicity
- ❌ **No Stock Validation:** No final availability check before booking
- ❌ **Race Condition Risk:** Gap between payment and seat locking

**DB Writes:**
```php
// Table: orders
INSERT INTO orders (booking_id, user_id, event_id, cust_name, 
    cust_email, total_price, status, payment_method, ...)

// Table: order_items  
INSERT INTO order_items (order_id, event_id, user_id, seat, 
    zone, ticket_id, category, status, amount, ...)

// Table: carts
DELETE FROM carts WHERE user_id = ? AND event_id = ?
```

**Ticket Generation:**
```php
// Generate unique ticket ID
$ticketId = $Zone . '' . $randomString . '' . rand(111111, 999999);
$OrderItem->ticket_id = $ticketId;
$OrderItem->status = $ticket_booking->status == "Reserved" ? '2' : "1";
```

### 4. BOOKED → RESERVED
**Trigger Method:** Manual admin action or system logic
**Guard Conditions:** Based on order status in payment flow
**DB Writes:**
```php
// Table: order_items
UPDATE order_items SET status = 2 WHERE order_id = ?
```

### 5. BOOKED/RESERVED → CHECKED_IN
**Trigger Method:** Not implemented in current codebase
**Expected Implementation:** QR code scanning at venue
**DB Writes:** 
```php
// Expected: order_items table
UPDATE order_items SET status = 3, checked_in_at = NOW() WHERE ticket_id = ?
```

## Admin State Overrides

### VIP Seat Management
**Trigger Method:** `Dashboard\TicketController@VipSeatUpdate`
**Route:** `GET /admin/event/vip-seat-update`

**Guard Conditions:**
- ✅ **DB Level:** Cannot set VIP if seat is blocked (`bloked_seat=0`)
- ✅ **DB Level:** Mutual exclusion with blocked seats

**DB Writes:**
```php
// Table: event_wise_seat_categories
UPDATE event_wise_seat_categories 
SET vip_seat = 1 WHERE seats = ? AND event_id = ?
```

### Blocked Seat Management  
**Trigger Method:** `Dashboard\TicketController@BlokedSeatUpdate`
**Route:** `GET /admin/event/bloked-seat-update`

**Guard Conditions:**
- ✅ **DB Level:** Cannot block if VIP (`vip_seat=0`) or booked-only (`booked_only_mbs=0`)
- ✅ **DB Level:** Mutual exclusion with other special states

**DB Writes:**
```php
// Table: event_wise_seat_categories  
UPDATE event_wise_seat_categories 
SET bloked_seat = 1 WHERE seats = ? AND event_id = ?
```

### Booked-Only (MBS) Management
**Trigger Method:** `Dashboard\TicketController@BookedOnlySeatUpdate` 
**Route:** `GET /admin/event/booked-only-seat-update`

**DB Writes:**
```php
// Table: event_wise_seat_categories
UPDATE event_wise_seat_categories 
SET booked_only_mbs = 1 WHERE seats = ? AND event_id = ?
```

## Critical Security Issues

### 🚨 Race Conditions
1. **Cart-to-Booking Gap:** No seat locking between cart addition and payment completion
2. **Concurrent Cart Access:** Multiple users can add same seat to cart simultaneously
3. **Payment Processing:** No validation of seat availability during payment flow

### 🚨 View-Only Validations
1. **Selling Period:** Only validated in UI, not in API endpoints
2. **Visual Indicators:** Seat colors only updated in frontend, no backend enforcement
3. **Stock Limits:** No enforcement of maximum tickets per category

### 🚨 Missing Guard Conditions
1. **Final Availability Check:** No validation before converting cart to order
2. **Concurrency Locks:** No row-level locking during critical operations
3. **Atomic Transactions:** Limited use of database transactions

## Recommended Improvements

1. **Implement Seat Locking:** Add distributed locks during cart-to-booking transition
2. **Add Concurrency Protection:** Row-level locks for seat allocation
3. **Validate at API Level:** Move all business rules from view to controller
4. **Add Stock Management:** Enforce category-wise ticket limits
5. **Implement Check-in:** Complete the state machine with venue entry tracking

## Database Schema Insights

```sql
-- Core state tracking
carts: user_id, seat_id, seat, event_id (temporary)
order_items: order_id, seat, status, ticket_id (permanent)

-- Seat configuration  
event_wise_seat_categories: seats, vip_seat, bloked_seat, booked_only_mbs

-- Status values in order_items:
-- 1 = BOOKED
-- 2 = RESERVED  
-- 3 = CHECKED_IN (inferred, not implemented)
```

*Analysis based on: event-stage-ticket.blade.php, EventController.php, TicketController.php, helpers.php*

## Ticketing Flow Analysis

### 1. Loading Seat Maps

**Primary Routes:**
```php
// Event details and seat map loading
Route::get('event/{identifier}', 'Frontend\EventController@details')->name('event');
Route::get('event/{event_id}/show/{show_id}', 'Frontend\EventController@showDetails')->name('show');
Route::get('event/booking/{identifier}', 'Frontend\EventController@FinalEventBooking')->name('final.booking');

// Zone-based ticket selection  
Route::get('event/ticket/{id}/{slug}', 'Frontend\EventController@EventZoneTickets')->name('event.zone_tickets');

// Hall zone image fetching
Route::post('event/hall-zones-image', 'Frontend\EventController@FetchHallZoneImage')->name('event.fetch.hall.zones-image');
```

**Controller Methods:**
- `Frontend\EventController@details` - Load main event page with seat map
- `Frontend\EventController@showDetails` - Show-specific seating
- `Frontend\EventController@FinalEventBooking` - Final booking interface
- `Frontend\EventController@EventZoneTickets` - Zone-specific seat selection
- `Frontend\EventController@FetchHallZoneImage` - AJAX seat map images

### 2. Toggling Seat Selection

**Primary Routes:**
```php
// Add tickets to cart
Route::get('add_to_cart', 'Frontend\EventController@TicketAddToCart')->name('ticket.add_to_cart');

// Remove cart items
Route::get('Cart_item_delete', 'Frontend\EventController@CartItemDelete')->name('ticket.Cart_item_delete');
```

**Controller Methods:**
- `Frontend\EventController@TicketAddToCart` - Handle seat selection/addition
- `Frontend\EventController@CartItemDelete` - Remove selected seats

### 3. Adding to Cart & Cart Management

**Primary Routes:**
```php
// Cart display
Route::get('cart', 'Frontend\HomeController@CartIndex')->name('cart.index');

// Coupon handling
Route::post('/cart/fetch/coupon', 'Frontend\HomeController@fetchCoupon')->name('front.cart.fetchCoupon');
```

**Controller Methods:**
- `Frontend\HomeController@CartIndex` - Display cart contents
- `Frontend\HomeController@fetchCoupon` - Apply discount coupons

### 4. Pricing Calculations

**Admin Pricing Routes:**
```php
// Fetch category-wise quantities for pricing
Route::post('/admin/fetch-cat-wise-quantity', 'Dashboard\TicketController@fetchCatWiseQunt')->name('admin.fetch-cat-wise-quantity');

// Ticket price management
Route::post('/admin/ticket-price-store', 'Dashboard\TicketController@TicketPriceStore')->name('admin.ticket-price-store');
Route::post('/admin/event/ticket-price-update', 'Dashboard\TicketController@TicketPriceUpdate')->name('admin.event.ticket-price-update');
```

**Controller Methods:**
- `Dashboard\TicketController@fetchCatWiseQunt` - Calculate category-based pricing
- `Dashboard\TicketController@TicketPriceStore` - Store pricing rules
- `Dashboard\TicketController@TicketPriceUpdate` - Update event pricing

### 5. Checkout Process

**Primary Routes:**
```php
// Checkout page
Route::get('cart/checkout', 'Frontend\HomeController@CartCheckoutIndex')->name('cart.checkout');

// Process payment
Route::post('cart/checkout/payment', 'Frontend\EventController@EventCheckoutForm')->name('cart.checkout.payment');

// Legacy booking form
Route::post('event/tickets/submit-ticket-booking-form', 'Frontend\CartController@submitTicketBookingForm')->name('ticket-booking');
```

**Controller Methods:**
- `Frontend\HomeController@CartCheckoutIndex` - Display checkout form
- `Frontend\EventController@EventCheckoutForm` - Process checkout submission
- `Frontend\CartController@submitTicketBookingForm` - Legacy booking processing

### 6. Payment Processing & Webhooks

**PayPal Integration:**
```php
// PayPal payment processing
Route::post('paypal/payment', 'Frontend\PayPalController@PayPalPayment')->name('paypal.payment');

// Payment callbacks
Route::get('payment/success', 'Frontend\PayPalController@callback')->name('payment.callback');
Route::get('payment/failed', 'Frontend\PayPalController@Failed')->name('payment.callback.failed');
```

**Payment Result Pages:**
```php
// Success/failure redirects
Route::get('event/payment/failed', 'Frontend\EventController@failed')->name('payment.failed');
Route::get('event/payment/success', 'Frontend\EventController@thankyou')->name('payment.success');

// Legacy success pages
Route::get('event/{identifier}/thankyou', 'Frontend\CartController@thankyou')->name('success');
Route::get('event/{identifier}/failed', 'Frontend\CartController@failed')->name('failed');
```

**Controller Methods:**
- `Frontend\PayPalController@PayPalPayment` - Initiate PayPal payment
- `Frontend\PayPalController@callback` - Handle successful payments
- `Frontend\PayPalController@Failed` - Handle failed payments
- `Frontend\EventController@thankyou` - Success page
- `Frontend\EventController@failed` - Failure page

### 7. Ticket Issuance & Management

**Booking Management:**
```php
// View booking details
Route::get('/admin/booking_details/{id}', 'Dashboard\AdminController@bookingDetails');

// Export bookings
Route::get('/admin/bookings/export', 'Dashboard\AdminController@downloadBookings')->name('bookings-export');
Route::get('/admin/bookings/export-show-wise', 'Dashboard\AdminController@downloadShowWiseSummary')->name('export-show-wise');

// Ticket listings
Route::get('/admin/order', 'Dashboard\AdminController@ticketList')->name('admin-tickets');
Route::post('/admin/order', 'Dashboard\AdminController@ticketList');
```

**Controller Methods:**
- `Dashboard\AdminController@bookingDetails` - View individual booking
- `Dashboard\AdminController@downloadBookings` - Export booking data
- `Dashboard\AdminController@downloadShowWiseSummary` - Show-wise reports
- `Dashboard\AdminController@ticketList` - List all tickets

## Seat Management System

### Hall & Zone Configuration
```php
// Hall management
Route::get('/admin/hall', 'Dashboard\TicketController@HallList')->name('admin.hall-list');
Route::post('/admin/hall-store', 'Dashboard\TicketController@HallStore')->name('admin.hall-store');
Route::get('/admin/hall-view/{id}', 'Dashboard\TicketController@HallView')->name('admin.hall-view');

// Zone management
Route::get('/admin/zone', 'Dashboard\TicketController@ZoneList')->name('admin.zone-list');
Route::post('/admin/zone-store', 'Dashboard\TicketController@ZoneStore')->name('admin.zone-store');
Route::post('/admin/updateZoneOrder', 'Dashboard\TicketController@updateZoneOrder')->name('admin.zone.updateOrder');
```

### Seat Categories & Containers
```php
// Seat categories
Route::get('/admin/seat-category', 'Dashboard\TicketController@ticketCategoryList')->name('admin.ticket-category');
Route::post('/admin/seat-category-store', 'Dashboard\TicketController@ticketCategoryStore')->name('admin.ticket-category-store');

// Seat containers
Route::get('/admin/seat-container', 'Dashboard\TicketController@SeatContainerList')->name('admin.seat-container-list');
Route::post('/admin/seat-container-store', 'Dashboard\TicketController@SeatContainerStore')->name('admin.seat-container-store');
```

### Special Seat Types
```php
// VIP seats
Route::get('/admin/event/vip-seat/{id}', 'Dashboard\TicketController@VipSeat')->name('admin.event.vip-seat');
Route::get('/admin/event/vip-seat-update', 'Dashboard\TicketController@VipSeatUpdate')->name('admin.event.vip-seat-update');

// Blocked seats
Route::get('/admin/event/bloked-seat/{id}', 'Dashboard\TicketController@BlokedSeat')->name('admin.event.bloked-seat');
Route::get('/admin/event/bloked-seat-update', 'Dashboard\TicketController@BlokedSeatUpdate')->name('admin.event.bloked-seat-update');

// Booked-only seats
Route::get('/admin/event/booked-only-seat/{id}', 'Dashboard\TicketController@BookedOnlySeat')->name('admin.event.booked-only-seat');
Route::get('/admin/event/booked-only-seat-update', 'Dashboard\TicketController@BookedOnlySeatUpdate')->name('admin.event.booked-only-seat-update');
```

## API Endpoints Summary

**Frontend AJAX Endpoints:**
1. `POST /event/hall-zones-image` - Load seat map images
2. `GET /add_to_cart` - Add seats to cart  
3. `GET /Cart_item_delete` - Remove cart items
4. `POST /cart/fetch/coupon` - Apply coupons

**Admin AJAX Endpoints:**
1. `POST /admin/fetch-cat-wise-quantity` - Pricing calculations
2. `POST /admin/updateZoneOrder` - Reorder zones
3. `POST /admin/hall-seat-category-update` - Update seat categories

## Payment Integration

The system integrates with:
1. **PayPal** (primary) - via `srmklive/paypal`
2. **Stripe** support indicated in status.md

Payment flow follows:
1. Cart → Checkout Form → Payment Gateway
2. Success/Failure callbacks handle completion
3. Booking records created on successful payment

## Notes

- The system maintains both new (`EventController`) and legacy (`CartController`) booking flows
- Seat maps are dynamically loaded with zone-based selection
- Complex seat management with VIP, blocked, and category-based pricing
- Full admin interface for venue and pricing configuration
- Export capabilities for booking management and reporting

*Note: Without access to network.har file, timestamps and sequence diagrams cannot be generated. The above represents the complete route-to-controller mapping for the ticketing system.*
