# Project Architecture

## System Overview

The EventBookings Shopify app is a bridge application that connects Shopify stores with the EventBookings API, enabling merchants to display and manage events directly within their Shopify ecosystem.

## Architecture Diagram

```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   Shopify       │    │  EventBookings   │    │  Customer       │
│   Admin Panel   │    │  Shopify App     │    │  Storefront     │
│                 │    │  (PHP)           │    │                 │
├─────────────────┤    ├──────────────────┤    ├─────────────────┤
│ • App Install   │◄──►│ • Dashboard      │    │ • Event Widgets │
│ • Theme Editor  │    │ • API Management │    │ • Event Details │
│ • Store Config  │    │ • Widget Config  │    │ • Booking Flow  │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                              │     │
                              ▼     ▼
                    ┌─────────────────┐    ┌─────────────────┐
                    │ EventBookings   │    │ Shopify Admin   │
                    │ API             │    │ API             │
                    │ (Identity +     │    │ (OAuth +        │
                    │  Events API)    │    │  Store Data)    │
                    └─────────────────┘    └─────────────────┘
```

## Core Components

### 1. Web Application Layer
- **Framework**: PHP (Laravel/Symfony recommended)
- **Purpose**: Main application handling Shopify integration
- **Responsibilities**:
  - Shopify OAuth authentication
  - Dashboard interface
  - API proxy and caching
  - Widget generation

### 2. Database Layer
- **Technology**: MySQL/PostgreSQL
- **Schema**: See [Database Schema](02-database-schema.md)
- **Key Entities**:
  - ShopifyStore
  - StoreSettings
  - EventToggle
  - ShopifyPage (optional)

### 3. API Integration Layer
- **EventBookings API**: OAuth 2.0 client credentials flow
- **Shopify Admin API**: App-based authentication
- **Error Handling**: Retry logic, token refresh, rate limiting

### 4. Widget System
- **JavaScript Components**: Framework-independent widgets
- **Embedding**: Cross-origin script injection
- **Styling**: Theme-adaptive CSS with customization

### 5. Security Layer
- **CSRF Protection**: Token-based request validation
- **CORS Handling**: Controlled cross-origin access
- **OAuth Management**: Secure token storage and refresh

## Data Flow

### 1. App Installation Flow
```
Shopify Store → OAuth Request → App Authorization → Store Registration → Dashboard Access
```

### 2. Event Sync Flow
```
Dashboard → API Credentials → EventBookings Auth → Event Fetch → Database Store → UI Update
```

### 3. Widget Display Flow
```
Storefront → Widget Request → API Data → Component Render → Event Display → Booking Redirect
```

## Directory Structure (PHP/Laravel)

```
eventbookings-shopify-app/
├── app/
│   ├── Http/
│   │   ├── Controllers/
│   │   │   ├── DashboardController.php
│   │   │   ├── ShopifyAuthController.php
│   │   │   ├── WidgetController.php
│   │   │   └── WebhookController.php
│   │   ├── Middleware/
│   │   │   ├── VerifyShopifyWebhook.php
│   │   │   ├── CorsMiddleware.php
│   │   │   └── ShopifyAuth.php
│   │   └── Requests/
│   ├── Models/
│   │   ├── ShopifyStore.php
│   │   ├── StoreSettings.php
│   │   ├── EventToggle.php
│   │   └── ShopifyPage.php
│   ├── Services/
│   │   ├── EventBookingsApi.php
│   │   ├── ShopifyApi.php
│   │   └── TokenManager.php
│   └── Providers/
├── database/
│   ├── migrations/
│   └── seeders/
├── public/
│   ├── widgets/
│   │   ├── events.js
│   │   ├── featured.js
│   │   └── event-components.js
│   └── assets/
├── resources/
│   ├── views/
│   │   ├── dashboard.blade.php
│   │   ├── auth/
│   │   └── widgets/
│   ├── js/
│   └── css/
├── routes/
│   ├── web.php
│   ├── api.php
│   └── webhooks.php
├── storage/
└── tests/
```

## Component Responsibilities

### Controllers

#### DashboardController
- Main app interface
- Tab-based navigation (Settings, Events, Widgets)
- Event toggle management
- Widget configuration

#### ShopifyAuthController
- OAuth flow implementation
- Store registration
- Token validation and refresh

#### WidgetController
- Widget JavaScript generation
- API endpoints for event data
- CORS handling
- Cross-origin security

#### WebhookController
- Shopify webhook processing
- Store updates
- App uninstall handling

### Models

#### ShopifyStore
```php
// Core store information
- shop_domain (string, unique)
- access_token (string, encrypted)
- created_at, updated_at (timestamps)
```

#### StoreSettings
```php
// EventBookings integration settings
- store_id (foreign key)
- client_id (string)
- client_secret (string, encrypted)
- access_token (text, JWT from EventBookings)
- org_uuid (string, extracted from JWT)
- token_expires_at (datetime)
- is_connected (boolean)
- connection_error (text)
```

#### EventToggle
```php
// Event visibility controls
- store_id (foreign key)
- event_uuid (string, from EventBookings API)
- show_event (boolean, default true)
- featured_event (boolean, default false)
```

### Services

#### EventBookingsApi
- Token generation and refresh
- Event data fetching
- Error handling and retries
- JWT processing

#### ShopifyApi
- Store information queries
- Webhook management
- Theme integration

#### TokenManager
- Secure token storage
- Automatic refresh logic
- Expiration handling

## Security Architecture

### Authentication Layers
1. **Shopify OAuth**: Store-level authentication
2. **EventBookings OAuth**: API-level authentication
3. **CSRF Protection**: Request-level security
4. **CORS Policy**: Origin-level control

### Data Protection
- Encrypted token storage
- Secure API communication (HTTPS only)
- Input validation and sanitization
- Rate limiting and abuse prevention

### Error Handling Strategy
- Graceful degradation
- User-friendly error messages
- Detailed logging for debugging
- Automatic retry mechanisms

## Scalability Considerations

### Performance Optimization
- API response caching
- Database query optimization
- CDN for static assets
- Async processing for background tasks

### Monitoring and Maintenance
- Health check endpoints
- Performance metrics
- Error tracking
- Automated testing

## Integration Points

### Required APIs
1. **Shopify Admin API**
   - Store information
   - Theme asset management
   - Webhook subscriptions

2. **EventBookings Identity API**
   - Token generation
   - Organization UUID extraction

3. **EventBookings Events API**
   - Event listing
   - Event details
   - Status and metadata

### Optional Enhancements
- Shopify GraphQL API for advanced queries
- EventBookings webhooks for real-time updates
- Analytics integration for usage tracking

## Development Phases

### Phase 1: Foundation
- Database schema implementation
- Basic Shopify OAuth flow
- EventBookings API integration
- Core models and services

### Phase 2: Dashboard
- Admin interface development
- Event management functionality
- Settings configuration
- Error handling implementation

### Phase 3: Widget System
- JavaScript widget development
- Cross-origin integration
- Theme compatibility testing
- Mobile responsiveness

### Phase 4: Production
- Security audit
- Performance optimization
- Documentation completion
- Deployment automation

This architecture provides a solid foundation for building a robust, scalable EventBookings Shopify integration that matches the functionality of the original Django implementation while leveraging PHP ecosystem best practices.