# 📋 Dynamic Forms - Admin Guide

## Overview
Dynamic forms allow admins to create custom fields for services **without writing code**. This guide shows how to use the user-friendly validation system.

---

## 🎯 How It Works

### Step 1: Get Available Validation Rules

**Endpoint:**
```
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": "max",
      "label": "Maximum Length",
      "requires_value": true,
      "value_type": "number",
      "example": "100"
    },
    {
      "value": "alpha",
      "label": "Letters Only",
      "requires_value": false,
      "value_type": "text",
      "example": ""
    }
  ]
}
```

---

## 📝 Creating Fields with User-Friendly Validations

### Example 1: Text Field with Min/Max Length

**Admin UI shows:**
```
☑ Minimum Length: [3]
☑ Maximum Length: [100]
☐ Letters Only
☐ Letters and Numbers Only
```

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

---

### Example 2: Number Field with Range

**Admin UI shows:**
```
☑ Minimum Value: [1]
☑ Maximum Value: [100]
☐ Integer Only
```

**Sends:**
```json
{
  "field_key": "number_of_rooms",
  "field_type": "number",
  "validation_rules": ["min:1", "max:100"],
  "ar": { "label": "عدد الغرف" },
  "en": { "label": "Number of Rooms" }
}
```

---

### Example 3: Phone with Predefined Pattern

**Admin UI shows:**
```
☑ Saudi Mobile Number (05xxxxxxxx)
☐ Custom Pattern
```

**Sends:**
```json
{
  "field_key": "phone",
  "field_type": "phone",
  "validation_rules": ["regex:/^(05|\\+9665)[0-9]{8}$/"],
  "ar": { "label": "رقم الجوال" },
  "en": { "label": "Mobile Number" }
}
```

---

### Example 4: Date with Range

**Admin UI shows:**
```
☑ After Date: [today]
☑ Before Date: [+30 days]
```

**Sends:**
```json
{
  "field_key": "appointment_date",
  "field_type": "date",
  "validation_rules": ["after:today", "before:+30 days"],
  "ar": { "label": "تاريخ الموعد" },
  "en": { "label": "Appointment Date" }
}
```

---

### Example 5: File Upload with Size and Type

**Admin UI shows:**
```
☑ Maximum File Size: [10240] KB (10 MB)
☑ Allowed File Types: [☑ PDF ☑ DOCX ☑ JPG ☑ PNG]
```

**Sends:**
```json
{
  "field_key": "documents",
  "field_type": "file",
  "is_repeatable": true,
  "meta": {
    "max_size": 10240,
    "allowed_types": ["pdf", "docx", "jpg", "png"]
  },
  "ar": { "label": "المستندات" },
  "en": { "label": "Documents" }
}
```

---

## 🎨 Frontend Implementation Example

### Admin Panel UI Pseudocode

```javascript
// 1. Admin selects field type
const fieldType = 'text';

// 2. Fetch available validations
const validations = await fetch(`/api/dashboard/admin/validation-rules?field_type=${fieldType}`);

// 3. Show checkboxes/inputs based on response
validations.data.forEach(rule => {
  if (rule.requires_value) {
    // Show checkbox + input field
    html += `
      <label>
        <input type="checkbox" value="${rule.value}" />
        ${rule.label}
        <input type="${rule.value_type}" placeholder="${rule.example}" />
      </label>
    `;
  } else {
    // Show checkbox only
    html += `
      <label>
        <input type="checkbox" value="${rule.value}" />
        ${rule.label}
      </label>
    `;
  }
});

// 4. When admin submits, build validation_rules array
const selectedRules = [];
document.querySelectorAll('input[type="checkbox"]:checked').forEach(checkbox => {
  const value = checkbox.nextElementSibling?.value; // get input value if exists
  if (value) {
    selectedRules.push(`${checkbox.value}:${value}`);
  } else {
    selectedRules.push(checkbox.value);
  }
});

// 5. Send to API
const fieldData = {
  field_key: 'client_name',
  field_type: 'text',
  validation_rules: selectedRules, // e.g., ["min:3", "max:100"]
  ar: { label: '...', placeholder: '...' },
  en: { label: '...', placeholder: '...' }
};
```

---

## 📚 Available Validations by Field Type

### TEXT
- Minimum Length
- Maximum Length
- Exact Length
- Letters Only
- Letters and Numbers Only
- Letters, Numbers, Dashes, Underscores
- Starts With
- Ends With
- Custom Pattern (Regex)

### TEXTAREA
- Minimum Length
- Maximum Length

### NUMBER
- Minimum Value
- Maximum Value
- Between (range)
- Integer Only
- Exact Digits
- Digits Between

### EMAIL
- Email (Basic)
- Email (DNS Check)

### PHONE
- Saudi Mobile Number (predefined)
- Custom Pattern

### DATE
- After Date
- After or Equal Date
- Before Date
- Before or Equal Date
- Date Format

### FILE
- Allowed File Types
- Maximum File Size (KB)
- Image Dimensions

---

## 🚀 Quick Start Checklist

1. ✅ Admin selects field type (text, number, etc.)
2. ✅ System fetches available validations for that type
3. ✅ Admin checks which validations to apply
4. ✅ Admin enters values where needed (e.g., min: 3, max: 100)
5. ✅ Admin enters AR and EN translations
6. ✅ System builds `validation_rules` array automatically
7. ✅ Send to API endpoint

---

## 💡 Benefits

✅ **No Code Required**: Admins use checkboxes and inputs  
✅ **Type Safe**: Only relevant validations shown per field type  
✅ **Predefined Patterns**: Common patterns like Saudi mobile ready to use  
✅ **Error Prevention**: Can't enter invalid validation rules  
✅ **Multi-language**: Labels automatically translated  
✅ **Consistent**: Same validation logic across all services  

---

## 🔧 Advanced: Custom Patterns

For advanced admins who need custom regex:

**UI shows:**
```
☑ Custom Pattern
   Pattern: [/^[A-Z]{3}[0-9]{6}$/]
   Example: ABC123456
   Error Message (AR): [يجب أن يكون الرمز بالصيغة ABC123456]
   Error Message (EN): [Code must be in format ABC123456]
```

**Sends:**
```json
{
  "validation_rules": ["regex:/^[A-Z]{3}[0-9]{6}$/"]
}
```

---

## 📞 Support

For questions about validation rules or field types, contact the development team.
