# FINEART Referral Program - Installation Guide

## Version 1.0

This guide will help you integrate the FINEART Referral Program into your existing system.

---

## 📋 What's Included

The referral program adds the following features:

1. **Artist Referral Links** - Each artist gets a unique referral link (e.g., `?ref=artistname`)
2. **Embedded Gallery Tracking** - Automatic tracking of sales from embedded galleries
3. **1.5x Commission Bonus** - Artists earn 50% more when they bring the sale
4. **Dashboard Interface** - Beautiful dashboard for artists to manage their referral program
5. **Statistics Tracking** - Track sales, bonuses, and conversion rates

---

## 🚀 Installation Steps

### Step 1: Plugin Files

The following files have been added to your plugin:

```
fineart-plugin/
├── includes/
│   └── class-fineart-referral-system.php (NEW)
├── templates/vendor-dashboard/
│   └── referral-program.php (NEW)
├── css/
│   └── referral-program.css (NEW)
└── includes/
    └── class-fineart-loader.php (UPDATED)
```

### Step 2: Add Commission Filter to functions.php

**IMPORTANT:** You need to add this code to your theme's `functions.php` file or wherever you currently have the commission calculation code.

```php
<?php
/**
 * FINEART Commission Calculation with Referral Bonus
 * 
 * This replaces your existing commission filter
 */

add_filter('vendor_commission_amount', 'fineart_custom_commission_by_size', 99, 6);
function fineart_custom_commission_by_size($amount, $product_id, $variation_id, $item, $order_id, $item_id) {
    // Base commission rates by size
    $size_to_commission = array(
        'SMALL'  => 30,
        'MEDIUM' => 60,
        'LARGE'  => 120,
        'LUXE'   => 240,
    );
    
    $commission = 0;
    
    // Get size from item meta
    foreach ($item->get_all_formatted_meta_data() as $meta) {
        $value = trim(strip_tags(wp_kses_post($meta->display_value)));
        if (array_key_exists($value, $size_to_commission)) {
            $commission = $size_to_commission[$value];
            break;
        }
    }
    
    // Default to original amount if no matching size found
    if ($commission == 0) {
        $commission = $amount;
    }
    
    // Apply referral bonus (1.5x) - handled by the referral system
    $commission = apply_filters('fineart_referral_commission_bonus', $commission, $product_id, $order_id, $item);
    
    return $commission;
}
```

### Step 3: Add Dashboard Navigation Menu Item

Add the referral program to your vendor dashboard menu. This depends on your dashboard system, but typically you'd add:

**For WC Vendors (MVX):**

The referral system automatically registers the endpoint. If it doesn't appear in your menu, add this to your dashboard navigation:

```php
// Add to your dashboard menu array
array(
    'label' => __('Referral Program', 'fineart'),
    'url' => home_url('/vendor-dashboard/referral-program'),
    'icon' => 'dashicons-awards', // or any icon you prefer
)
```

### Step 4: Flush Rewrite Rules

After installation, you need to flush rewrite rules:

1. Go to WordPress Admin
2. Navigate to **Settings > Permalinks**
3. Click **Save Changes** (you don't need to change anything)

This will register the new `referral-program` endpoint.

---

## 📊 How It Works

### For Artists

1. **Get Referral Link**
   - Artists visit `/vendor-dashboard/referral-program`
   - Copy their unique referral link: `https://fineart.gallery/?ref=artistname`

2. **Register Website Domain**
   - Artists enter their website URL (e.g., `https://johnartist.com`)
   - System automatically tracks sales from their embedded gallery

3. **Share & Earn**
   - Share referral link on social media, email, etc.
   - When someone purchases within 90 days → 1.5x commission

### Commission Calculation Examples

**Regular Sale (no referral):**
```
LARGE print = €120 base commission
Artist earns: €120
```

**With Referral (artist brought the sale):**
```
LARGE print = €120 base commission × 1.5
Artist earns: €180 (+€60 bonus)
```

**Commission Breakdown by Size:**
| Size   | Base | With Referral |
|--------|------|---------------|
| SMALL  | €30  | €45           |
| MEDIUM | €60  | €90           |
| LARGE  | €120 | €180          |
| LUXE   | €240 | €360          |

---

## 🔗 Embed Gallery Integration

The referral system automatically integrates with your existing embed gallery feature:

### How Embed Tracking Works

1. Artist registers their website domain (e.g., `johnartist.com`)
2. Artist embeds their FINEART gallery on their website
3. When a visitor clicks from `johnartist.com` to FINEART:
   - System detects the external referrer
   - Matches domain to artist
   - Tracks as `embedded_gallery` source
4. If visitor purchases within 90 days → 1.5x commission

### Enhanced Embed Code (Optional)

To make embed tracking even more reliable, you can modify your embed code generator to include the referral parameter:

```php
// In fineart_get_embed_code() function
function fineart_get_embed_code($artist_id) {
    if (empty($artist_id)) return '';
    
    $artist = get_userdata($artist_id);
    $ref_param = $artist ? $artist->user_login : $artist_id;
    
    $version = time();
    $container_id = 'fineart-gallery-placeholder';

    return sprintf(
        '<div id="%1$s" data-artist="%2$d"></div><script src="https://fineart.gallery/widgets/fineart-embed.js?ref=%4$s&artist=%2$d&v=%3$s" async></script>',
        $container_id,
        esc_attr($artist_id),
        esc_attr($version),
        esc_attr($ref_param) // Add referral parameter
    );
}
```

---

## 📈 Statistics & Analytics

The dashboard shows artists:

- **Total Sales Driven** - Number of sales from their referrals
- **Extra Earned** - Total bonus commission earned
- **Via Embed** - Sales from embedded gallery
- **Via Link** - Sales from direct referral links

These stats are calculated from order meta data and updated in real-time.

---

## 🎯 Key Features

### 1. Multiple Tracking Sources
- Direct referral links (`?ref=username`)
- Embedded galleries (domain detection)
- Social media traffic
- Email campaigns

### 2. Long Attribution Window
- 90-day cookie tracking
- First-click attribution (prevents hijacking)
- Secure session backup

### 3. Self-Purchase Support
- Artists can buy their own work
- Still earn 1.5x commission
- Encourages self-promotion

### 4. Order Notes
Every referral sale gets a note like:
```
✨ Artist-driven sale bonus: Commission increased by 50% via 🔗 Referral Link
Base: €120.00 → Enhanced: €180.00
```

---

## 🔧 Customization

### Change Commission Multiplier

To change from 1.5x to a different multiplier, edit this line in `class-fineart-referral-system.php`:

```php
// Line ~225
$amount = $amount * 1.5;  // Change 1.5 to desired multiplier
```

### Change Tracking Duration

To change from 90 days, edit this line:

```php
// Line ~117
time() + (90 * DAY_IN_SECONDS),  // Change 90 to desired days
```

### Add More Statistics

Add to the `get_artist_stats()` method in `class-fineart-referral-system.php`:

```php
$stats['total_revenue'] = 0;
// Calculate total revenue from referred orders
foreach ($orders as $order) {
    $stats['total_revenue'] += $order->get_total();
}
```

---

## 🐛 Troubleshooting

### Dashboard page returns 404
- Go to Settings > Permalinks
- Click Save Changes
- Flush browser cache

### Referral not tracking
- Check if cookies are enabled
- Verify JavaScript is not blocked
- Check for cookie consent plugins (they might block tracking)

### Commission not applying
- Verify the commission filter is in functions.php
- Check order notes for error messages
- Ensure product has correct vendor/author

### Embed tracking not working
- Verify domain is registered correctly (without www.)
- Check HTTP_REFERER is being sent
- Test from external domain (won't work on same domain)

---

## 🔐 Security Notes

The referral system uses:
- Base64 encoding for cookie data
- Nonce verification for forms
- User role validation
- Secure cookies (httponly flag)
- Input sanitization

However, it's designed for trust-based partnerships. If you need stricter fraud prevention, additional measures can be added.

---

## 📝 Testing Checklist

After installation, test these scenarios:

- [ ] Artist can access `/vendor-dashboard/referral-program`
- [ ] Referral link copies correctly
- [ ] Clicking referral link sets cookie (check DevTools)
- [ ] Domain can be saved and updated
- [ ] Test purchase with referral link shows 1.5x commission
- [ ] Order note appears with referral details
- [ ] Statistics update after completed order
- [ ] Embed gallery tracking works from external domain

---

## 🆘 Support

For issues or questions:

1. Check this guide's Troubleshooting section
2. Verify all installation steps completed
3. Check browser console for JavaScript errors
4. Review WordPress error logs
5. Test in incognito mode to rule out cookie issues

---

## 🎉 Success!

Once installed, artists will see the "Referral Program" option in their dashboard and can immediately start sharing their referral links and earning bonuses!

The system works automatically - no ongoing maintenance required. Just let your artists know about the new feature and watch them drive more sales!

---

## Version History

**v1.0** (Current)
- Initial release
- Referral link tracking
- Embed gallery tracking
- 1.5x commission bonus
- Dashboard interface
- Statistics tracking
