# Provider API — Latest Updates

## Overview

This document covers the latest updates to the Provider API including order reporting, profile response improvements, and app settings integration.

---

## Table of Contents

1. [Order Reporting System](#order-reporting-system)
2. [Provider Profile Updates](#provider-profile-updates)
3. [App Settings in Profile Response](#app-settings-in-profile-response)

---

## 1. Order Reporting System

### Overview

Providers can now report **Service Orders** and **Urgent Orders** to flag issues, violations, or problems during order execution.

### Endpoints

#### Report Service Order

```http
POST /api/provider/service-orders/{id}/report
Authorization: Bearer {provider_token}
Content-Type: application/json

{
    "title": "Client Requested Illegal Service",
    "message": "The client asked me to perform services outside the agreed scope...",
    "complaint_type": "inappropriate_behavior"
}
```

#### Report Urgent Order

```http
POST /api/provider/urgent-orders/{urgentOrder}/report
Authorization: Bearer {provider_token}
Content-Type: application/json

{
    "title": "Incorrect Emergency Authority Information",
    "message": "The provided documents do not match the authority details...",
    "complaint_type": "incorrect_information"
}
```

### When Can Providers Report?

**✅ Reporting is ALLOWED:**
- Provider has **accepted** the order
- Order status is **active** / **in_progress** / **started**
- Order is **NOT completed**
- Order is **NOT cancelled**

**❌ Reporting is NOT ALLOWED:**
- Order is **pending** (not accepted yet)
- Order is **completed**
- Order is **cancelled**
- Provider already submitted a report for this order

### Request Fields

| Field | Type | Required | Max Length | Description |
|-------|------|----------|------------|-------------|
| `title` | `string` | ✅ Yes | 255 | Report title/subject |
| `message` | `string` | ✅ Yes | 2000 | Detailed explanation |
| `complaint_type` | `enum` | ✅ Yes | - | Type of complaint |

### Complaint Types

| Value | Description |
|-------|-------------|
| `inappropriate_behavior` | Inappropriate or unprofessional behavior |
| `payment_issue` | Payment-related problems |
| `service_quality` | Quality of service concerns |
| `incorrect_information` | Misleading or false information |
| `scope_violation` | Work outside agreed scope |
| `safety_concern` | Safety or security issues |
| `other` | Other issues |

### Response Examples

**Success:**
```json
{
    "status": "success",
    "message": "Your report has been submitted successfully. Our team will review it.",
    "data": null
}
```
**Status Code:** `201 Created`

**Error - Already Reported:**
```json
{
    "status": "error",
    "message": "You have already submitted a report for this order.",
    "data": null
}
```
**Status Code:** `422 Unprocessable Entity`

**Error - Order Not Found:**
```json
{
    "status": "error",
    "message": "Order not found",
    "data": null
}
```
**Status Code:** `404 Not Found`

**Error - Team Order (Not Leader):**
```json
{
    "status": "error",
    "message": "Only the team leader can report this order.",
    "data": null
}
```
**Status Code:** `422 Unprocessable Entity`

### Business Rules

1. **One Report Per Order:** Providers can only submit ONE report per order
2. **Team Orders:** Only the team leader can submit reports for team orders
3. **Provider Assignment:** Provider must be assigned to the order
4. **Status Validation:** Reports only allowed when order is active (between accepted and before completed/cancelled)

### Frontend Implementation Notes

**Check if reporting is available:**
```javascript
const canReport = (order.status === 'accepted' || 
                   order.status === 'in_progress' ||
                   order.status === 'started') &&
                  !order.has_reported;

const isFinished = order.status === 'completed' || 
                   order.status === 'cancelled';

// Show report button only if allowed
if (canReport && !isFinished) {
    // Show "Report Order" button
}
```

---

## 2. Provider Profile Updates

### is_available Field Fix

The `is_available` field now returns as **proper boolean** instead of `1`/`0`.

**Before:**
```json
{
    "is_available": 1
}
```

**After:**
```json
{
    "is_available": true
}
```

### Impact

- All provider profile responses now return `is_available` as `true` or `false`
- No more integer values (`1` or `0`)
- Frontend should handle boolean values directly

---

## 3. App Settings in Profile Response

### Overview

Provider profile responses now include **app settings** with contact information and social media links. These settings are configured by admins and are the same across all users.

### Profile Response Structure

```http
GET /api/provider/profile
Authorization: Bearer {provider_token}
```

**Response:**
```json
{
    "id": 123,
    "full_name": "Ahmed Mohamed",
    "email": "ahmed@example.com",
    "phone": "+966500000000",
    "is_available": true,
    "national_id_type": "national_id",
    
    "provider_data": {
        // ... provider specific fields
    },
    
    "app_settings": {
        "contact": {
            "phone": "+966500000000",
            "whatsapp": "+966501234567"
        },
        "social_links": {
            "facebook": "https://facebook.com/company",
            "twitter": "https://twitter.com/company",
            "instagram": "https://instagram.com/company",
            "snapchat": null,
            "tiktok": null,
            "linkedin": "https://linkedin.com/company/company-name",
            "youtube": "https://youtube.com/@company"
        }
    }
}
```

### App Settings Structure

#### Contact Object

| Field | Type | Nullable | Description |
|-------|------|----------|-------------|
| `phone` | `string` | ✅ Yes | Main company phone number |
| `whatsapp` | `string` | ✅ Yes | WhatsApp contact number |

#### Social Links Object

| Field | Type | Nullable | Description |
|-------|------|----------|-------------|
| `facebook` | `string` | ✅ Yes | Facebook page URL |
| `twitter` | `string` | ✅ Yes | Twitter/X profile URL |
| `instagram` | `string` | ✅ Yes | Instagram profile URL |
| `snapchat` | `string` | ✅ Yes | Snapchat profile URL |
| `tiktok` | `string` | ✅ Yes | TikTok profile URL |
| `linkedin` | `string` | ✅ Yes | LinkedIn page URL |
| `youtube` | `string` | ✅ Yes | YouTube channel URL |

### Important Notes

⚠️ **All fields in app_settings are NULLABLE**

- Values can be `null` if not configured by admin
- Frontend **must check for null** before displaying
- Do not show fields with `null` values in the UI

### Example with Null Values

```json
{
    "app_settings": {
        "contact": {
            "phone": "+966500000000",
            "whatsapp": null
        },
        "social_links": {
            "facebook": "https://facebook.com/company",
            "twitter": null,
            "instagram": "https://instagram.com/company",
            "snapchat": null,
            "tiktok": null,
            "linkedin": null,
            "youtube": null
        }
    }
}
```

### Where App Settings Appear

The `app_settings` object is included in:

- ✅ Provider profile (`GET /api/provider/profile`)
- ✅ Provider login response (`POST /api/provider/auth/login`)
- ✅ Provider registration completion
- ✅ Client profile (same structure)
- ✅ Client login response

### Frontend Implementation Guide

#### Check for Null Values

```javascript
// ❌ WRONG - Will show "null" text or cause errors
<Text>{profile.app_settings.social_links.facebook}</Text>

// ✅ CORRECT - Check for null first
{profile.app_settings?.social_links?.facebook && (
    <Link href={profile.app_settings.social_links.facebook}>
        Facebook
    </Link>
)}
```

#### Filter Out Null Social Links

```javascript
// Get only configured social links
const activeSocialLinks = Object.entries(profile.app_settings.social_links)
    .filter(([platform, url]) => url !== null)
    .map(([platform, url]) => ({ platform, url }));

// Display only active links
{activeSocialLinks.map(({ platform, url }) => (
    <SocialLink key={platform} platform={platform} url={url} />
))}
```

#### Display Contact Information

```javascript
// Phone
{profile.app_settings?.contact?.phone && (
    <TouchableOpacity onPress={() => Linking.openURL(`tel:${profile.app_settings.contact.phone}`)}>
        <Text>Call: {profile.app_settings.contact.phone}</Text>
    </TouchableOpacity>
)}

// WhatsApp
{profile.app_settings?.contact?.whatsapp && (
    <TouchableOpacity onPress={() => {
        const whatsappNumber = profile.app_settings.contact.whatsapp.replace(/\+/g, '');
        Linking.openURL(`https://wa.me/${whatsappNumber}`);
    }}>
        <Text>WhatsApp: {profile.app_settings.contact.whatsapp}</Text>
    </TouchableOpacity>
)}
```

#### Show Contact Section Conditionally

```javascript
const hasContactInfo = profile.app_settings?.contact?.phone || 
                       profile.app_settings?.contact?.whatsapp;

{hasContactInfo && (
    <View style={styles.contactSection}>
        <Text style={styles.sectionTitle}>Contact Us</Text>
        {/* Contact fields */}
    </View>
)}
```

#### Show Social Media Section Conditionally

```javascript
const hasSocialLinks = Object.values(profile.app_settings?.social_links || {})
    .some(value => value !== null);

{hasSocialLinks && (
    <View style={styles.socialSection}>
        <Text style={styles.sectionTitle}>Follow Us</Text>
        {/* Social media links */}
    </View>
)}
```

---

## Summary

### ✅ What's New

1. **Order Reporting:**
   - Providers can report service orders and urgent orders
   - Allowed only when order is active (accepted but not completed/cancelled)
   - One report per order
   - Team orders: only team leader can report

2. **Profile Improvements:**
   - `is_available` now returns boolean (`true`/`false`) instead of `1`/`0`

3. **App Settings:**
   - Contact information (phone, whatsapp) in profile response
   - Social media links (7 platforms) in profile response
   - All settings are nullable - frontend must check before displaying

### ⚠️ Important for Frontend

- Always check for `null` values in `app_settings`
- Filter out `null` social links before displaying
- Handle boolean `is_available` field properly
- Validate order status before showing "Report" button
- Prevent duplicate report submissions

---

## Related Documentation

- [PROVIDER_SERVICE_ORDER_FLOW.md](./PROVIDER_SERVICE_ORDER_FLOW.md) - Service order lifecycle
- [PROVIDER_URGENT_ORDER_FLOW.md](./PROVIDER_URGENT_ORDER_FLOW.md) - Urgent order flow
- [SETTINGS_SYSTEM.md](./SETTINGS_SYSTEM.md) - Complete settings documentation
