# Office 365 Calendar Integration Module

This module provides modern OAuth2-based integration with Office 365 calendars, replacing the legacy Exchange Web Services (EWS) implementation.

## Features

- ✅ **OAuth2 Authentication** - Secure, modern authentication flow
- ✅ **Read-only Calendar Access** - Fetch events from Office 365 calendars
- ✅ **Automatic Token Refresh** - Handles token expiration automatically
- ✅ **Fallback Compatibility** - Falls back to EWS if Office 365 is not configured
- ✅ **Dashboard Integration** - Seamlessly integrates with existing calendar tab
- ✅ **Admin Settings** - Easy setup and management interface

## Setup Instructions

### 1. Register Application in Azure AD

1. Go to [Azure Portal](https://portal.azure.com)
2. Navigate to **Azure Active Directory** > **App registrations**
3. Click **New registration**
4. Configure the application:
   - **Name**: `Seraph Calendar Integration`
   - **Supported account types**: `Accounts in this organizational directory only`
   - **Redirect URI**: `Web` - `https://your-domain.com/admin/settings/office365/callback`

### 2. Configure Application Permissions

1. In your registered application, go to **API permissions**
2. Click **Add a permission** > **Microsoft Graph**
3. Select **Delegated permissions**
4. Add these permissions:
   - `Calendars.Read`
   - `offline_access`
   - `openid`
   - `profile`
5. Click **Grant admin consent** (if you're an admin)

### 3. Get Application Credentials

1. Go to **Certificates & secrets**
2. Click **New client secret**
3. Copy the **Application (client) ID** and **Client secret value**

### 4. Configure Environment Variables

Add these to your `.env` file:

```env
OFFICE365_CLIENT_ID=your-application-client-id
OFFICE365_CLIENT_SECRET=your-client-secret-value
OFFICE365_REDIRECT_URI=https://your-domain.com/admin/settings/office365/callback
```

### 5. Access Settings Page

1. Go to **Admin** > **Settings** > **Office 365 Calendar** (`/admin/settings/office365`)
2. Click **Connect Office 365 Calendar**
3. Complete the OAuth flow by signing in with your Office 365 account

## API Endpoints

### Calendar Events
```
GET /api/v1/office365/calendar/events?start_date=2025-01-01&end_date=2025-01-31
```

### Authentication Status
```
GET /api/v1/office365/auth/status
```

### Calendar Connection Status
```
GET /api/v1/office365/calendar/status
```

## Integration with Dashboard

The module automatically integrates with the existing calendar API endpoint (`/api/v1/calendar`). The system will:

1. First try to use Office 365 calendar events (if authenticated)
2. Fall back to EWS if Office 365 is not available
3. Combine with onsite bookings as before

Calendar events from Office 365 are displayed in **green**, while EWS events remain **blue**.

## Database

The module creates a `office365_tokens` table to store OAuth tokens securely:

- `user_id` - Links to the user who authenticated
- `access_token` - Current access token (encrypted)
- `refresh_token` - Token for refreshing access
- `expires_at` - When the access token expires
- `scope` - Granted permissions
- `token_type` - Usually "Bearer"

## Migration from EWS

This module is designed to work alongside the existing EWS integration:

1. **Gradual Migration**: Users can authenticate Office 365 individually
2. **Automatic Fallback**: If Office 365 fails, system falls back to EWS
3. **No Breaking Changes**: Existing calendar functionality continues to work
4. **Better Error Handling**: Clear messages when authentication is needed

## Troubleshooting

### Common Issues

1. **"Calendar authentication failed"**
   - Check that OFFICE365_CLIENT_ID and OFFICE365_CLIENT_SECRET are set
   - Verify the redirect URI matches your Azure app registration
   - Ensure the user has completed OAuth flow in admin settings

2. **"Invalid redirect URI"**
   - Make sure the redirect URI in Azure AD exactly matches your domain
   - Use HTTPS in production environments

3. **"Insufficient privileges"**
   - Verify the user has access to their calendar in Office 365
   - Check that the required permissions are granted in Azure AD

### Logs

The module logs important events:
- Office365 authentication attempts
- Token refresh operations
- Calendar API calls
- Fallback to EWS when needed

Check Laravel logs for detailed error information.

## Security

- All tokens are stored securely in the database
- Access tokens are automatically refreshed before expiration
- The module follows OAuth2 best practices
- No credentials are logged or exposed in the frontend

## Development

The module follows the same pattern as other Seraph modules (Xero, ThreeCX):

```
app/Modules/Office365/
├── controllers/           # Web and API controllers
├── models/               # Office365Token model
├── services/             # Core business logic
├── views/               # Admin interface templates
└── routes.php           # Module routes
```

Key services:
- `Office365AuthService` - Handles OAuth flow and token management
- `Office365CalendarService` - Fetches and formats calendar events
- `Office365ServiceInterface` - Service contract for testability