# Ads Data Structure & Scenarios

This document describes the complete data structure for ads and all possible scenarios that the backend should handle.

## Ad Data Structure

```json
{
    "id": 1,
    "name": "اسم الشركة أو الصندوق",
    "sector": "القطاع أو نوع الصندوق",
    "image": "images/companies/logo.webp",
    "price": "150",  // "0" if negotiable
    "shares": "1,000",  // Number of shares/units
    "value": "150k",
    "offers": "5",
    "views": "245",
    "time": "منذ 3 ساعات",
    "type": "sell",  // "sell" or "buy"
    "verified": true,  // true or false
    "bg": "#f9f1f3",
    "asset_type": "company",  // "company" or "fund"
    "price_type": "fixed",  // "fixed" or "negotiable"
    "description": "وصف تفصيلي للإعلان",
    "order_number": "AD-2024-1001",  // Unique order identifier
    "ad_status": "active",  // "active", "closed", or "pending"
    "ad_stage": "receiving_offers",  // "receiving_offers" or "completed"
    "seller": {
        "name": "محمد عبدالله الشمري",
        "verified": true,
        "avatar": "images/avatar.jpg",
        "member_since": "2022"
    },
    "submitted_offers": [
        {
            "id": 1,
            "buyer_name": "أحمد خالد العتيبي",
            "buyer_verified": true,
            "quantity": "500",
            "price_per_share": "148",
            "total": "74,000",
            "status": "pending",  // "pending", "accepted", "rejected"
            "time": "منذ ساعة واحدة"
        }
    ]
}
```

## Field Descriptions

### Required Fields

| Field | Type | Description | Values |
|-------|------|-------------|--------|
| `id` | integer | Unique identifier | Any positive integer |
| `name` | string | Company or fund name | Arabic text |
| `sector` | string | Sector or fund type | Arabic text |
| `type` | string | Ad type | `"sell"` or `"buy"` |
| `verified` | boolean | Verification status | `true` or `false` |
| `asset_type` | string | Type of asset | `"company"` or `"fund"` |
| `price_type` | string | Pricing model | `"fixed"` or `"negotiable"` |
| `shares` | string | Total quantity (formatted) | Formatted number with comma separator |
| `sold_shares` | string | Quantity sold (formatted) | Formatted number, default "0" |

### Optional Fields

| Field | Type | Description |
|-------|------|-------------|
| `image` | string | Path to logo image |
| `price` | string | Price per share/unit (set to "0" if negotiable) |
| `value` | string | Total value (formatted) |
| `offers` | string | Number of offers received |
| `views` | string | Number of views |
| `time` | string | Time since posted (Arabic) |
| `bg` | string | Background color (hex) |
| `description` | string | Detailed description (supports line breaks) |
| `order_number` | string | Unique order identifier (e.g., "AD-2024-1001") |
| `ad_status` | string | Ad status: `"active"`, `"closed"`, or `"pending"` |
| `ad_stage` | string | Progress stage: `"receiving_offers"` or `"completed"` |
| `seller` | object | Ad creator information (see Seller Object below) |
| `submitted_offers` | array | List of submitted offers (see Offer Object below) |

### Seller Object

| Field | Type | Description |
|-------|------|-------------|
| `name` | string | Seller's full name |
| `verified` | boolean | Whether seller account is verified |
| `avatar` | string | Path to seller's avatar image |
| `member_since` | string | Year the seller joined |

### Offer Object

| Field | Type | Description |
|-------|------|-------------|
| `id` | integer | Offer unique identifier |
| `buyer_name` | string | Buyer's full name |
| `buyer_verified` | boolean | Whether buyer account is verified |
| `quantity` | string | Number of shares/units in the offer |
| `price_per_share` | string | Price per share/unit offered |
| `total` | string | Total offer amount (formatted) |
| `status` | string | Offer status: `"pending"`, `"accepted"`, or `"rejected"` |
| `time` | string | Time since offer submitted (Arabic) |

## All Possible Scenarios

The system supports 9 different scenarios covering all combinations:

### Sell Ads (5 scenarios)

#### 1. Sell - Company - Fixed Price - Verified ✅
```json
{
    "type": "sell",
    "asset_type": "company",
    "price_type": "fixed",
    "verified": true,
    "price": "150",
    "shares": "1,000"
}
```
**Use Case**: User owns verified shares in a company and wants to sell at a fixed price.
**Backend Action**: Ad published immediately as verified.

---

#### 2. Sell - Company - Negotiable Price - Verified ✅
```json
{
    "type": "sell",
    "asset_type": "company",
    "price_type": "negotiable",
    "verified": true,
    "price": "0",
    "shares": "800"
}
```
**Use Case**: User owns verified shares but wants to negotiate price with buyers.
**Backend Action**: Ad published immediately, buyers can submit offers with their proposed price.

---

#### 3. Sell - Company - Fixed Price - Unverified ⚠️
```json
{
    "type": "sell",
    "asset_type": "company",
    "price_type": "fixed",
    "verified": false,
    "price": "120",
    "shares": "500"
}
```
**Use Case**: User claims to own shares but is not in the shareholder registry.
**Backend Action**:
- Send verification request to company
- Mark ad as "pending verification"
- Company reviews and approves/rejects
- If approved, set `verified: true`

---

#### 4. Sell - Fund - Fixed Price - Verified ✅
```json
{
    "type": "sell",
    "asset_type": "fund",
    "price_type": "fixed",
    "verified": true,
    "price": "85",
    "shares": "300"
}
```
**Use Case**: User owns verified fund units and wants to sell at a fixed price.
**Backend Action**: Ad published immediately as verified.

---

#### 5. Sell - Fund - Negotiable Price - Unverified ⚠️
```json
{
    "type": "sell",
    "asset_type": "fund",
    "price_type": "negotiable",
    "verified": false,
    "price": "0",
    "shares": "200"
}
```
**Use Case**: User claims to own fund units (not verified) and wants to negotiate price.
**Backend Action**:
- Send verification request to fund manager
- Mark ad as "pending verification"
- Accept price offers from buyers

---

### Buy Ads (4 scenarios)

**Important**: Buy ads DO NOT require verification since the user is purchasing, not claiming ownership.

#### 6. Buy - Company - Fixed Price 💰
```json
{
    "type": "buy",
    "asset_type": "company",
    "price_type": "fixed",
    "verified": true,
    "price": "95",
    "shares": "600"
}
```
**Use Case**: User wants to buy specific number of company shares at a fixed price.
**Backend Action**: Sellers can accept the offer directly if they agree to the price.

---

#### 7. Buy - Company - Negotiable Price 💰
```json
{
    "type": "buy",
    "asset_type": "company",
    "price_type": "negotiable",
    "verified": true,
    "price": "0",
    "shares": "400"
}
```
**Use Case**: User wants to buy company shares and will negotiate price with sellers.
**Backend Action**: Sellers can submit their price offers.

---

#### 8. Buy - Fund - Fixed Price 💰
```json
{
    "type": "buy",
    "asset_type": "fund",
    "price_type": "fixed",
    "verified": true,
    "price": "110",
    "shares": "250"
}
```
**Use Case**: User wants to buy fund units at a fixed price.
**Backend Action**: Sellers can accept the offer directly.

---

#### 9. Buy - Fund - Negotiable Price 💰
```json
{
    "type": "buy",
    "asset_type": "fund",
    "price_type": "negotiable",
    "verified": true,
    "price": "0",
    "shares": "150"
}
```
**Use Case**: User wants to buy fund units and will negotiate price.
**Backend Action**: Sellers can submit their price offers.

---

## Shares Tracking & Progress

### For SELL Ads:

Ads track three key metrics:
1. **Total Shares** (`shares`): Original quantity listed for sale
2. **Sold Shares** (`sold_shares`): Cumulative quantity that has been sold
3. **Remaining Shares** (computed): `shares - sold_shares`

### How Sold Shares Work:

1. **Initial State**: `sold_shares = 0`, all shares available
2. **Offer Accepted**: When seller accepts an offer, `sold_shares` += offer quantity
3. **Multiple Deals**: Seller can accept multiple offers until all shares are sold
4. **Completion**: When `sold_shares = shares`, ad automatically moves to "completed" stage

### Example:

```json
{
    "shares": "1,000",      // Total shares for sale
    "sold_shares": "300",   // 300 shares already sold
    // remaining = 700 shares still available
    "ad_stage": "receiving_offers"  // Still accepting offers
}
```

After accepting another offer for 700 shares:
```json
{
    "shares": "1,000",
    "sold_shares": "1,000",  // All shares sold
    // remaining = 0
    "ad_stage": "completed"  // Auto-updated to completed
}
```

### Stage Determination:

```javascript
if (remaining_shares > 0) {
    ad_stage = "receiving_offers";
    ad_status = "active";
} else {
    ad_stage = "completed";
    ad_status = "closed";
}
```

---

## Verification Logic

### For SELL Ads:

1. **If user IS in shareholder/investor registry** → `verified: true`
   - Ad is published immediately
   - No verification request needed

2. **If user is NOT in registry** → `verified: false`
   - Ad is published as "unverified"
   - System sends verification request to company/fund
   - Company/fund reviews and approves/rejects
   - On approval: Update `verified: true`
   - On rejection: Ad remains unverified or can be removed

### For BUY Ads:

- **NO verification needed** (user is purchasing, not claiming ownership)
- All buy ads are published immediately
- `verified: true` by default (indicates ad itself is legitimate, not ownership)

---

## Display Logic

### Price Display

```php
if ($price_type === 'negotiable') {
    echo "قابل للتفاوض";
} else {
    echo $price . " ريال";
}
```

### Quantity Label

```php
$label = ($asset_type === 'company') ? 'أسهم' : 'وحدات';
$label_single = ($asset_type === 'company') ? 'سهم' : 'وحدة';
```

### Verification Badge

```php
// Only for SELL ads
if ($type === 'sell' && $verified === true) {
    echo "موثق";
}
```

---

## Database Schema Recommendations

### ads table

```sql
CREATE TABLE ads (
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT NOT NULL,
    name VARCHAR(255) NOT NULL,
    sector VARCHAR(255),
    asset_type ENUM('company', 'fund') NOT NULL,
    type ENUM('sell', 'buy') NOT NULL,
    price_type ENUM('fixed', 'negotiable') NOT NULL,
    price DECIMAL(10,2) DEFAULT 0,
    quantity INT NOT NULL,
    verified BOOLEAN DEFAULT FALSE,
    description TEXT,
    image VARCHAR(255),
    views INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

### verification_requests table

```sql
CREATE TABLE verification_requests (
    id INT PRIMARY KEY AUTO_INCREMENT,
    ad_id INT NOT NULL,
    entity_id INT NOT NULL,  -- company_id or fund_id
    entity_type ENUM('company', 'fund') NOT NULL,
    status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    reviewed_at TIMESTAMP NULL,

    FOREIGN KEY (ad_id) REFERENCES ads(id)
);
```

---

## API Endpoints Recommendations

### Create Ad
```
POST /api/ads
```

**Request Body:**
```json
{
    "asset_type": "company",
    "company_id": 1,  // or fund_id
    "type": "sell",
    "price_type": "fixed",
    "price": 150.00,
    "quantity": 1000,
    "description": "Description text"
}
```

**Response:**
```json
{
    "success": true,
    "ad_id": 123,
    "verified": true,  // or false if verification needed
    "verification_request_sent": false  // true if sent to company/fund
}
```

### Get Ads
```
GET /api/ads?type=sell&asset_type=company&verified=true
```

### Submit Offer
```
POST /api/ads/{ad_id}/offers
```

**Request Body:**
```json
{
    "price": 145.00,  // proposed price per unit
    "quantity": 500,
    "message": "Optional message"
}
```

---

## Ad Details Page Structure

The ad details page (`ad-details.php`) displays comprehensive information about an ad:

### 1. Header Section
- **Order Number**: Unique identifier for the ad (e.g., "AD-2024-1001")
- **Ad Stage Badge**: Shows current stage
  - "مرحلة تلقي العروض" (Receiving Offers) - Blue badge
  - "تم إتمام الصفقة" (Deal Completed) - Green badge

### 2. Title & Badges
- **Ad Type**: "بيع" (Sell) or "شراء" (Buy)
- **Verification Status**:
  - "موثق" (Verified) - Green badge
  - "غير موثق" (Unverified) - Amber badge
- **Ad Status**:
  - "نشط" (Active) - Green
  - "مغلق" (Closed) - Gray
  - "معلق" (Pending) - Yellow
- **Time & Views**: Time since posted and view count

### 3. Stats Cards (4 cards)
1. **Price per Share/Unit**:
   - Fixed price: Shows amount in SAR
   - Negotiable: Shows "قابل للتفاوض"
2. **Quantity**: Number of shares/units
3. **Number of Offers**: Total offers submitted
4. **Total Deal Value**:
   - Fixed price: Calculated total
   - Negotiable: Shows "حسب العرض"

### 4. Description Section
- Displays detailed ad description
- Preserves line breaks
- Only shown if description exists

### 5. Submitted Offers Section
- Only shown if offers exist
- For each offer displays:
  - Buyer name with verification badge
  - Time since offer submitted
  - Offer status badge (Pending/Accepted/Rejected)
  - Three stats: Quantity, Price per share, Total amount

### 6. Company/Fund Information
- Company or fund details
- Verification badge
- Link to company/fund details page

### 7. Ad Creator Card (Sidebar)
- Creator's name
- Account verification status
- Member since year
- Avatar image

### 8. Calculator (Sidebar)
- Interactive quantity selector
- VAT calculation (15%)
- Total cost calculator
- Submit offer button

---

## Frontend Examples

All 9 scenarios are implemented in `/data/ads.json`:

- **ID 1**: Sell - Company - Fixed - Verified
- **ID 2**: Sell - Company - Negotiable - Verified
- **ID 3**: Sell - Company - Fixed - Unverified
- **ID 4**: Sell - Fund - Fixed - Verified
- **ID 5**: Sell - Fund - Negotiable - Unverified
- **ID 6**: Buy - Company - Fixed
- **ID 7**: Buy - Company - Negotiable
- **ID 8**: Buy - Fund - Fixed
- **ID 9**: Buy - Fund - Negotiable

Each example includes realistic data and descriptions explaining the scenario.
