# Vendor Update Implementation Summary

## ✅ What Was Implemented

A flexible vendor profile update endpoint that allows admins to update any combination of vendor fields. Only the fields sent in the request are updated; all other fields remain unchanged.

---

## 📁 Files Created/Modified

### 1. Request Validation
**File:** `app/Http/Requests/Api/Dashboard/Admin/Vendor/UpdateVendorProfileRequest.php`

Validates all possible fields that can be updated:
- ✅ Media files (logo, commercial_register_file)
- ✅ Merchant basic info (commercial_register_number, stock_alert_threshold, expiry_alert_before_days, iban)
- ✅ Delivery settings (delivery_type, delivery_cities)
- ✅ Translations (ar, en)
- ✅ Location data
- ✅ Categories

### 2. Controller Method
**File:** `app/Http/Controllers/Api/Dashboard/Admin/User/VendorController.php`

Added `updateProfile()` method that:
- ✅ Only updates fields that are sent
- ✅ Handles media files via syncMedia()
- ✅ Updates merchant data conditionally
- ✅ Updates translations per language
- ✅ Updates delivery type and cities
- ✅ Updates location with proper field mapping
- ✅ Updates categories with permission check
- ✅ Wraps everything in a database transaction

### 3. Route
**File:** `routes/api/dashboard/admin.php`

```php
Route::patch('vendors/{vendor}/profile', [VendorController::class, 'updateProfile'])
    ->name('vendors.update-profile');
```

### 4. Documentation
- `docs/vendor-profile-update-api.md` - Complete API documentation
- `docs/vendor-profile-update-examples.md` - Detailed examples with delivery settings

---

## 🎯 Supported Fields

### Merchant Basic Info
```json
{
  "commercial_register_number": "1010897654",
  "stock_alert_threshold": 5,
  "expiry_alert_before_days": 30,
  "iban": "SA1234567890123456789012"
}
```

### Media Files
```json
{
  "logo": "d3082cdc-9e8b-49d5-828b-61163d2abe63",
  "commercial_register_file": "142bbd15-6082-41ae-aba3-c9d31424af74"
}
```

### Delivery Settings
```json
{
  "delivery_type": "merchant",
  "delivery_cities": [
    {
      "country_id": 1,
      "city_id": 5,
      "delivery_price": 25.50
    }
  ]
}
```

### Translations
```json
{
  "ar": {
    "name": "متجر السعيد",
    "description": "متجر متخصص في بيع المنتجات الإلكترونية"
  },
  "en": {
    "name": "Saed Store",
    "description": "A store specialized in selling electronics"
  }
}
```

### Location
```json
{
  "location": {
    "city_id": 1,
    "lat": "24.713552",
    "lng": "46.675296",
    "name": "Main Branch",
    "property_number": "Building 25",
    "details": "King Fahd Road, Al Olaya District",
    "url": "https://maps.google.com/?q=24.713552,46.675296"
  }
}
```

### Categories
```json
{
  "category_ids": [1, 10, 15]
}
```

---

## 🔑 Key Features

### 1. Partial Updates
Send only the fields you want to update. All other fields remain unchanged.

**Example:**
```json
{
  "stock_alert_threshold": 10
}
```
Only updates stock_alert_threshold, everything else stays the same.

### 2. Flexible Combinations
Update any combination of fields in a single request.

**Example:**
```json
{
  "logo": "uuid-here",
  "stock_alert_threshold": 5,
  "ar": {"name": "متجر السعيد"},
  "delivery_type": "merchant"
}
```

### 3. Conditional Logic
- **Categories**: Only updates if vendor has `can_change_categories` permission
- **Delivery Cities**: Replaces all existing cities when sent
- **Translations**: Can update one language without affecting the other
- **Location**: Requires `city_id` when sent

### 4. Transaction Safety
All updates are wrapped in a database transaction. If any part fails, all changes are rolled back.

### 5. Media Handling
Uses `syncMedia()` method to properly handle logo and commercial register file uploads.

---

## 📊 Database Tables Affected

| Table | Fields Updated |
|-------|----------------|
| `merchants` | commercial_register_number, stock_alert_threshold, expiry_alert_before_days, iban, delivery_type |
| `merchant_translations` | name, description (per locale) |
| `merchant_cities` | country_id, city_id, delivery_price (replaced) |
| `locations` | city_id, lat, lng, name, property_number, details, url |
| `merchant_categories` | category_id (synced) |
| `user_specialties` | category_id (synced) |
| `media` | logo, commercial_register_file (via MediaTrait) |

---

## 🚀 Usage Examples

### Example 1: Update Only Delivery Settings
```bash
curl -X PATCH \
  https://api.example.com/api/dashboard/admin/vendors/123/profile \
  -H 'Authorization: Bearer TOKEN' \
  -H 'Content-Type: application/json' \
  -d '{
    "delivery_type": "merchant",
    "delivery_cities": [
      {"country_id": 1, "city_id": 5, "delivery_price": 25.50}
    ]
  }'
```

### Example 2: Update Logo and Translations
```bash
curl -X PATCH \
  https://api.example.com/api/dashboard/admin/vendors/123/profile \
  -H 'Authorization: Bearer TOKEN' \
  -H 'Content-Type: application/json' \
  -d '{
    "logo": "d3082cdc-9e8b-49d5-828b-61163d2abe63",
    "ar": {"name": "متجر السعيد"},
    "en": {"name": "Saed Store"}
  }'
```

### Example 3: Update Everything
```bash
curl -X PATCH \
  https://api.example.com/api/dashboard/admin/vendors/123/profile \
  -H 'Authorization: Bearer TOKEN' \
  -H 'Content-Type: application/json' \
  -d '{
    "logo": "uuid",
    "commercial_register_number": "1010897654",
    "stock_alert_threshold": 5,
    "delivery_type": "merchant",
    "delivery_cities": [
      {"country_id": 1, "city_id": 5, "delivery_price": 25.50}
    ],
    "ar": {"name": "متجر السعيد"},
    "en": {"name": "Saed Store"},
    "location": {
      "city_id": 1,
      "lat": "24.713552",
      "lng": "46.675296"
    },
    "category_ids": [1, 10]
  }'
```

---

## ⚠️ Important Notes

### 1. Don't Send Null Values
If you don't want to update a field, **don't send it at all**. Don't send `null` values.

❌ **Wrong:**
```json
{
  "logo": null,
  "location": null
}
```

✅ **Correct:**
```json
{
  "stock_alert_threshold": 5
}
```

### 2. Delivery Cities Are Replaced
When you send `delivery_cities`, **all existing cities are deleted** and replaced with the new ones.

If you want to keep existing cities, include them in the array.

### 3. Location Requires city_id
When sending location data, `city_id` is required. All other location fields are optional.

### 4. Categories Require Permission
Updating categories only works if the vendor has `can_change_categories` set to `true`. Otherwise, you'll get a 403 error.

### 5. Media Files Are UUIDs
The `logo` and `commercial_register_file` fields expect UUIDs from a previous media upload endpoint, not file uploads directly.

---

## 🔍 Response Structure

### Success Response
```json
{
  "status": "success",
  "message": "Vendor profile updated successfully",
  "data": {
    "id": 123,
    "merchant": {
      "id": 45,
      "commercial_register_number": "1010897654",
      "stock_alert_threshold": 5,
      "expiry_alert_before_days": 30,
      "delivery_type": "merchant",
      "translations": {...},
      "categories": [...],
      "delivery_cities": [...]
    },
    "locations": [...],
    "specialties": [...]
  }
}
```

### Error Responses
- **404**: Vendor merchant data not found
- **403**: Vendor cannot change main categories
- **422**: Validation error
- **400**: Update failed (with exception message)

---

## 🧪 Testing Checklist

- [ ] Update only logo
- [ ] Update only translations (ar)
- [ ] Update only translations (en)
- [ ] Update only location
- [ ] Update only categories (with permission)
- [ ] Update only categories (without permission - should fail)
- [ ] Update only delivery_type
- [ ] Update only delivery_cities
- [ ] Update delivery_type + delivery_cities together
- [ ] Update stock_alert_threshold
- [ ] Update everything at once
- [ ] Send invalid data (should return 422)
- [ ] Update non-existent vendor (should return 404)

---

## 📝 Related Endpoints

| Endpoint | Purpose |
|----------|---------|
| `PATCH /vendors/{vendor}/profile` | **NEW** - Flexible profile update |
| `PATCH /vendors/{vendor}/basic-info` | Update user table data only |
| `PATCH /vendors/{vendor}/merchant-data` | Update merchant data only |
| `PUT /vendors/{vendor}` | Original full update endpoint |

---

## 🎉 Summary

You now have a powerful, flexible vendor update endpoint that:
- ✅ Supports partial updates
- ✅ Handles all vendor-related data
- ✅ Includes delivery settings (delivery_type, delivery_cities)
- ✅ Is transaction-safe
- ✅ Has proper validation
- ✅ Is well-documented

**Endpoint:** `PATCH /api/dashboard/admin/vendors/{vendor}/profile`

**Route Name:** `vendors.update-profile`
