# Ad Creation & Verification Logic Documentation

## Overview
This document explains how the verification system works when users create ads (buy/sell) for companies and funds.

---

## 1. Sell Ads - Verification Logic

### When a user creates a SELL ad:

#### Verified Ad ✅
**Condition:** User IS registered in the company's shareholder registry

**Flow:**
1. User selects a company/fund they own shares/units in
2. System checks: Is user registered in the shareholder registry?
3. If **YES** → Ad is **verified** immediately
4. Ad status: `verified`
5. No verification request needed

**Example:**
- User owns 500 shares in "Riyadh Tech Company"
- User IS in the company's shareholder registry
- Creates sell ad → **Verified immediately** ✅

---

#### Unverified Ad ⚠️
**Condition:** User is NOT registered in the company's shareholder registry

**Flow:**
1. User selects a company/fund they claim to own shares/units in
2. System checks: Is user registered in the shareholder registry?
3. If **NO** → Ad is **unverified** (pending verification)
4. System sends verification request to the company/fund
5. Company reviews the request:
   - **Accept** → Ad becomes verified
   - **Reject** → Ad remains unverified or gets removed
6. Ad status: `pending_verification`

**Example:**
- User claims to own 150 shares in "Dammam Trading Company"
- User is NOT in the company's shareholder registry
- Creates sell ad → **Unverified** (pending) ⚠️
- Verification request sent to company
- Company verifies → Ad becomes verified ✅

**User Warning:**
```
⚠️ Unverified Ad
This company is not verified in the shareholder registry.
A verification request will be sent to the company after publishing the ad.
The company will review the request and accept or reject it.
```

---

## 2. Buy Ads - Verification Logic

### Question for Backend Team:

**Does a buyer need verification from the company/fund before creating a BUY ad?**

### Option A: No Verification Required (Recommended)
**Logic:** Anyone can create a buy ad for any company/fund without pre-verification

**Flow:**
1. User selects any company/fund from the complete list
2. Creates buy ad immediately
3. No verification needed
4. Ad status: `active`

**Rationale:**
- Buyer doesn't need to be a shareholder to express interest in buying
- Verification happens AFTER the transaction is agreed upon
- More flexible for buyers

---

### Option B: Verification Required
**Logic:** Buyer must be registered in shareholder registry (or will be after purchase)

**Flow:**
1. User selects company/fund
2. System checks if user is registered
3. If NO → Send verification request
4. Similar to sell ad logic

**When to use this:**
- If regulations require pre-registration before purchasing
- If the platform requires KYC verification with the company first

---

## 3. Data Structure

### For Sell Ads (User's Portfolio)
```php
$my_companies = [
    [
        'id' => 1,
        'name' => 'Riyadh Tech Company',
        'shares' => 500,
        'verified' => true,  // User IS in shareholder registry
    ],
    [
        'id' => 3,
        'name' => 'Dammam Trading Company',
        'shares' => 150,
        'verified' => false, // User NOT in shareholder registry
    ],
];
```

### For Buy Ads (All Available Companies)
```php
$all_companies = get_companies(); // All companies from database
// No 'verified' field needed (unless Option B is chosen)
```

---

## 4. Backend API Requirements

### Endpoint: `POST /api/ads/create`

#### Request Body:
```json
{
  "type": "sell",              // or "buy"
  "asset_type": "company",     // or "fund"
  "asset_id": 1,               // company_id or fund_id
  "quantity": 150,
  "price_type": "fixed",       // or "negotiable"
  "price": 45.50,              // null if negotiable
  "description": "...",
  "partial_sale": true
}
```

#### Backend Logic:
```php
if ($request->type === 'sell') {
    // Check if user owns this asset
    $userAsset = UserAsset::where('user_id', $user->id)
                          ->where('asset_id', $request->asset_id)
                          ->first();

    if (!$userAsset) {
        return error('You do not own this asset');
    }

    // Check verification status
    $isVerified = ShareholderRegistry::where('user_id', $user->id)
                                     ->where('company_id', $request->asset_id)
                                     ->exists();

    $ad = Ad::create([
        'user_id' => $user->id,
        'asset_id' => $request->asset_id,
        'verified' => $isVerified,
        'status' => $isVerified ? 'active' : 'pending_verification',
        // ... other fields
    ]);

    if (!$isVerified) {
        // Send verification request to company
        VerificationRequest::create([
            'ad_id' => $ad->id,
            'user_id' => $user->id,
            'company_id' => $request->asset_id,
            'status' => 'pending',
        ]);

        // Notify company
        Notification::send($company, new VerificationRequestNotification($ad));
    }
}
```

---

## 5. Verification Request Flow

### 5.1. Send Verification Request
**When:** User creates unverified sell ad

**Data stored:**
```json
{
  "id": 1,
  "ad_id": 123,
  "user_id": 456,
  "company_id": 789,
  "status": "pending",
  "requested_at": "2025-01-23 10:00:00",
  "reviewed_at": null,
  "reviewed_by": null,
  "notes": null
}
```

---

### 5.2. Company Reviews Request
**Endpoint:** `POST /api/verification-requests/{id}/review`

**Request:**
```json
{
  "action": "approve",  // or "reject"
  "notes": "Verified in shareholder registry"
}
```

**Backend Logic:**
```php
$request->update([
    'status' => $action === 'approve' ? 'approved' : 'rejected',
    'reviewed_at' => now(),
    'reviewed_by' => $company_user_id,
    'notes' => $notes,
]);

if ($action === 'approve') {
    // Update ad status
    $request->ad->update(['verified' => true, 'status' => 'active']);

    // Update shareholder registry
    ShareholderRegistry::firstOrCreate([
        'user_id' => $request->user_id,
        'company_id' => $request->company_id,
    ]);

    // Notify user
    Notification::send($user, new VerificationApprovedNotification($ad));
} else {
    // Notify user of rejection
    Notification::send($user, new VerificationRejectedNotification($ad));
}
```

---

## 6. Database Tables

### `ads` table
```sql
CREATE TABLE ads (
    id BIGINT PRIMARY KEY,
    user_id BIGINT,
    type ENUM('buy', 'sell'),
    asset_type ENUM('company', 'fund'),
    asset_id BIGINT,
    quantity INT,
    price_type ENUM('fixed', 'negotiable'),
    price DECIMAL(10, 2) NULL,
    verified BOOLEAN DEFAULT FALSE,
    status ENUM('active', 'pending_verification', 'rejected', 'completed'),
    created_at TIMESTAMP,
    updated_at TIMESTAMP
);
```

### `verification_requests` table
```sql
CREATE TABLE verification_requests (
    id BIGINT PRIMARY KEY,
    ad_id BIGINT,
    user_id BIGINT,
    company_id BIGINT,
    status ENUM('pending', 'approved', 'rejected'),
    requested_at TIMESTAMP,
    reviewed_at TIMESTAMP NULL,
    reviewed_by BIGINT NULL,
    notes TEXT NULL,
    created_at TIMESTAMP,
    updated_at TIMESTAMP
);
```

### `shareholder_registry` table
```sql
CREATE TABLE shareholder_registry (
    id BIGINT PRIMARY KEY,
    user_id BIGINT,
    company_id BIGINT,
    shares INT,
    verified_at TIMESTAMP,
    created_at TIMESTAMP,
    updated_at TIMESTAMP,
    UNIQUE(user_id, company_id)
);
```

---

## 7. Questions for Backend Team

**Please clarify the following:**

1. **Buy Ads:** Should buyers be verified before creating buy ads? (Option A or Option B?)

2. **Shareholder Registry:** Where does the initial shareholder registry data come from?
   - Imported from companies?
   - Manual registration?
   - API integration with external system?

3. **Verification Rejection:** What happens when a company rejects verification?
   - Ad gets deleted?
   - Ad stays but marked as rejected?
   - User gets penalty?

4. **Multiple Verification Requests:** Can a user retry verification if rejected?

5. **Fund vs Company:** Are funds handled the same way as companies for verification?

---

## 8. Frontend Implementation

### Current Implementation:
- ✅ Select2 dropdown for company/fund selection
- ✅ Show verified/unverified badge
- ✅ Warning message for unverified ads
- ✅ Confirmation dialog before submitting unverified ad

### Data Sent to Backend:
```javascript
const formData = {
    type: 'sell',
    asset_type: 'company',
    asset_id: $('#company-select').val(),
    quantity: $('#quantity').val(),
    price_type: $('input[name="price_type"]:checked').val(),
    price: $('#price').val() || null,
    description: $('textarea[name="description"]').val(),
    partial_sale: $('#partial_sale').is(':checked')
};

// POST to /api/ads/create
```

---

## Contact
If you need any clarification or have questions, please reach out to the frontend team.

**Last Updated:** 2025-01-23
