# Public Lead Form Documentation

## Overview

The Public Lead Form is a customer-facing web form designed to collect security guard service requirements from prospective clients. The form is accessible to the public without authentication and integrates seamlessly with the internal Lead Management system.

**Form URL**: `/lead-form`

---

## Form Structure & Sections

### 1. Client & Site Details

Captures essential information about the client and their service location.

**Fields**:
| Field | Type | Required | Notes |
|-------|------|----------|-------|
| Company / Client Name | Text | Yes | Max 255 chars |
| Contact Person | Text | Yes | Max 255 chars |
| Mobile Number | Tel | Yes | Format: +country-number |
| Email Address | Email | Yes | Unique, will receive updates |
| Country | Select | Yes | India or Malaysia |
| City / State | Text | Yes | Service location city |
| Postal Code | Text | Yes | ZIP/PIN code |
| Address | Textarea | Yes | Complete address (2 rows) |
| Service Location Details | Textarea | No | Describe the exact site |
| Site Type | Radio | Yes | Options: Office, Factory, Residential, Event, Retail, Hospital, Educational, Other |

**Validation**:
- Email must be unique in system
- All required fields enforced
- Character limits applied
- Country restriction to India/Malaysia

---

### 2. Service Type Selection

Multi-select section allowing clients to choose required security services.

**Options**:
- ✓ Static Guard
- ✓ Armed Guard
- ✓ Escort Service (Pistol)

**Features**:
- Multiple selections allowed (minimum 1)
- Selection triggers dynamic questions section
- Affects available inventory items

**Validation**:
- At least one service type must be selected

---

### 3. Working Hours

Specifies the shift duration required.

**Options**:
- ⊙ 8 Hours
- ⊙ 12 Hours
- ⊙ 24 Hours (Custom)

**Features**:
- Radio button (single select)
- Selecting "24 Hours" reveals additional custom hours input
- Custom hours example: "Monday-Friday 9AM-5PM, Saturday 10AM-2PM"

**Validation**:
- One option required
- Custom hours field optional

---

### 4. Overtime (OT) Requirement

Specifies maximum expected overtime hours.

**Options**:
- ⊙ 1 Hour
- ⊙ 2 Hours
- ⊙ 3 Hours
- ⊙ 4 Hours

**Features**:
- Optional selection
- For planning maximum OT exposure

---

### 5. Allowances (Multi-Select)

Specifies which allowances should be included in service quotation.

**Options**:
- ☑ Transport Allowance
- ☑ Performance Bonus
- ☑ Attendance Allowance
- ☑ Supervisor Allowance
- ☑ Assistant Supervisor Allowance

**Features**:
- Multiple selections allowed
- Optional section (can skip all)
- Affects cost estimation

---

### 6. Dynamic Questionnaire

Conditional questions that appear based on service type selection.

**Auto-Generated Questions**:

**For Static Guard**:
- Supervisor required? (Yes/No)
- Night duty required? (Yes/No)

**For Armed Guard**:
- Armed Supervisor required? (Yes/No)
- Assistant Supervisor required? (Yes/No)
- Night duty required? (Yes/No)

**For Escort Service**:
- Escort frequency? (Daily/Weekly/As needed)
- Armed escorts required? (Yes/No)

**Features**:
- Questions appear/disappear based on service selection
- Section hidden if no services selected
- Multiple choice radio buttons

---

### 7. Inventory Requirements

Specifies quantities of equipment/uniforms needed (requirement collection only - no stock/cost).

**Items Available**:

**Uniforms & Clothing**:
- Uniform Sets (qty)
- Jacket (qty)
- Blazer (qty)
- Safety Shoes (qty)
- Normal Shoes (qty)
- Accessories (qty)

**Equipment**:
- Baton (qty)
- Torch Light (qty)
- Walkie-Talkie (qty)
- Body Camera (qty)

**Infrastructure**:
- Guard Cabin (qty)
- Visitor Register (qty)

**Features**:
- Number input fields (min: 0)
- Section appears only when service type selected
- 2-column grid layout
- No pricing shown
- No stock checking

---

### 8. Compliance Requirements

Specifies compliance certifications needed.

**Options**:
- ☑ SMETA Certification Required
- ☑ RBA Compliance Required
- ☑ Local Labour Law Compliance

**Special Features**:
- **RBA Auto-Enable for Malaysia**: If country selected is "Malaysia", RBA checkbox is automatically checked and disabled
- Info message: "RBA compliance is mandatory for Malaysia"

**Validation**:
- Optional (can submit without compliance selections)
- RBA auto-enabled for Malaysia

---

### 9. Additional Information

Captures notes, expectations, and follow-up details.

**Fields**:
| Field | Type | Required | Notes |
|-------|------|----------|-------|
| Sales Notes | Textarea | No | Internal notes (3 rows) |
| Client Expectations | Textarea | No | What client expects (3 rows) |
| Follow-up Date | Date | No | When to follow up |
| Budget Range - Minimum | Number | No | Min budget in currency |
| Budget Range - Maximum | Number | No | Max budget in currency |

---

## Form Submission

### Submission Options

The form has two submission actions:

#### 1. Save as Draft
- **Button**: "Save as Draft"
- **Status**: `draft`
- **Purpose**: Save incomplete form for later completion
- **Message**: "Your form has been saved as draft. You can continue filling it later using your email."

#### 2. Submit Lead
- **Button**: "Submit Lead"
- **Status**: `submitted`
- **Purpose**: Submit complete lead for sales processing
- **Message**: "Thank you! Your lead has been submitted successfully. Our team will contact you shortly."

### Form Submission Process

```
User fills form
       ↓
Clicks "Submit Lead" or "Save as Draft"
       ↓
Client-side validation (HTML5)
       ↓
Form sent to LeadController@store
       ↓
Server-side validation
       ↓
If valid:
  - Lead created with status = draft|submitted
  - Service types, allowances, inventory stored in sales_notes as JSON
  - Redirect to home with success message
       ↓
If invalid:
  - Return to form with error messages
  - Pre-fill with old() helper
```

### Data Storage

**Database Table**: `leads`

**Fields Populated**:
| DB Field | Source | Notes |
|----------|--------|-------|
| company_name | Form input | Direct |
| contact_person_name | Form input | Direct |
| email | Form input | Direct, Unique |
| mobile_number | Form input | Direct |
| address | Form input | Direct |
| city | Form input (city/state combined) | Direct |
| state | Hidden field | Set to "N/A" |
| postal_code | Form input | Direct |
| country | Form input | Direct (India/Malaysia) |
| service_location | Form textarea | Direct |
| site_type | Form radio | Direct |
| service_type_id | Default | Set to 1 (Security) |
| lead_status | Action button | "draft" or "submitted" |
| guard_type | Default | Set to "both" |
| tentative_guards_count | Default | Set to 1 |
| lead_source | Default | Set to "website" |
| working_hours_type | Form radio | 8, 12, or 24 |
| compliance_required | Form checkbox or default | "yes", "no" or auto |
| rba_applicable | Country-dependent | Auto-true for Malaysia |
| sales_notes | Form textarea + JSON | Manual notes + structured data |
| client_expectations | Form textarea | Direct (stored in sales_notes) |
| follow_up_date | Form date | Direct |
| budget_range_min | Form number | Direct (0 if empty) |
| budget_range_max | Form number | Direct (0 if empty) |

**JSON Structure in sales_notes**:
```json
{
  "service_types": ["static_guard", "armed_guard"],
  "allowances": ["transport_allowance", "performance_bonus"],
  "overtime_hours": "2",
  "inventory": {
    "uniform_sets": 5,
    "jacket": 3,
    "walkie_talkie": 2,
    ...
  },
  "custom_working_hours": "Monday-Friday 9AM-5PM"
}
```

---

## Client-Side Features

### Dynamic Question Updates

```javascript
// Triggered when service type checkboxes change
function updateDynamicQuestions()
  - Get all checked service types
  - If none selected: hide questionnaire section
  - If selected: populate questions based on service
  - Show inventory section
```

### Country-based Auto-Population

```javascript
// Triggered when country select changes
function handleCountryChange()
  - If Malaysia: auto-check and disable RBA checkbox
  - If India: enable RBA for manual selection
```

### Working Hours Customization

```javascript
// Triggered when working hours radio change
function handleWorkingHoursChange(value)
  - If value == '24': show custom hours textarea
  - If value == '8' or '12': hide custom hours textarea
```

### Form Reset

- "Clear Form" button resets all fields to empty
- Does not reset to default values, truly clears form

---

## Styling & Design

### Color Scheme
- **Primary Color**: Red (#dc2626, #ef4444)
- **Background**: Gradient gray (from-gray-50 to-gray-100)
- **Cards**: White with shadow
- **Borders**: Gray-300

### Layout
- **Maximum Width**: 4xl (56rem)
- **Grid**: Responsive (1 col mobile, 2 col tablet+)
- **Spacing**: Consistent 6-unit gaps

### Visual Indicators
- **Section Headers**: Icon + Title
- **Form Sections**: Left border bar (4px red)
- **Required Fields**: Red asterisk (*)
- **Completed Sections**: Green border (future)
- **Error Fields**: Red border with error message

### Components
- Tailwind CSS (CDN)
- Font Awesome icons (v6.4.0)
- Custom animations (slideIn for toasts)

---

## Validation Rules

### Client-Side (HTML5)
- Required field attributes
- Email validation
- Number min/max
- Regex patterns (if needed)

### Server-Side (Laravel)

**Public Form Validation**:
```php
'company_name' => 'required|string|max:255',
'contact_person_name' => 'required|string|max:255',
'email' => 'required|email|unique:leads,email',
'mobile_number' => 'required|string|max:20',
'address' => 'required|string',
'city' => 'required|string|max:100',
'postal_code' => 'required|string|max:20',
'country' => 'required|string|max:100|in:India,Malaysia',
'service_location' => 'nullable|string',
'service_types' => 'required|array|min:1',
'working_hours_type' => 'required|in:8,12,24',
'custom_working_hours' => 'nullable|string',
'overtime_hours' => 'nullable|in:1,2,3,4',
'allowances' => 'nullable|array',
'site_type' => 'required|string|max:50|in:office,factory,residential,event,retail,hospital,educational,other',
'compliance_required' => 'nullable|in:yes,no',
'rba_applicable' => 'nullable|boolean',
'sales_notes' => 'nullable|string',
'client_expectations' => 'nullable|string',
'follow_up_date' => 'nullable|date',
'budget_range_min' => 'nullable|integer|min:0',
'budget_range_max' => 'nullable|integer|min:0',
'inventory' => 'nullable|array',
'action' => 'required|in:draft,submit',
```

---

## User Experience Flow

```
1. Customer visits /lead-form
   ↓
2. Form loads with all sections visible
   ↓
3. Customer fills Section 1: Client & Site Details
   ↓
4. Customer selects service types in Section 2
   ↓
5. Based on selection, Sections 6 & 7 appear with dynamic questions & inventory
   ↓
6. Customer fills remaining sections
   ↓
7. Customer chooses to "Save as Draft" OR "Submit Lead"
   ↓
8. Form validates and submits to server
   ↓
9. If errors: Page reloads with error highlights and form repopulated
   ↓
10. If success: Redirect to home page with success message
```

---

## Admin Review Process

### Accessing Public Submissions

**Location**: `/leads` (Leads index)
**Filter**: Status = "submitted" or "draft"

### Lead Status Values

For public submissions:
- `draft` - Incomplete form saved for later
- `submitted` - Completed and submitted form

### Data Extraction

Admins view leads through standard Lead Management interface:

1. **View Lead Details**: Click on lead → Show page
2. **Expand Sales Notes**: JSON data accessible in sales_notes field
3. **Review Responses**: Dynamic questions shown in responses section
4. **Convert Lead**: 
   - Create client record
   - Generate quotation
   - Enable pricing section
   - Update lead_status to "closed_won"

---

## Submission Response Messages

### Success Messages

**Draft Save**:
```
"Your form has been saved as draft. You can continue filling it later using your email."
```

**Submit**:
```
"Thank you! Your lead has been submitted successfully. Our team will contact you shortly."
```

### Error Messages

**Validation Errors**:
- Displayed inline below field
- Example: "This email address is already in use"

**Server Errors**:
- Toast notification in top-right
- Message depends on error type

---

## Key Business Rules

### Mandatory Fields
1. Company Name
2. Contact Person
3. Email (Unique)
4. Mobile Number
5. Address
6. City
7. Postal Code
8. Country (India/Malaysia)
9. Site Type
10. Service Type (min 1)
11. Working Hours

### Auto-Set Values
- `service_type_id` = 1 (Security)
- `guard_type` = "both"
- `tentative_guards_count` = 1
- `lead_source` = "website"
- `state` = "N/A"
- `rba_applicable` = true (if Malaysia)
- `compliance_required` = "no" (default)

### Data Conversion

**Public Form → Lead Record**:
```
Service Types Array → Stored in sales_notes (JSON)
Allowances Array → Stored in sales_notes (JSON)
Overtime Hours → Stored in sales_notes (JSON)
Inventory Object → Stored in sales_notes (JSON)
Custom Working Hours → Stored in sales_notes (JSON)
Manual Sales Notes → Appended with JSON data
```

---

## Security Considerations

### Protection Measures
1. **No Authentication Required**: Public form accessible without login
2. **CSRF Protection**: Form includes CSRF token
3. **Email Validation**: Ensures valid email format
4. **Unique Email Check**: Prevents duplicate submissions
5. **Input Sanitization**: Laravel auto-sanitizes all inputs
6. **Server-Side Validation**: All client inputs re-validated
7. **No Sensitive Data**: No passwords, PII, or financial info requested

### Rate Limiting (Recommended)
Should be implemented to prevent spam:
```php
Route::post('/lead-form', [LeadController::class, 'store'])
    ->middleware('throttle:10,60'); // 10 requests per minute
```

---

## Accessibility

### Features
- Semantic HTML (label associations, fieldsets)
- Aria labels on icon buttons
- Color contrast (WCAG AA compliant)
- Keyboard navigation support
- Tab order follows form flow
- Error messages associated with fields

### Enhancements Possible
- Add aria-describedby for help text
- Aria-live regions for dynamic updates
- Screen reader optimized radio button groups
- CAPTCHA for bot prevention

---

## Mobile Responsiveness

### Breakpoints
- **Mobile**: 1 column layout
- **Tablet** (md): 2 column layout
- **Desktop** (lg): 2 column layout

### Mobile Optimizations
- Touch-friendly button sizes (44px minimum)
- Larger input fields (py-2 padding)
- Full-width sections on mobile
- Sticky bottom action buttons
- Single column grids for stacked fields

---

## Future Enhancements

1. **Email Notification**: Send confirmation email to customer
2. **Draft Recovery**: Email link to resume incomplete form
3. **Dynamic Pricing**: Show estimated costs
4. **Questionnaire Integration**: Load questions from admin config
5. **File Uploads**: Allow document attachments
6. **Geographic Restrictions**: Limit services by region
7. **Multi-language**: Support India, Malaysia local languages
8. **Analytics**: Track form completion rates, drop-off points
9. **Captcha**: Add reCAPTCHA v3 for bot prevention
10. **Progressive Form**: Multi-step wizard instead of single page

---

## Troubleshooting

### Form Not Submitting

**Issue**: "Validation failed. Please check your inputs."

**Solutions**:
1. Verify all required fields have values
2. Check email is not already in system
3. Ensure country is India or Malaysia
4. Check at least one service type selected
5. Verify working hours selected

### Redirect Not Working

**Issue**: After submission, page doesn't redirect

**Solutions**:
1. Check browser console for JS errors
2. Verify form action URL is `/lead-form`
3. Check POST method is used
4. Verify CSRF token present

### Dynamic Questions Not Appearing

**Issue**: Questions don't show after selecting service type

**Solutions**:
1. Ensure JavaScript enabled in browser
2. Check browser console for JS errors
3. Clear browser cache and reload
4. Try different service type combination

---

## API Endpoint Reference

### Public Lead Form Submission

**Endpoint**: `/lead-form`
**Method**: POST
**Authentication**: None (Public)

**Request Fields** (Form Data):
```
_token: [CSRF Token]
action: draft|submit
company_name: string
contact_person_name: string
email: string
mobile_number: string
address: string
city: string
postal_code: string
country: India|Malaysia
service_location: string
site_type: office|factory|residential|event|retail|hospital|educational|other
service_types[]: array (static_guard|armed_guard|escort_service)
working_hours_type: 8|12|24
custom_working_hours: string
overtime_hours: 1|2|3|4
allowances[]: array
compliance_required: yes|no
rba_applicable: 0|1
sales_notes: string
client_expectations: string
follow_up_date: date
budget_range_min: integer
budget_range_max: integer
inventory[uniform_sets]: integer
inventory[jacket]: integer
... (other inventory items)
```

**Response**: Redirect to home page with success message in session flash

---

## Contact & Support

For issues or questions:
- Contact Sales Team: [sales@example.com]
- Support Portal: [support.example.com]
- Chat Support: Available 9 AM - 6 PM IST

