# Ad Details Page - Implementation Summary

## Overview
This document outlines the complete implementation of the ad details page with all required features.

---

## ✅ Implemented Features

### 1. Order Number (رقم الطلب)
- **Field**: `order_number`
- **Display**: Top of the page in a gray badge
- **Format**: "AD-2024-1001"
- **Backend**: Generate unique order numbers for each ad

### 2. Company/Fund Name (اسم الشركة أو الصندوق)
- **Field**: `name`
- **Display**: Main heading
- **Dynamic**: Shows "أسهم" for companies, "وحدات" for funds

### 3. Quantity (عدد الأسهم/الوحدات)
- **Fields**:
  - `shares` - إجمالي الأسهم
  - `sold_shares` - الالاسهم المباعة
  - `remaining_shares` - الأسهم المتبقية (محسوبة: shares - sold_shares)
- **Display**:
  - Stats card #2: إجمالي الأسهم
  - Stats card #3: الالاسهم المباعة (Green)
  - Stats card #4: الأسهم المتبقية (Blue)
  - Progress bar showing completion percentage
- **Labels**: Dynamic based on asset_type

### 4. Ad Status (حالة الإعلان)
- **Field**: `ad_status`
- **Values**:
  - `active` → "نشط" (Green)
  - `closed` → "مغلق" (Gray)
  - `pending` → "معلق" (Yellow)
- **Display**: Badge next to title

### 5. Ad Type (نوع الإعلان)
- **Field**: `type`
- **Values**:
  - `sell` → "بيع" (Red badge)
  - `buy` → "شراء" (Blue badge)
- **Display**: Primary badge in header

### 6. Price per Share (سعر السهم/الوحدة)
- **Field**: `price`, `price_type`
- **Fixed Price**: Shows amount in SAR
- **Negotiable**: Shows "قابل للتفاوض"
- **Display**: Stats card #1

### 7. Number of Offers (عدد العروض المقدمة)
- **Field**: `submitted_offers` (array length) or `offers` (fallback)
- **Display**: Stats card #5 (Amber color)
- **Dynamic**: Counts submitted_offers array

### 8. Submit Offer Button (زر تقديم عرض)
- **Location**: Calculator sidebar
- **Dynamic Text**: "تقديم عرض شراء" or "تقديم عرض بيع"
- **Opens**: Offer submission modal
- **Disabled State**: When `remaining_shares = 0`, button is disabled and shows "تم بيع جميع الأسهم"

### 9. Ad Progress Stage (مرحلة تقدم الإعلان)
- **Field**: `ad_stage` (calculated automatically based on remaining shares)
- **Calculation Logic**:
  - If `remaining_shares > 0` → `receiving_offers`
  - If `remaining_shares = 0` → `completed`
- **Values**:
  - `receiving_offers` → "مرحلة تلقي العروض" (Blue badge)
  - `completed` → "تم إتمام الصفقة" (Green badge)
- **Display**: Top section with order number
- **Important**: Stage is automatically calculated on frontend, backend should calculate when updating sold_shares

### 10. Progress Bar (شريط التقدم)
- **Field**: `ad_stage`
- **Values**:
  - `receiving_offers` → "مرحلة تلقي العروض" (Blue badge)
  - `completed` → "تم إتمام الصفقة" (Green badge)
- **Display**: Top section with order number

### 10. Progress Bar (شريط التقدم)
- **Display**: Below stats cards (for sell ads only)
- **Shows**:
  - Percentage completion: `(sold_shares / total_shares) * 100`
  - Progress bar with gradient fill
  - Text showing sold vs total (e.g., "تم بيع 300 من 1,000")
  - Remaining count or completion message
- **Purpose**: Visual representation of how many shares have been sold

### 11. Ad Creator Details (تفاصيل منشئ الإعلان)
- **Object**: `seller`
- **Fields**:
  - `name` - الاسم
  - `verified` - حالة التوثيق (boolean)
  - `avatar` - صورة الحساب
  - `member_since` - عضو منذ
- **Display**: Sidebar card with verification badge

### 11. Submitted Offers (العروض المقدمة)
- **Array**: `submitted_offers`
- **Each offer contains**:
  - `buyer_name` - اسم المشتري
  - `buyer_verified` - حالة التوثيق
  - `quantity` - عدد الأسهم/الوحدات
  - `price_per_share` - سعر السهم/الوحدة
  - `total` - الإجمالي
  - `status` - حالة العرض (pending/accepted/rejected)
  - `time` - وقت التقديم
- **Display**: Dedicated section with cards for each offer

---

## Data Structure Example

### Full Ad Object

```json
{
    "id": 1,
    "name": "شركة الرياض للتقنية",
    "sector": "قطاع التقنية",
    "image": "images/companies/cibc.webp",
    "price": "150",
    "shares": "1,000",
    "sold_shares": "300",
    "value": "150k",
    "offers": "5",
    "views": "245",
    "time": "منذ 3 ساعات",
    "type": "sell",
    "verified": true,
    "bg": "#f9f1f3",
    "asset_type": "company",
    "price_type": "fixed",
    "description": "وصف الإعلان...",
    "order_number": "AD-2024-1001",
    "ad_status": "active",
    "ad_stage": "receiving_offers",
    "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",
            "time": "منذ ساعة واحدة"
        }
    ]
}
```

---

## Page Layout

```
┌─────────────────────────────────────────────────────────┐
│ Order Number & Ad Stage Badge                           │
└─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────┐
│ Badges (Type, Verification, Status)                     │
│ Title                                                    │
│ Time & Views                                            │
└─────────────────────────────────────────────────────────┘

┌──────────┬──────────┬──────────┬──────────┐
│  Price   │ Quantity │  Offers  │  Total   │
│  Card    │   Card   │   Card   │   Card   │
└──────────┴──────────┴──────────┴──────────┘

┌─────────────────────────────────────────────────────────┐
│ Description                                              │
└─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────┐
│ Submitted Offers                                         │
│ ┌─────────────────────────────────────────────────┐    │
│ │ Offer #1: Buyer Name + Verification             │    │
│ │ [Quantity] [Price] [Total]                       │    │
│ └─────────────────────────────────────────────────┘    │
│ ┌─────────────────────────────────────────────────┐    │
│ │ Offer #2: Buyer Name + Verification             │    │
│ │ [Quantity] [Price] [Total]                       │    │
│ └─────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────┐
│ Company/Fund Info                                        │
└─────────────────────────────────────────────────────────┘

SIDEBAR:
┌─────────────────────────────────────┐
│ Ad Creator Card                      │
│ ● Name                               │
│ ● Verification Status                │
│ ● Member Since                       │
└─────────────────────────────────────┘

┌─────────────────────────────────────┐
│ Calculator                           │
│ ● Quantity Selector                  │
│ ● Price Calculation                  │
│ ● VAT (15%)                          │
│ ● Total                              │
│ [Submit Offer Button]                │
└─────────────────────────────────────┘
```

---

## Backend Requirements

### 1. Database Schema

#### ads table additions:
```sql
ALTER TABLE ads ADD COLUMN order_number VARCHAR(50) UNIQUE;
ALTER TABLE ads ADD COLUMN ad_status ENUM('active', 'closed', 'pending') DEFAULT 'active';
ALTER TABLE ads ADD COLUMN sold_shares INT DEFAULT 0;
ALTER TABLE ads ADD COLUMN seller_id INT;

-- Note: ad_stage is calculated dynamically (remaining_shares > 0 ? 'receiving_offers' : 'completed')
-- It should be computed in queries, not stored as a column
```

**Computed Fields**:
- `remaining_shares` = `shares - sold_shares` (calculated in queries)
- `ad_stage` = `remaining_shares > 0 ? 'receiving_offers' : 'completed'` (calculated in application logic)

#### sellers table (or use users table):
```sql
CREATE TABLE IF NOT EXISTS sellers (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    verified BOOLEAN DEFAULT FALSE,
    avatar VARCHAR(255),
    member_since YEAR
);
```

#### offers table:
```sql
CREATE TABLE offers (
    id INT PRIMARY KEY AUTO_INCREMENT,
    ad_id INT NOT NULL,
    buyer_id INT NOT NULL,
    buyer_name VARCHAR(255),
    buyer_verified BOOLEAN DEFAULT FALSE,
    quantity INT NOT NULL,
    price_per_share DECIMAL(10,2) NOT NULL,
    total DECIMAL(12,2) NOT NULL,
    status ENUM('pending', 'accepted', 'rejected') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY (ad_id) REFERENCES ads(id),
    FOREIGN KEY (buyer_id) REFERENCES users(id)
);
```

### 2. API Endpoints

#### Get Ad Details
```
GET /api/ads/{id}
```

**Response**:
```json
{
    "success": true,
    "ad": {
        "id": 1,
        "order_number": "AD-2024-1001",
        "name": "شركة الرياض للتقنية",
        "type": "sell",
        "asset_type": "company",
        "price_type": "fixed",
        "price": "150",
        "shares": "1,000",
        "sold_shares": "300",
        "remaining_shares": "700",
        "verified": true,
        "ad_status": "active",
        "ad_stage": "receiving_offers",
        "completion_percentage": 30,
        "description": "...",
        "seller": {
            "id": 1,
            "name": "محمد عبدالله الشمري",
            "verified": true,
            "avatar": "/uploads/avatars/1.jpg",
            "member_since": "2022"
        },
        "submitted_offers": [
            {
                "id": 1,
                "buyer_name": "أحمد خالد العتيبي",
                "buyer_verified": true,
                "quantity": "500",
                "price_per_share": "148",
                "total": "74,000",
                "status": "pending",
                "created_at": "2024-01-23 10:30:00"
            }
        ]
    }
}
```

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

**Request**:
```json
{
    "quantity": 500,
    "price_per_share": 148.00,
    "message": "Optional message to seller"
}
```

**Response**:
```json
{
    "success": true,
    "offer_id": 123,
    "message": "تم إرسال العرض بنجاح"
}
```

#### Update Offer Status (Seller only)
```
PATCH /api/offers/{offer_id}/status
```

**Request**:
```json
{
    "status": "accepted" // or "rejected"
}
```

---

## Testing Checklist

- [ ] Order number displays correctly
- [ ] Ad stage badge shows correct status
- [ ] Ad status badge shows correct status
- [ ] Verification badges display properly
- [ ] Price shows correctly (fixed vs negotiable)
- [ ] Quantity labels adapt to asset type (shares/units)
- [ ] Offers count is accurate
- [ ] Submitted offers section displays when offers exist
- [ ] Seller card shows verification status
- [ ] Calculator works with negotiable pricing
- [ ] Submit offer button text is dynamic
- [ ] Modal adapts to buy/sell type

---

## Example Test Data

See `/data/ads.json` for complete examples:
- **AD ID 1**: Sell - Company - Fixed - Verified - Receiving Offers - With 3 offers
- **AD ID 2**: Sell - Company - Negotiable - Verified - Completed - No offers

---

## Notes for Backend Developers

### 1. Shares Management

**sold_shares Logic**:
- When seller accepts an offer, increment `sold_shares` by the offer quantity
- Calculate `remaining_shares = shares - sold_shares`
- When `remaining_shares = 0`, ad_stage becomes "completed"
- Update `ad_status` to "closed" when all shares are sold

**Important**:
- Multiple offers can be accepted until all shares are sold
- Seller can accept partial quantities from different buyers
- Each accepted offer reduces `remaining_shares`

### 2. Order Number Generation
Use format `AD-{YEAR}-{SEQUENTIAL}` (e.g., "AD-2024-1001")

### 3. Offer Notifications
When an offer is submitted, send notification to seller

### 4. Stage Auto-Update
- Calculate `remaining_shares = shares - sold_shares`
- If `remaining_shares > 0` → `ad_stage = 'receiving_offers'`
- If `remaining_shares = 0` → `ad_stage = 'completed'`
- This should be calculated dynamically, not stored

### 5. Status Management
- `active`: Ad is live and receiving offers (remaining_shares > 0)
- `pending`: Ad waiting for verification
- `closed`: All shares sold (remaining_shares = 0) OR manually closed by seller

### 6. Verification
Use existing shareholder registry verification logic

### 7. Offer Total
Calculate on backend to ensure accuracy: `quantity * price_per_share`

### 8. Wallet Balance Check
Before completing deal:
- Check buyer's wallet balance >= total amount
- If insufficient, show error with link to wallet page
- Allow offer editing/deletion before payment

### 9. Multiple Deal Support
- Seller can accept multiple offers (up to total shares)
- Each offer can be for different quantities
- Track sold_shares cumulatively
- Example: 1000 shares total
  - Offer 1: 300 shares accepted → sold_shares = 300
  - Offer 2: 200 shares accepted → sold_shares = 500
  - Offer 3: 500 shares accepted → sold_shares = 1000 → completed

### 10. Time Display
Return timestamps, frontend will format as "منذ X"

### 11. Access Control
- Only ad owner can see all offer details and accept/reject
- Other users see aggregated stats only
- Offer submitter can edit/delete their own offers before acceptance

---

## Deal Completion Workflow

### Step 1: Offer Submission
1. User views ad details
2. Clicks "تقديم عرض"
3. Enters quantity and price per share
4. Submits offer
5. Notification sent to ad creator

### Step 2: Communication
- Users can chat via platform chat system
- WhatsApp integration available
- Both parties can communicate through either method

### Step 3: Deal Acceptance (Ad Creator)
1. Ad creator clicks "إتمام الصفقة" in chat
2. Contract details form displays:
   - Date selection
   - Party 1 (Seller/Buyer - ad creator):
     - Name (auto-filled from profile, editable)
     - Phone (auto-filled from profile, editable)
   - Party 2 (Other party):
     - Name
     - Phone
   - Company details:
     - Company name
     - Commercial registration number
   - Transaction details:
     - Number of shares
     - Price per share
     - Total value
   - Share transfer agreement (checkbox to accept terms)
3. Click "إتمام الصفقة" button
4. Ad summary displayed
5. PDF contract generated
6. Notification sent to offer submitter

### Step 4: Deal Completion (Offer Submitter)
1. Receives notification of accepted offer
2. Clicks "استكمال"
3. Reviews contract details
4. Clicks "إتمام الصفقة"
5. **Wallet balance check**:
   - If sufficient → Process payment
   - If insufficient → Show error message with "الذهاب إلى المحفظة" button
6. Can edit or delete offer before payment

### Step 5: Post-Payment
1. `sold_shares` incremented by deal quantity
2. `remaining_shares` recalculated
3. If all shares sold → `ad_stage` = "completed", `ad_status` = "closed"
4. Both parties receive confirmation
5. Deal added to transaction history

---

## API Endpoints for Deal Workflow

### Accept Offer & Create Contract
```
POST /api/offers/{offer_id}/accept
```

**Request**:
```json
{
    "contract_date": "2024-01-23",
    "party1_name": "محمد أحمد",
    "party1_phone": "+966501234567",
    "party2_name": "أحمد خالد",
    "party2_phone": "+966507654321",
    "company_name": "شركة الرياض للتقنية",
    "commercial_registration": "1234567890",
    "quantity": 300,
    "price_per_share": 150,
    "total": 45000,
    "terms_accepted": true
}
```

**Response**:
```json
{
    "success": true,
    "contract_id": 123,
    "contract_pdf_url": "/contracts/123.pdf",
    "message": "تم قبول العرض وإنشاء العقد"
}
```

### Complete Deal (Buyer Payment)
```
POST /api/contracts/{contract_id}/complete
```

**Response**:
```json
{
    "success": true/false,
    "wallet_balance": 10000,
    "required_amount": 45000,
    "insufficient_balance": true/false,
    "message": "..."
}
```

### Edit Offer (Before Payment)
```
PATCH /api/offers/{offer_id}
```

**Request**:
```json
{
    "quantity": 400,
    "price_per_share": 145
}
```

### Delete Offer (Before Payment)
```
DELETE /api/offers/{offer_id}
```
