# Beyti API - Postman Collection Guide

This guide will help you test the Beyti API using the provided Postman collection.

## Files

- `Beyti-API.postman_collection.json` - Complete API collection with all endpoints
- `Beyti-API.postman_environment.json` - Environment configuration for local development

## Import into Postman

### Option 1: Import Files

1. Open Postman
2. Click "Import" button (top left)
3. Drag and drop both JSON files or click "Upload Files"
4. Select both files:
   - `Beyti-API.postman_collection.json`
   - `Beyti-API.postman_environment.json`
5. Click "Import"

### Option 2: Import from Link (if hosted)

1. Click "Import" > "Link"
2. Paste the URL to the collection file
3. Click "Continue"

## Setup

### 1. Select Environment

1. In the top-right corner of Postman, click the environment dropdown
2. Select "Beyti API - Local"

### 2. Configure Base URL (if different)

If your API is running on a different URL:

1. Click the environment dropdown > "Beyti API - Local" > Edit
2. Update the `baseUrl` value (default: `http://localhost:8080/beyti-api/public`)
3. Save changes

### 3. Get Authentication Token (Development)

**Quick Method - Using Test Authentication:**

1. Go to **🧪 Test Authentication (Dev Only)** folder
2. Click **Generate Test Token**
3. Send the request
4. **Token is automatically saved!** No manual steps needed.
5. Start testing any protected endpoint

The default user is `admin@beyti.test`. Change the email in the request body to test different roles:
- `admin@beyti.test` - Full admin access
- `security@beyti.test` - Can approve/reject visits
- `host@beyti.test` - Basic user access

**Production Method - Azure AD (when configured):**

1. Go to **Authentication** > **Azure AD Login URL**
2. Send the request to get the Azure AD login URL
3. Follow the authentication flow
4. Copy the `access_token` from the response
5. Manually set it in the environment variable

## Collection Structure

The collection is organized into the following groups:

### 1. Health Check
- **Health Check** - Verify API is running

### 2. 🧪 Test Authentication (Dev Only)
**⚠️ REMOVE IN PRODUCTION!**

Quick authentication for development testing:
- **List Test Users** - See all available test users
- **Generate Test Token** - Auto-saves token to {{authToken}}
- **Get My Info** - Verify current authentication
- **Revoke Token** - Logout current session

### 3. Locations
- **Get All Locations** - List all available locations

### 4. Visits
CRUD operations and actions:
- **Get All Visits** - List with filters (status, location, search)
- **Get Visit by ID** - Single visit details
- **Create Visit - Single Day** - Create a one-day visit
- **Create Visit - Multiple Days** - Create a multi-day visit
- **Approve Visit** - Approve (security/admin only)
- **Reject Visit** - Reject with reason (security/admin only)
- **Send Reminder** - Email reminder to visitors

### 5. Dashboard
- **Get Statistics** - Dashboard stats
- **Get Recent Visits** - Latest visits
- **Get Today's Visits** - Visits scheduled for today
- **Update Azure AD Settings** - Azure AD config
- **Update Dauha Settings** - Dauha API config
- **Update SMTP Settings** - Email server config
- **Update Timezone** - System timezone
- **Get Email Templates** - All email templates
- **Update Email Template** - Modify template

## Testing Workflow

### Quick Start Test

1. **Test Health**
   ```
   GET /api/health
   ```
   Should return: `{"status":"ok","timestamp":"..."}`

2. **Get Locations** (requires auth)
   ```
   GET /api/locations
   ```

3. **Create a Visit** (requires auth)
   ```
   POST /api/visits
   ```
   Use the example body provided

4. **Get Visits**
   ```
   GET /api/visits
   ```

### Testing Visitor Registration Flow

1. Create a visit (authenticated) - Note the visit ID
2. Get the registration token for a visitor from the database
3. **Validate Token**
   ```
   GET /api/visitor/registration/{token}/validate
   ```
4. **Get Visit Details**
   ```
   GET /api/visitor/registration/{token}
   ```
5. **Save Draft** (optional)
   ```
   POST /api/visitor/registration/{token}/draft
   ```
6. **Submit Registration**
   ```
   POST /api/visitor/registration/{token}/submit
   ```

### Testing Security Workflows

1. Create a visit (status: pending)
2. **Approve Visit** (as security/admin)
   ```
   POST /api/visits/{id}/approve
   ```
3. **Reject Visit** (alternative)
   ```
   POST /api/visits/{id}/reject
   ```
4. **Mark as Returned**
   ```
   POST /api/visits/{id}/return
   ```

## Common Query Parameters

### Get All Visits
- `page` - Page number (default: 1)
- `per_page` - Items per page (default: 15)
- `status` - Filter by status (pending, approved, rejected, arrived, departed)
- `location_id` - Filter by location
- `search` - Search in visitor names, emails, etc.

Example:
```
GET /api/visits?page=1&per_page=20&status=pending&location_id=1
```

## Rate Limiting

Some endpoints have rate limiting:
- **Visitor Registration (Draft/Submit)**: 3 requests per 10 minutes
- **General API**: 60 requests per minute (per user/IP)

## Response Status Codes

- `200` - Success
- `201` - Created
- `400` - Bad Request / Validation Error
- `401` - Unauthenticated
- `403` - Forbidden (insufficient permissions)
- `404` - Not Found
- `409` - Conflict (e.g., visitor already registered)
- `410` - Gone (token expired)
- `422` - Validation Failed
- `429` - Too Many Requests (rate limited)
- `500` - Internal Server Error

## Tips

1. **Save Responses**: Click "Save Response" to save example responses for later reference
2. **Environment Variables**: Use `{{variable}}` syntax to reference environment variables
3. **Pre-request Scripts**: Add scripts to automatically refresh tokens
4. **Tests**: Add test scripts to validate responses automatically
5. **Collections Runner**: Run entire collection or folder to test multiple endpoints

## Testing with Different Roles

To test role-based access:

1. Authenticate as different users (admin, security_member, host)
2. Update the `authToken` environment variable
3. Test endpoints that require specific roles:
   - Admin only: Settings endpoints
   - Security/Admin: Approve, Reject, Return visits

## Troubleshooting

### "Unauthenticated" Error
- Verify `authToken` is set in environment
- Check if token has expired (get new token)
- Ensure "Bearer " prefix is in Authorization header

### "Rate limiter not defined" Error
- Server configuration issue
- Check `bootstrap/app.php` has rate limiter configured

### "Forbidden" Error
- User doesn't have required role
- Check role requirements in endpoint description

### CORS Errors (from browser)
- CORS is configured in `config/cors.php`
- Postman bypasses CORS (testing should work)

## Example Request Bodies

### Create Visit - Single Day
```json
{
    "hostVisitor": {
        "name": "Ahmed Mohamed",
        "email": "admin@beyti.test",
        "phone": "01021002800",
        "location": "1"
    },
    "mainVisitorEmail": "visitor@example.com",
    "visitReason": "Business meeting for project discussion",
    "meetingType": "single",
    "date": "2026-01-15",
    "startTime": "09:00 AM",
    "endTime": "05:00 PM"
}
```

**Field Requirements:**
- `hostVisitor.email` - Must exist in user_roles table
- `visitReason` - Minimum 10 characters
- `startTime/endTime` - Format: `HH:MM AM/PM` (e.g., "09:00 AM")
- Business hours: 8 AM to 6 PM
- `date` - Must be today or future date (YYYY-MM-DD)

### Create Visit - Multiple Days
```json
{
    "hostVisitor": {
        "name": "Ahmed Mohamed",
        "email": "admin@beyti.test",
        "phone": "01021002800",
        "location": "1"
    },
    "mainVisitorEmail": "visitor@example.com",
    "visitReason": "Workshop and training session over multiple days",
    "meetingType": "multiple",
    "dateFrom": "2026-01-20",
    "dateTo": "2026-01-22",
    "startTime": "08:00 AM",
    "endTime": "06:00 PM"
}
```

**Notes:**
- `startTime` and `endTime` are optional for multiple day visits
- If not provided, defaults are "08:00 AM" and "06:00 PM"
- `dateTo` must be after `dateFrom`

### Reject Visit
```json
{
    "reason": "Security concerns regarding visitor background"
}
```

**Requirements:**
- `reason` - Minimum 10 characters

## Need Help?

- Check endpoint descriptions in Postman
- Review API response error messages
- Consult Laravel logs: `storage/logs/laravel.log`
- Check network tab for detailed request/response
