# Media Upload Guide for Profile Update Requests

## Understanding the Media System

Your application uses a custom Media module that handles file uploads with a polymorphic relationship pattern. Here's how it works:

### Media System Architecture

1. **Media Model** (`modules/Media/Models/Media.php`)
   - Stores file metadata (name, path, size, type, etc.)
   - Uses polymorphic relationship (`model_type`, `model_id`)
   - Each media record can be attached to any model

2. **MediaTrait** (`modules/Media/Traits/MediaTrait.php`)
   - Used by models that need media attachments (like `Profile`)
   - Provides magic getter for media columns
   - Returns media data with full URL path

3. **UploadMediaObserver** (`modules/Media/Observers/UploadMediaObserver.php`)
   - Automatically attaches media when model is saved
   - Handles single and multiple media attachments
   - Deletes old media when updating single media fields

## How to Upload Media Files

### Step 1: Upload File to Get Media ID

**Endpoint:** `POST /api/media` (or your media upload endpoint)

**Request (multipart/form-data):**
```
file: [binary file]
model: Profile
media_type: image  (for logo) or file (for commercial_register_file)
width: 800 (optional, for images)
height: 800 (optional, for images)
quality: 85 (optional, for images)
```

**Example using cURL:**
```bash
curl -X POST https://your-domain.com/api/media \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -F "file=@/path/to/logo.jpg" \
  -F "model=Profile" \
  -F "media_type=image" \
  -F "width=800" \
  -F "height=800" \
  -F "quality=85"
```

**Response:**
```json
{
  "status": true,
  "message": "File uploaded successfully",
  "data": {
    "id": "9d4f8a2b-1c3e-4d5f-8a9b-1c2d3e4f5a6b",
    "type": "image"
  }
}
```

### Step 2: Use Media ID in Profile Update Request

Now use the returned media `id` in your profile update request:

```json
{
  "logo": "9d4f8a2b-1c3e-4d5f-8a9b-1c2d3e4f5a6b",
  "commercial_register_file": "9d4f8a2b-1c3e-4d5f-8a9b-1c2d3e4f5a6b",
  "commercial_register_number": "CR-2024-123456",
  "ar": {
    "name": "متجر الإلكترونيات",
    "description": "وصف المتجر"
  },
  "en": {
    "name": "Electronics Store",
    "description": "Store description"
  }
}
```

## Complete Workflow Example

### Example 1: Upload Logo and Create Profile Update Request

**Step 1: Upload Logo**
```bash
POST /api/media
Content-Type: multipart/form-data

file: logo.jpg
model: Profile
media_type: image
width: 800
height: 800
```

**Response:**
```json
{
  "status": true,
  "data": {
    "id": "abc123-logo-id"
  }
}
```

**Step 2: Upload Commercial Register File**
```bash
POST /api/media
Content-Type: multipart/form-data

file: commercial_register.pdf
model: Profile
media_type: pdf
generate_thumbnail: true
```

**Response:**
```json
{
  "status": true,
  "data": {
    "id": "def456-file-id"
  }
}
```

**Step 3: Create Profile Update Request**
```bash
POST /api/dashboard/vendor/profile-update-requests
Content-Type: application/json

{
  "logo": "abc123-logo-id",
  "commercial_register_file": "def456-file-id",
  "commercial_register_number": "CR-2024-123456",
  "ar": {
    "name": "متجر الإلكترونيات الحديثة",
    "description": "نحن متجر متخصص في بيع الأجهزة الإلكترونية"
  },
  "en": {
    "name": "Modern Electronics Store",
    "description": "We are a store specialized in selling electronic devices"
  },
  "location": {
    "country_id": 1,
    "city_id": 5,
    "lat": 24.7136,
    "lng": 46.6753,
    "name": "Main Branch",
    "property_number": "1234",
    "details": "Building 15, Floor 2",
    "url": "https://maps.google.com/?q=24.7136,46.6753"
  }
}
```

## Media Types Supported

| Media Type | Use Case | Validation |
|------------|----------|------------|
| `image` | Logo, profile pictures | JPG, PNG, GIF, SVG, WebP |
| `pdf` | Commercial register, documents | PDF files |
| `file` | General files | Any file type |
| `video` | Video content | MP4, AVI, MOV, etc. |
| `audio` | Audio files | MP3, WAV, etc. |

## How Media Attachment Works

When admin approves the profile update request:

1. **Old Media Deletion:**
   ```php
   $profile->media()->where('option', 'logo')->delete();
   ```

2. **New Media Attachment:**
   ```php
   $logoMedia = Media::find($mediaId);
   $logoMedia->update([
       'model_id'    => $profile->id,
       'model_type'  => 'App\Models\Profile',
       'is_attached' => true,
       'option'      => 'logo',
       'uploaded_by' => auth('api')->id(),
   ]);
   ```

3. **Accessing Media in Profile:**
   ```php
   $profile->logo; // Returns array with id, path, type, option
   // Output: ['id' => 'abc123', 'path' => 'https://domain.com/storage/images/logo.jpg', ...]
   ```

## Profile Model Media Configuration

The `Profile` model defines media columns:

```php
protected array $mediaColumns = [
    'logo' => [
        'is_single'  => true,      // Only one logo allowed
        'type'       => 'image',
        'option'     => 'logo',
        'default'    => null,
    ],
    'commercial_register_file' => [
        'is_single'  => true,      // Only one file allowed
        'type'       => 'file',
        'option'     => 'commercial_register_file',
        'default'    => null,
    ],
];
```

## Important Notes

1. **Media IDs are UUIDs** - Not integers, they are string UUIDs
2. **Upload First, Then Reference** - Always upload media files first to get IDs
3. **Validation** - The request validates that media IDs exist in the `media` table
4. **Automatic Cleanup** - Old media is automatically deleted when new media is attached
5. **Polymorphic Relationship** - Same media table serves all models

## Validation Rules

In `ProfileUpdateRequestRequest.php`:

```php
'logo' => ['nullable', 'exists:media,id'],
'commercial_register_file' => ['nullable', 'exists:media,id'],
```

This ensures:
- Media ID must exist in the `media` table
- Media ID must be a valid UUID string
- Field is optional (nullable)

## Testing with Postman

### Collection Setup

1. **Upload Logo:**
   - Method: POST
   - URL: `{{base_url}}/api/media`
   - Body: form-data
     - `file`: [Select File]
     - `model`: Profile
     - `media_type`: image

2. **Create Request:**
   - Method: POST
   - URL: `{{base_url}}/api/dashboard/vendor/profile-update-requests`
   - Body: raw JSON
   - Use the media ID from step 1

## Common Issues & Solutions

### Issue 1: "The selected logo is invalid"
**Cause:** Media ID doesn't exist or is incorrect
**Solution:** Verify the media was uploaded successfully and use the correct ID

### Issue 2: Media not showing after approval
**Cause:** Media attachment failed
**Solution:** Check that media ID exists and is not already attached to another model

### Issue 3: Old media not deleted
**Cause:** Observer not triggered or option mismatch
**Solution:** Ensure the `option` field matches the media column key exactly

## API Response Examples

### Get Profile with Media
```json
{
  "id": 1,
  "name": "Electronics Store",
  "logo": {
    "id": "abc123-logo-id",
    "path": "https://domain.com/storage/images/logo_abc123.jpg",
    "type": "image",
    "option": "logo"
  },
  "commercial_register_file": {
    "id": "def456-file-id",
    "path": "https://domain.com/storage/files/register_def456.pdf",
    "type": "pdf",
    "option": "commercial_register_file"
  }
}
```

### Profile Update Request Details
```json
{
  "id": 1,
  "profile_data": {
    "logo": "abc123-logo-id",
    "commercial_register_file": "def456-file-id",
    "commercial_register_number": "CR-2024-123456",
    "translations": {
      "ar": {
        "name": "متجر الإلكترونيات",
        "description": "وصف المتجر"
      },
      "en": {
        "name": "Electronics Store",
        "description": "Store description"
      }
    }
  },
  "status": "pending"
}
```
