# n8n Webhook Integration Guide

This guide explains how to set up n8n webhook integration for the Mawidi Demo Scheduler.

## Webhook Payload Structure

The scheduler sends the following JSON payload to your n8n webhook:

```json
{
  "bookingReference": "BK-2024-ABC123",
  "duration": 30,
  "selectedDate": "2024-01-15T00:00:00.000Z",
  "selectedTime": "14:00",
  "timezone": "Asia/Riyadh",
  "userInfo": {
    "name": "John Doe",
    "email": "john@example.com",
    "phone": "+966501234567",
    "message": "Looking forward to the demo"
  },
  "submittedAt": "2024-01-10T10:30:00.000Z"
}
```

## Field Descriptions

| Field              | Type    | Description                                        |
| ------------------ | ------- | -------------------------------------------------- |
| `bookingReference` | string  | Unique booking identifier (format: BK-YYYY-XXXXXX) |
| `duration`         | number  | Meeting duration in minutes (30 or 60)             |
| `selectedDate`     | string  | ISO 8601 date string for the booking date          |
| `selectedTime`     | string  | Time in 24-hour format (HH:MM)                     |
| `timezone`         | string  | IANA timezone identifier (default: Asia/Riyadh)    |
| `userInfo.name`    | string  | User's full name (sanitized)                       |
| `userInfo.email`   | string  | User's email address (validated)                   |
| `userInfo.phone`   | string? | Optional phone number (validated if provided)      |
| `userInfo.message` | string  | User's message or requirements (sanitized)         |
| `submittedAt`      | string  | ISO 8601 timestamp of submission                   |

## n8n Workflow Setup

### 1. Create Webhook Node

1. In n8n, create a new workflow
2. Add a **Webhook** node as the trigger
3. Configure webhook settings:
   - **HTTP Method**: POST
   - **Path**: `/mawidi-demo-booking` (or your preferred path)
   - **Authentication**: None (or configure as needed)
   - **Response Mode**: Respond Immediately

### 2. Extract Booking Data

Add a **Set** node to structure the data:

```javascript
// Node: Extract Booking Data
return [
  {
    json: {
      // Booking Details
      bookingRef: $json.bookingReference,
      duration: $json.duration,

      // Date & Time
      bookingDate: new Date($json.selectedDate).toLocaleDateString("en-US", {
        weekday: "long",
        year: "numeric",
        month: "long",
        day: "numeric",
      }),
      bookingTime: $json.selectedTime,
      timezone: $json.timezone,

      // Calculate meeting end time
      startDateTime: new Date(
        `${$json.selectedDate.split("T")[0]}T${$json.selectedTime}:00`,
      ),

      // User Information
      userName: $json.userInfo.name,
      userEmail: $json.userInfo.email,
      userPhone: $json.userInfo.phone || "Not provided",
      userMessage: $json.userInfo.message,

      // Metadata
      submittedAt: $json.submittedAt,
    },
  },
];
```

### 3. Send Confirmation Email

Add a **Gmail** or **Send Email** node:

**Subject:** Booking Confirmed: Mawidi Demo on {{ $json.bookingDate }}

**Body:**

```html
<h2>Demo Booking Confirmed</h2>

<p>Hi {{ $json.userName }},</p>

<p>Your demo session with Mawidi has been confirmed!</p>

<h3>Booking Details:</h3>
<ul>
  <li><strong>Reference:</strong> {{ $json.bookingRef }}</li>
  <li><strong>Date:</strong> {{ $json.bookingDate }}</li>
  <li><strong>Time:</strong> {{ $json.bookingTime }} ({{ $json.timezone }})</li>
  <li><strong>Duration:</strong> {{ $json.duration }} minutes</li>
</ul>

<h3>Your Message:</h3>
<p>{{ $json.userMessage }}</p>

<h3>Next Steps:</h3>
<ol>
  <li>You'll receive a calendar invite shortly</li>
  <li>We'll send a reminder 24 hours before the session</li>
  <li>Meeting link will be included in the calendar invite</li>
</ol>

<p>Looking forward to meeting you!</p>

<p>Questions? Reply to this email or call us at +966 50 123 4567</p>

<hr />
<p><small>Booking submitted at: {{ $json.submittedAt }}</small></p>
```

### 4. Create Google Calendar Event (Optional)

Add a **Google Calendar** node:

- **Operation**: Create Event
- **Calendar**: Your calendar
- **Start**: `{{ $json.startDateTime }}`
- **Duration**: `{{ $json.duration }}` minutes
- **Summary**: `Mawidi Demo - {{ $json.userName }}`
- **Description**:

  ```
  Demo session with {{ $json.userName }}

  Contact: {{ $json.userEmail }}
  Phone: {{ $json.userPhone }}

  Message: {{ $json.userMessage }}

  Booking Reference: {{ $json.bookingRef }}
  ```

- **Attendees**: `{{ $json.userEmail }}`

### 5. Send Internal Notification (Optional)

Add a **Slack** or **Discord** node to notify your team:

```
🎯 New Demo Booking!

📅 Date: {{ $json.bookingDate }}
⏰ Time: {{ $json.bookingTime }}
⏱️ Duration: {{ $json.duration }} min

👤 Name: {{ $json.userName }}
📧 Email: {{ $json.userEmail }}
📱 Phone: {{ $json.userPhone }}

💬 Message: {{ $json.userMessage }}

🔖 Reference: {{ $json.bookingRef }}
```

### 6. Save to Database (Optional)

Add a **MySQL**, **PostgreSQL**, or **MongoDB** node to store bookings:

```sql
INSERT INTO bookings (
  booking_reference,
  duration,
  booking_date,
  booking_time,
  timezone,
  user_name,
  user_email,
  user_phone,
  user_message,
  created_at
) VALUES (
  '{{ $json.bookingRef }}',
  {{ $json.duration }},
  '{{ $json.selectedDate }}',
  '{{ $json.bookingTime }}',
  '{{ $json.timezone }}',
  '{{ $json.userName }}',
  '{{ $json.userEmail }}',
  '{{ $json.userPhone }}',
  '{{ $json.userMessage }}',
  '{{ $json.submittedAt }}'
);
```

## Environment Configuration

Add your n8n webhook URL to your environment variables:

```bash
# .env.local
NEXT_PUBLIC_N8N_WEBHOOK_URL=https://your-n8n-instance.com/webhook/mawidi-demo-booking
```

## Usage in Next.js

```tsx
import { DemoScheduler } from "@/components/DemoScheduler";

export default function DemoPage() {
  return (
    <DemoScheduler
      language="en"
      webhookUrl={process.env.NEXT_PUBLIC_N8N_WEBHOOK_URL}
      onBookingComplete={(data, reference) => {
        console.log("Booking completed:", reference);
        // Optional: Track analytics, show confirmation, etc.
      }}
    />
  );
}
```

## Testing

### Manual Test with curl

```bash
curl -X POST https://your-n8n-instance.com/webhook/mawidi-demo-booking \
  -H "Content-Type: application/json" \
  -d '{
    "bookingReference": "BK-2024-TEST01",
    "duration": 30,
    "selectedDate": "2024-01-15T00:00:00.000Z",
    "selectedTime": "14:00",
    "timezone": "Asia/Riyadh",
    "userInfo": {
      "name": "Test User",
      "email": "test@example.com",
      "phone": "+966501234567",
      "message": "Test booking"
    },
    "submittedAt": "2024-01-10T10:30:00.000Z"
  }'
```

### Expected Response

```json
{
  "status": "success"
}
```

## Error Handling

The scheduler handles webhook failures gracefully:

1. If webhook returns non-2xx status, user sees an error
2. Booking data is still saved to localStorage
3. User can retry submission
4. Check n8n execution logs for debugging

## Security Considerations

1. **HTTPS Only**: Always use HTTPS for webhook URLs
2. **Authentication**: Add API key or webhook secret in n8n
3. **Rate Limiting**: Configure rate limits in n8n
4. **Input Validation**: The scheduler sanitizes all inputs before sending
5. **CORS**: Configure CORS headers in n8n if needed

## Production Checklist

- [ ] Webhook URL is using HTTPS
- [ ] Environment variable is set correctly
- [ ] n8n workflow is activated
- [ ] Email node is configured with valid credentials
- [ ] Calendar node has proper OAuth permissions
- [ ] Test booking successfully creates all expected records
- [ ] Error handling tested (simulate webhook failures)
- [ ] Monitoring/alerts set up for failed executions

## Support

For n8n-specific issues, refer to:

- [n8n Documentation](https://docs.n8n.io/)
- [n8n Community](https://community.n8n.io/)

For scheduler issues, check the main README.md
