# Political Groups Management System - Morocco Edition
## Technical Specification (DRAFT v1.0)

---

## 1. Overview

### 1.1 Business Model
Political organizations in Morocco can purchase **Group Licenses** (BuddyBoss groups) to:
- Recruit members via **affiliate links** with commission tracking
- Gamify engagement with **points, badges, and leaderboards**
- Manage hierarchies (National → Regional → Local chapters)
- Track campaign metrics and member activity
- Incentivize activism through rewards

### 1.2 Revenue Streams
```
Group Purchase: 5,000 MAD/year (National)
               2,000 MAD/year (Regional)
               500 MAD/year (Local)

Affiliate Commissions: 10% of group sales
Member Upgrades: Premium features (500 MAD/member/year)
Campaign Boosts: Featured placement (1,000 MAD/month)
```

---

## 2. Architecture Overview

### 2.1 Core Components
```
┌─────────────────────────────────────────────────┐
│   WordPress + BuddyBoss + WooCommerce           │
│   ↓                                              │
│   Group Licensing System (WooCommerce Products)  │
│   ↓                                              │
│   Affiliate System (AffiliateWP / Custom)        │
│   ↓                                              │
│   Gamification Engine (GamiPress / Custom)       │
│   ↓                                              │
│   GHL CRM Integration (Campaign Data Sync)       │
└─────────────────────────────────────────────────┘
```

### 2.2 User Roles
```
Super Admin (Platform Owner)
  └── Party Admin (National Level)
      └── Regional Coordinator
          └── Local Chapter Leader
              └── Active Member
                  └── Supporter (Guest)
```

---

## 3. Group Licensing System

### 3.1 WooCommerce Products
Create 3 product types as **Subscriptions**:

| Product | Price | Features |
|---------|-------|----------|
| **National Group License** | 5,000 MAD/year | Unlimited members, 10 sub-groups, Full analytics, GHL sub-account |
| **Regional Group License** | 2,000 MAD/year | 500 members max, 5 sub-groups, Basic analytics |
| **Local Group License** | 500 MAD/year | 100 members max, No sub-groups, View-only analytics |

### 3.2 Purchase Flow
```
1. Party Admin buys "National Group License" product
2. Order completed → Webhook triggers group creation
3. Auto-create BuddyBoss group with buyer as organizer
4. Assign GHL sub-account to group
5. Email welcome package with affiliate link
```

### 3.3 Database Schema

#### `wp_ghl_political_groups` (Custom Table)
```sql
CREATE TABLE wp_ghl_political_groups (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    group_id BIGINT UNSIGNED NOT NULL, -- BuddyBoss group ID
    license_type ENUM('national', 'regional', 'local') NOT NULL,
    order_id BIGINT UNSIGNED NOT NULL, -- WooCommerce order
    subscription_id BIGINT UNSIGNED, -- WooCommerce subscription
    parent_group_id BIGINT UNSIGNED NULL, -- Hierarchical structure
    ghl_location_id VARCHAR(255),
    affiliate_link VARCHAR(255) UNIQUE,
    total_recruited INT DEFAULT 0,
    total_commission_earned DECIMAL(10,2) DEFAULT 0,
    status ENUM('active', 'suspended', 'expired') DEFAULT 'active',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    expires_at DATETIME,
    INDEX idx_group_id (group_id),
    INDEX idx_parent_group (parent_group_id),
    INDEX idx_status (status)
);
```

#### Group Meta Keys (BuddyBoss)
```php
_ghl_political_license_type    // string: national|regional|local
_ghl_political_parent_group    // int: Parent group ID (for hierarchy)
_ghl_political_member_limit    // int: Max members allowed
_ghl_political_subgroup_limit  // int: Max sub-groups allowed
_ghl_political_affiliate_code  // string: Unique referral code
_ghl_political_total_points    // int: Group-wide gamification score
```

---

## 4. Affiliate System

### 4.1 Affiliate Link Structure
```
https://yoursite.com/?ref=PTY-CASA-2025
                            ↑
                   Unique per-group code
```

### 4.2 Attribution Logic
```php
// When user clicks affiliate link
1. Store referrer code in cookie (30-day expiry)
2. On group purchase, check cookie
3. Credit commission to referrer group
4. Record in wp_ghl_affiliate_commissions table
```

### 4.3 Commission Table

#### `wp_ghl_affiliate_commissions`
```sql
CREATE TABLE wp_ghl_affiliate_commissions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    referrer_group_id BIGINT UNSIGNED NOT NULL, -- Who referred
    referred_group_id BIGINT UNSIGNED NOT NULL, -- Who purchased
    order_id BIGINT UNSIGNED NOT NULL,
    commission_amount DECIMAL(10,2) NOT NULL,
    commission_rate DECIMAL(5,2) NOT NULL, -- e.g., 10.00 for 10%
    status ENUM('pending', 'approved', 'paid', 'rejected') DEFAULT 'pending',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    paid_at DATETIME NULL,
    INDEX idx_referrer (referrer_group_id),
    INDEX idx_status (status)
);
```

### 4.4 Commission Payout
```php
// In group dashboard
function render_affiliate_earnings() {
    $group_id = bp_get_current_group_id();
    $total_earned = get_group_total_commissions($group_id);
    $pending = get_group_pending_commissions($group_id);
    
    echo "Total Earned: {$total_earned} MAD";
    echo "Pending: {$pending} MAD";
    echo '<button>Request Payout</button>'; // Email admin
}
```

---

## 5. Gamification System

### 5.1 Point System

#### Point Rules
| Action | Points | Cooldown |
|--------|--------|----------|
| Invite new member (+join) | 100 | None |
| Daily login | 10 | 24h |
| Post in group | 20 | 1h |
| Comment on post | 5 | None |
| Share event | 30 | Per event |
| Attend event (check-in) | 50 | Per event |
| Recruit affiliate sale | 500 | None |
| Complete campaign task | 100 | Per task |

#### `wp_ghl_gamification_points` (Custom Table)
```sql
CREATE TABLE wp_ghl_gamification_points (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    group_id BIGINT UNSIGNED NOT NULL,
    points INT NOT NULL,
    action_type VARCHAR(50) NOT NULL, -- 'invite', 'login', 'post', etc
    reference_id BIGINT UNSIGNED NULL, -- e.g., post_id, event_id
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_user_group (user_id, group_id),
    INDEX idx_action (action_type)
);
```

### 5.2 Badge System

#### Predefined Badges
```php
[
    'recruiter_bronze' => [
        'label' => 'Recruiter Bronze',
        'condition' => 'invited_users >= 10',
        'icon' => 'badge-bronze.svg',
    ],
    'recruiter_silver' => [
        'label' => 'Recruiter Silver',
        'condition' => 'invited_users >= 50',
        'icon' => 'badge-silver.svg',
    ],
    'activist_legend' => [
        'label' => 'Activist Legend',
        'condition' => 'total_points >= 10000 AND events_attended >= 20',
        'icon' => 'badge-legend.svg',
    ],
]
```

#### `wp_ghl_gamification_badges` (Custom Table)
```sql
CREATE TABLE wp_ghl_gamification_badges (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    group_id BIGINT UNSIGNED NOT NULL,
    badge_key VARCHAR(50) NOT NULL, -- 'recruiter_bronze', etc
    earned_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY unique_badge (user_id, group_id, badge_key)
);
```

### 5.3 Leaderboards

#### Group Leaderboard (Custom Tab)
```php
// Display top 10 members by points
SELECT 
    u.ID, u.display_name, 
    SUM(p.points) as total_points,
    COUNT(DISTINCT b.badge_key) as badge_count
FROM wp_users u
JOIN wp_ghl_gamification_points p ON u.ID = p.user_id
LEFT JOIN wp_ghl_gamification_badges b ON u.ID = b.user_id AND b.group_id = p.group_id
WHERE p.group_id = %d
GROUP BY u.ID
ORDER BY total_points DESC
LIMIT 10
```

#### National Leaderboard (Cross-Group)
```php
// Top groups by total member points
SELECT 
    g.group_name,
    SUM(p.points) as group_total_points,
    COUNT(DISTINCT p.user_id) as active_members
FROM wp_bp_groups g
JOIN wp_ghl_gamification_points p ON g.id = p.group_id
GROUP BY g.id
ORDER BY group_total_points DESC
LIMIT 20
```

---

## 6. Invitation & Recruitment System

### 6.1 Invite Flow
```
1. Member clicks "Invite Friends" in group
2. System generates unique invite link:
   https://yoursite.com/join/PTY-CASA-2025?inviter=user123

3. Friend clicks link → Pre-filled registration form
4. Friend completes registration → Auto-joins group
5. Inviter earns 100 points + badge progress
```

### 6.2 Bulk Invite via CSV
```php
// Group admin uploads CSV with emails
function process_bulk_invites($group_id, $csv_file) {
    $emails = parse_csv($csv_file);
    
    foreach ($emails as $email) {
        // Send personalized email with invite link
        $invite_link = generate_invite_link($group_id, get_current_user_id());
        wp_mail($email, 'Join Our Political Movement', "Click here: {$invite_link}");
    }
    
    // Track pending invites in transient
    set_transient("pending_invites_{$group_id}", $emails, WEEK_IN_SECONDS);
}
```

---

## 7. Campaign Management

### 7.1 Campaign Custom Post Type
```php
register_post_type('political_campaign', [
    'label' => 'Campaigns',
    'public' => false,
    'show_ui' => true,
    'supports' => ['title', 'editor', 'thumbnail'],
    'taxonomies' => ['campaign_type'], // 'election', 'awareness', 'fundraising'
]);
```

### 7.2 Campaign Tasks (Checklist)
```php
// Store as post meta
_campaign_tasks = [
    [
        'id' => 1,
        'title' => 'Share campaign poster on social media',
        'points' => 50,
        'proof_required' => true, // Upload screenshot
    ],
    [
        'id' => 2,
        'title' => 'Attend town hall meeting',
        'points' => 100,
        'proof_required' => true, // GPS check-in
    ],
]
```

### 7.3 Task Completion Tracking
```sql
CREATE TABLE wp_ghl_campaign_completions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    group_id BIGINT UNSIGNED NOT NULL,
    campaign_id BIGINT UNSIGNED NOT NULL,
    task_id INT NOT NULL,
    proof_url VARCHAR(255) NULL, -- Screenshot/photo URL
    status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
    completed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_user_campaign (user_id, campaign_id)
);
```

---

## 8. Group Hierarchy & Permissions

### 8.1 Hierarchical Structure
```
National Party HQ (Parent: NULL)
  ├── Casablanca Region (Parent: National)
  │   ├── Anfa Chapter (Parent: Casablanca)
  │   └── Hay Hassani Chapter (Parent: Casablanca)
  └── Rabat Region (Parent: National)
      └── Agdal Chapter (Parent: Rabat)
```

### 8.2 Permission Inheritance
```php
function can_user_manage_group($user_id, $group_id) {
    // Check direct membership
    if (groups_is_user_admin($user_id, $group_id)) {
        return true;
    }
    
    // Check parent group permissions (cascade down)
    $parent_id = groups_get_groupmeta($group_id, '_ghl_political_parent_group', true);
    if ($parent_id && groups_is_user_admin($user_id, $parent_id)) {
        return true; // National admin can manage regional/local
    }
    
    return false;
}
```

---

## 9. Custom Group Tabs

### 9.1 Affiliate Dashboard Tab
```php
bp_core_new_subnav_item([
    'name' => 'Affiliate Dashboard',
    'slug' => 'affiliate',
    'parent_url' => bp_get_group_permalink(groups_get_current_group()),
    'parent_slug' => bp_get_current_group_slug(),
    'screen_function' => 'render_affiliate_dashboard',
    'position' => 50,
]);

function render_affiliate_dashboard() {
    // Show:
    // - Unique affiliate link
    // - Total recruits
    // - Commission earned
    // - Pending payouts
    // - Top recruiters leaderboard
}
```

### 9.2 Leaderboard Tab
```php
bp_core_new_subnav_item([
    'name' => 'Leaderboard',
    'slug' => 'leaderboard',
    'screen_function' => 'render_leaderboard',
    'position' => 51,
]);

function render_leaderboard() {
    // Show:
    // - Top 10 members by points
    // - Recent badge earners
    // - Group rank (national comparison)
    // - Weekly/monthly top performers
}
```

### 9.3 Campaigns Tab
```php
bp_core_new_subnav_item([
    'name' => 'Campaigns',
    'slug' => 'campaigns',
    'screen_function' => 'render_campaigns',
    'position' => 52,
]);

function render_campaigns() {
    // Show:
    // - Active campaigns
    // - Task checklist with progress
    // - Submit proof of completion
    // - Campaign analytics (reach, engagement)
}
```

---

## 10. GHL CRM Integration

### 10.1 Sync Political Group Data
```php
// When user joins group via affiliate link
add_action('groups_join_group', function($group_id, $user_id) {
    $affiliate_code = groups_get_groupmeta($group_id, '_ghl_political_affiliate_code', true);
    $referrer_user = get_referrer_from_cookie();
    
    // Queue sync to GHL
    $queue = \GHL_CRM\Sync\QueueManager::get_instance();
    $queue->add_to_queue('user', $user_id, 'user_register', [
        'email' => $user->user_email,
        'firstName' => $user->first_name,
        'tags' => [
            'political-member',
            "group-{$group_id}",
            "referred-by-{$referrer_user}",
        ],
        'customField.affiliate_source' => $affiliate_code,
        '_group_id' => $group_id, // For context manager
    ]);
}, 10, 2);
```

### 10.2 Campaign Metrics to GHL Custom Fields
```php
// Update contact with gamification stats
$client = \GHL_CRM\API\Client\Client::get_instance();
$client->put("contacts/{$contact_id}", [
    'customField.total_points' => get_user_total_points($user_id),
    'customField.badges_earned' => count(get_user_badges($user_id)),
    'customField.recruits_count' => get_user_recruits_count($user_id),
    'customField.campaigns_completed' => get_user_campaigns_completed($user_id),
]);
```

---

## 11. Admin Dashboard (Platform Owner)

### 11.1 Analytics Overview
```php
// Display in WordPress Admin → Political Groups
- Total active groups (National/Regional/Local breakdown)
- Total members across all groups
- Total affiliate sales this month
- Pending commission payouts
- Top performing groups (by points/recruits)
- Revenue from group licenses
```

### 11.2 Commission Approval Queue
```php
// Approve/reject affiliate commissions
SELECT 
    r.group_name as referrer,
    g.group_name as referred,
    c.commission_amount,
    c.status
FROM wp_ghl_affiliate_commissions c
JOIN wp_ghl_political_groups r ON c.referrer_group_id = r.group_id
JOIN wp_ghl_political_groups g ON c.referred_group_id = g.group_id
WHERE c.status = 'pending'
ORDER BY c.created_at DESC
```

---

## 12. Moroccan Localization

### 12.1 Currency
- All prices in **MAD (Moroccan Dirham)**
- WooCommerce currency: `MAD`
- Payment gateways: CMI, Maroc Telecommerce, PayPal

### 12.2 Language
- Primary: **Arabic (ar_MA)**
- Secondary: **French (fr_FR)**
- Use WPML or Polylang for translations

### 12.3 Cultural Considerations
- Right-to-left (RTL) support for Arabic
- Respect Moroccan political regulations (transparency, reporting)
- Privacy compliance (CNDP guidelines)

---

## 13. Implementation Phases

### Phase 1: Licensing & Purchase (Week 1-2)
- [ ] Create WooCommerce subscription products
- [ ] Auto-create groups on purchase
- [ ] Link orders to `wp_ghl_political_groups` table
- [ ] Email templates (welcome, renewal reminders)

### Phase 2: Affiliate System (Week 2-3)
- [ ] Generate unique affiliate codes per group
- [ ] Cookie-based attribution
- [ ] Commission calculation on purchases
- [ ] Affiliate dashboard tab in groups

### Phase 3: Gamification Engine (Week 3-4)
- [ ] Point tracking system
- [ ] Badge definitions and auto-award
- [ ] Leaderboard queries and UI
- [ ] Gamification tab in groups

### Phase 4: Campaign Management (Week 4-5)
- [ ] Campaign CPT and task system
- [ ] Task completion tracking
- [ ] Proof submission (uploads)
- [ ] Campaign analytics

### Phase 5: GHL Integration (Week 5-6)
- [ ] Sync group membership to GHL tags
- [ ] Sync gamification stats to custom fields
- [ ] Use existing GHL sub-account system
- [ ] Webhook for campaign events

### Phase 6: Hierarchy & Permissions (Week 6)
- [ ] Parent-child group relationships
- [ ] Permission cascade logic
- [ ] National → Regional → Local admin UI

### Phase 7: Testing & Launch (Week 7-8)
- [ ] Multi-group scenarios
- [ ] Payment flow testing
- [ ] Security audit (affiliate fraud prevention)
- [ ] Performance optimization
- [ ] User documentation (Arabic/French)

---

## 14. Security & Anti-Fraud

### 14.1 Affiliate Fraud Prevention
```php
// Detect self-referral
if ($referrer_group_id === $purchaser_group_id) {
    reject_commission('Self-referral not allowed');
}

// Detect click farms (same IP, multiple groups)
if (count_purchases_from_ip($ip) > 5) {
    flag_for_review('Suspicious activity');
}

// Cookie tampering detection
if (!verify_referral_signature($cookie)) {
    reject_commission('Invalid referral signature');
}
```

### 14.2 Point Manipulation Prevention
```php
// Rate limit point-earning actions
if (has_user_earned_points($user_id, 'post', $last_hour = true)) {
    throw new Exception('Cooldown active');
}

// Admin audit log
log_point_change($user_id, $points, $action, $admin_id);
```

---

## 15. Revenue Projections (Year 1)

```
Assumptions:
- 20 National groups × 5,000 MAD = 100,000 MAD
- 50 Regional groups × 2,000 MAD = 100,000 MAD
- 100 Local groups × 500 MAD = 50,000 MAD
- Affiliate sales: 10% × 250,000 MAD = 25,000 MAD (commission)

Total Annual Revenue: ~275,000 MAD (~$27,500 USD)
```

---

## 16. Technical Stack Summary

| Component | Technology |
|-----------|-----------|
| **CMS** | WordPress 6.4+ |
| **Community** | BuddyBoss Platform |
| **E-Commerce** | WooCommerce + Subscriptions |
| **Payments** | CMI / Maroc Telecommerce |
| **CRM** | GoHighLevel (existing integration) |
| **Gamification** | Custom tables + GamiPress (optional) |
| **Affiliate** | Custom (or AffiliateWP if budget allows) |
| **Translations** | WPML / Polylang (Arabic + French) |

---

## 17. Open Questions (To Finalize)

1. **Payout Method?**
   - Bank transfer, mobile money (Orange Money, Maroc Telecommerce)?
   - Minimum payout threshold?

2. **Gamification Rewards?**
   - Virtual-only or physical prizes (t-shirts, event tickets)?
   - Redemption system (points → coupons)?

3. **Campaign Approval Workflow?**
   - Who creates campaigns? National admins only?
   - Review process for task submissions?

4. **Data Privacy?**
   - How long to retain affiliate tracking data?
   - GDPR/CNDP compliance for member data?

5. **Expansion Beyond Morocco?**
   - Multi-currency support?
   - Regional regulations (e.g., Algeria, Tunisia)?

---

**Estimated Total Dev Time:** 7-8 weeks (1 developer full-time)

**Maintenance Cost:** ~10 hours/month (bug fixes, feature tweaks)

---

*This is a living document. Update as requirements evolve.*