# 🎯 Admin-Friendly Validation System

## Problem Solved
❌ **Before**: Admins had to write `["min:3", "max:100", "regex:/^[A-Z]+$/"]`  
✅ **After**: Admins use checkboxes and simple inputs

---

## 📡 Available API Endpoints

### 1. Get Field Types
```
GET /api/dashboard/admin/field-types
```

**Response:**
```json
{
  "status": "success",
  "data": [
    {
      "value": "text",
      "label": "Text Input",
      "supports_options": false,
      "supports_repeatable": true,
      "icon": "text_fields",
      "description": "Short text input field (e.g., name, address)"
    },
    {
      "value": "select",
      "label": "Dropdown Select",
      "supports_options": true,
      "supports_repeatable": true,
      "icon": "arrow_drop_down_circle",
      "description": "Dropdown list to select from multiple options"
    }
  ]
}
```

---

### 2. Get Available Validations for Field Type
```
GET /api/dashboard/admin/validation-rules?field_type=text
```

**Response:**
```json
{
  "status": "success",
  "data": [
    {
      "value": "min",
      "label": "Minimum Length",
      "requires_value": true,
      "value_type": "number",
      "example": "3"
    },
    {
      "value": "alpha",
      "label": "Letters Only",
      "requires_value": false,
      "value_type": "text",
      "example": ""
    }
  ]
}
```

---

## 🎨 Admin UI Flow

### Step 1: Choose Field Type
```
Admin sees:
┌─────────────────────────────────────┐
│ Select Field Type:                  │
│ ○ Text Input                        │
│ ○ Text Area                         │
│ ○ Dropdown Select                   │
│ ○ Number                            │
│ ○ Date Picker                       │
│ ○ File Upload                       │
│ ○ Email                             │
│ ○ Phone                             │
└─────────────────────────────────────┘
```

### Step 2: Configure Validations (Based on Selected Type)

**Example: Admin selects "Text"**
```
┌─────────────────────────────────────┐
│ Validations:                        │
│                                     │
│ ☑ Minimum Length: [3]              │
│ ☑ Maximum Length: [100]            │
│ ☐ Letters Only                     │
│ ☐ Letters and Numbers Only         │
│ ☐ Custom Pattern                   │
└─────────────────────────────────────┘
```

**Example: Admin selects "Number"**
```
┌─────────────────────────────────────┐
│ Validations:                        │
│                                     │
│ ☑ Minimum Value: [1]               │
│ ☑ Maximum Value: [100]             │
│ ☐ Integer Only                     │
│ ☐ Exact Digits: [10]               │
└─────────────────────────────────────┘
```

**Example: Admin selects "File"**
```
┌─────────────────────────────────────┐
│ File Settings:                      │
│                                     │
│ ☑ Maximum Size: [10240] KB         │
│                                     │
│ ☑ Allowed Types:                   │
│   ☑ PDF                            │
│   ☑ DOCX                           │
│   ☑ JPG                            │
│   ☑ PNG                            │
└─────────────────────────────────────┘
```

### Step 3: Translations
```
┌─────────────────────────────────────┐
│ Arabic:                             │
│ Label: [اسم العميل]                │
│ Placeholder: [أدخل اسمك]           │
│ Help Text: [الاسم الكامل للعميل]   │
│                                     │
│ English:                            │
│ Label: [Client Name]               │
│ Placeholder: [Enter your name]     │
│ Help Text: [Full name of client]   │
└─────────────────────────────────────┘
```

### Step 4: Additional Options
```
┌─────────────────────────────────────┐
│ ☑ Required Field                   │
│ ☑ Active                           │
│ ☑ Allow Multiple Values            │
│                                     │
│ Order: [1]                         │
└─────────────────────────────────────┘
```

---

## 💻 Frontend Code Example

```javascript
// 1. Get field types on page load
const fieldTypes = await api.get('/admin/field-types');

// 2. When admin selects a field type
async function onFieldTypeChange(selectedType) {
  // Get available validations for this type
  const validations = await api.get(`/admin/validation-rules?field_type=${selectedType}`);
  
  // Render validation checkboxes
  renderValidationOptions(validations.data);
}

// 3. Render validation UI
function renderValidationOptions(validations) {
  return validations.map(rule => {
    if (rule.requires_value) {
      return `
        <label>
          <input type="checkbox" name="validation_${rule.value}" />
          ${rule.label}
          <input 
            type="${rule.value_type}" 
            name="validation_${rule.value}_value"
            placeholder="${rule.example}"
          />
        </label>
      `;
    } else {
      return `
        <label>
          <input type="checkbox" name="validation_${rule.value}" />
          ${rule.label}
        </label>
      `;
    }
  });
}

// 4. Build validation_rules array on submit
function buildValidationRules() {
  const rules = [];
  
  document.querySelectorAll('input[name^="validation_"]:checked').forEach(checkbox => {
    const ruleName = checkbox.name.replace('validation_', '');
    const valueInput = document.querySelector(`input[name="validation_${ruleName}_value"]`);
    
    if (valueInput && valueInput.value) {
      rules.push(`${ruleName}:${valueInput.value}`);
    } else {
      rules.push(ruleName);
    }
  });
  
  return rules;
}

// 5. Submit form
async function submitField() {
  const fieldData = {
    field_key: document.querySelector('#field_key').value,
    field_type: document.querySelector('#field_type').value,
    is_required: document.querySelector('#is_required').checked,
    is_repeatable: document.querySelector('#is_repeatable').checked,
    validation_rules: buildValidationRules(),
    ar: {
      label: document.querySelector('#ar_label').value,
      placeholder: document.querySelector('#ar_placeholder').value,
      help_text: document.querySelector('#ar_help_text').value
    },
    en: {
      label: document.querySelector('#en_label').value,
      placeholder: document.querySelector('#en_placeholder').value,
      help_text: document.querySelector('#en_help_text').value
    }
  };
  
  // For file fields, add meta
  if (fieldData.field_type === 'file') {
    fieldData.meta = {
      max_size: document.querySelector('#max_file_size').value,
      allowed_types: getSelectedFileTypes()
    };
  }
  
  await api.post(`/admin/services/${serviceId}/form-fields`, fieldData);
}
```

---

## 🔑 Key Benefits

### For Admins:
✅ **No Technical Knowledge Required**: Use checkboxes and inputs  
✅ **Context-Aware**: Only see relevant validations for selected field type  
✅ **Pre-defined Patterns**: Common patterns ready (Saudi mobile, etc.)  
✅ **Real-time Validation**: Can't submit invalid configuration  
✅ **Multi-language UI**: Labels in Arabic/English  

### For Developers:
✅ **Type-Safe**: Validation rules properly formatted  
✅ **Extensible**: Easy to add new validation types  
✅ **Consistent**: Same validation logic everywhere  
✅ **Maintainable**: One source of truth for validation rules  

---

## 📋 Complete Example: Creating a "Client Name" Field

**Admin does:**
1. Select "Text" field type
2. Check "Minimum Length" → Enter 3
3. Check "Maximum Length" → Enter 100
4. Enter Arabic label: "اسم العميل"
5. Enter English label: "Client Name"
6. Check "Required"
7. Click "Save"

**System sends:**
```json
{
  "field_key": "client_name",
  "field_type": "text",
  "is_required": true,
  "validation_rules": ["min:3", "max:100"],
  "ar": {
    "label": "اسم العميل",
    "placeholder": "أدخل اسمك",
    "help_text": "الاسم الكامل"
  },
  "en": {
    "label": "Client Name",
    "placeholder": "Enter your name",
    "help_text": "Full name"
  }
}
```

**Client sees form:**
```
اسم العميل *
┌─────────────────────────────┐
│ أدخل اسمك                   │
└─────────────────────────────┘
الاسم الكامل
```

**Validation happens automatically:**
- Must not be empty (required)
- Must be at least 3 characters
- Must not exceed 100 characters

---

## 🚀 Next Steps

1. Implement the frontend UI using the `/field-types` endpoint
2. Show relevant validations based on selected field type using `/validation-rules`
3. Build the `validation_rules` array from user selections
4. Handle `meta` object for file fields
5. Support `options` object for select/radio/checkbox fields

Done! ✨
