# Advertisement System - Testing & Examples

## Quick Test Commands

### Run Setup Script

```powershell
.\setup-advertisements.ps1
```

### Manual Migration

```bash
php artisan migrate --path=database/migrations/2025_12_12_000001_create_audio_advertisements_table.php
```

### Create Upload Directory

```powershell
New-Item -ItemType Directory -Force -Path "public\uploads\advertisements"
```

---

## API Testing

### Test Active Ads Endpoint

```bash
curl http://localhost:8000/api/advertisements/active
```

**Expected Response**:

```json
{
  "status": 1,
  "data": [
    {
      "id": 1,
      "title": "Summer Sale 2025",
      "audio_url": "http://localhost:8000/uploads/advertisements/1734000000_ad.mp3",
      "duration": 30,
      "play_frequency_type": "song_based",
      "play_frequency_value": 3,
      "is_skippable": false
    }
  ]
}
```

---

## Browser Console Testing

### Check Advertisement Manager Status

```javascript
// View loaded advertisements
console.log(window.advertisementManager.activeAds);

// Check song play count
console.log("Songs played:", window.advertisementManager.songPlayCount);

// Check if ad is playing
console.log("Playing ad:", window.advertisementManager.isPlayingAd);

// Manually trigger ad check
window.advertisementManager.checkIfAdShouldPlay();
```

### Force Ad Play (Testing)

```javascript
// Get first active ad
const testAd = window.advertisementManager.activeAds[0];

// Play it immediately
window.advertisementManager.playAdvertisement(testAd);
```

### Reset Song Counter

```javascript
window.advertisementManager.songPlayCount = 0;
console.log("Counter reset");
```

---

## Sample Advertisement Data

### Example 1: Non-Skippable Ad (Every 3 Songs)

```php
[
    'title' => 'Brand Promotion - Holiday Sale',
    'audio_file' => '1734000000_holiday_sale.mp3',
    'duration' => 30,
    'play_frequency_type' => 'song_based',
    'play_frequency_value' => 3,
    'is_skippable' => false,
    'status' => true,
    'priority' => 10
]
```

### Example 2: Skippable Ad (Every 5 Songs)

```php
[
    'title' => 'Sponsor Message',
    'audio_file' => '1734000001_sponsor.mp3',
    'duration' => 15,
    'play_frequency_type' => 'song_based',
    'play_frequency_value' => 5,
    'is_skippable' => true,
    'status' => true,
    'priority' => 5
]
```

### Example 3: High Priority Ad (Every 2 Songs)

```php
[
    'title' => 'Urgent Announcement',
    'audio_file' => '1734000002_announcement.mp3',
    'duration' => 20,
    'play_frequency_type' => 'song_based',
    'play_frequency_value' => 2,
    'is_skippable' => false,
    'status' => true,
    'priority' => 100
]
```

---

## Test Scenarios

### Scenario 1: Basic Ad Play

1. Upload ad with frequency: 3 songs
2. Play 3 songs on homepage
3. **Expected**: Ad plays after 3rd song ends
4. **Verify**: Controls disabled, banner shows, volume works
5. **Expected**: After ad ends, 4th song resumes

### Scenario 2: Multiple Ads (Priority)

1. Upload 2 ads:
   - Ad A: Priority 10, Frequency 2
   - Ad B: Priority 5, Frequency 2
2. Play 2 songs
3. **Expected**: Ad A plays (higher priority)
4. Play 2 more songs
5. **Expected**: Ad B plays

### Scenario 3: Skip Test

1. Upload ad with `is_skippable = true`
2. Play required songs to trigger ad
3. **Expected**: "Skip available after 5 seconds" banner
4. **Note**: Skip functionality requires additional implementation

### Scenario 4: Disabled Ad

1. Upload ad, set status = inactive
2. Play songs
3. **Expected**: Ad never plays
4. Toggle status to active in admin
5. **Expected**: Ad now plays at frequency

---

## Database Queries (Testing)

### Get All Active Ads

```sql
SELECT * FROM audio_advertisements WHERE status = 1 ORDER BY priority DESC;
```

### Get Song-Based Ads

```sql
SELECT * FROM audio_advertisements
WHERE status = 1 AND play_frequency_type = 'song_based'
ORDER BY priority DESC;
```

### Count Active Ads

```sql
SELECT COUNT(*) as total_active FROM audio_advertisements WHERE status = 1;
```

### Update Ad Priority

```sql
UPDATE audio_advertisements SET priority = 100 WHERE id = 1;
```

---

## Frontend Integration Check

### Verify Script Loaded

Open browser console:

```javascript
// Should return object, not undefined
typeof window.advertisementManager;
// Output: "object"
```

### Verify Player Exists

```javascript
// Should return video.js player instance
typeof gmoplayer;
// Output: "object"
```

### Check Event Bindings

```javascript
// List all event listeners on player
videojs.getPlayer("audio-player").off(); // Shows registered events
```

---

## Common Issues & Solutions

### Issue: Ads Not Playing

**Debug**:

```javascript
// 1. Check if ads loaded
console.log("Ads loaded:", window.advertisementManager.activeAds.length);

// 2. Check song counter
console.log("Songs played:", window.advertisementManager.songPlayCount);

// 3. Check frequency match
let songCount = window.advertisementManager.songPlayCount;
let frequency = window.advertisementManager.activeAds[0].play_frequency_value;
console.log("Should play?", songCount % frequency === 0);
```

**Solutions**:

- Ensure API endpoint returns data
- Check ad status is active
- Verify frequency value is set
- Clear browser cache

### Issue: Controls Not Disabling

**Debug**:

```javascript
// Check if ad mode is active
console.log("Playing ad:", window.advertisementManager.isPlayingAd);

// Check disabled class
$(".jp-previous").hasClass("disabled"); // Should be true
```

**Solutions**:

- Inspect element to see if `.disabled` class is applied
- Check CSS is loaded (F12 → Elements → Computed styles)
- Try manually: `$('.jp-previous').addClass('disabled')`

### Issue: Song Doesn't Resume

**Debug**:

```javascript
// Check saved state
console.log("Paused index:", window.advertisementManager.pausedSongIndex);
console.log("Paused time:", window.advertisementManager.pausedSongTime);

// Check current playlist
console.log("Playlist:", gmoplayer.playlist());
```

**Solutions**:

- Verify `pausedSongIndex` is valid number
- Check playlist array hasn't been modified
- Ensure `adEnded()` method is called

---

## Performance Testing

### Load Test

```javascript
// Simulate 100 song plays
for (let i = 0; i < 100; i++) {
  window.advertisementManager.songPlayCount++;
  window.advertisementManager.checkIfAdShouldPlay();
}
```

### Memory Leak Check

```javascript
// Monitor memory usage
console.memory.usedJSHeapSize / 1048576 + " MB";

// Play multiple ads
// Re-check memory
console.memory.usedJSHeapSize / 1048576 + " MB";
```

---

## File Upload Testing

### Valid Files

- `test.mp3` (30 seconds, 1MB)
- `ad_short.mp3` (15 seconds, 500KB)
- `ad_long.wav` (60 seconds, 5MB)

### Invalid Files (Should Reject)

- `video.mp4` (wrong format)
- `large.mp3` (15MB, over limit)
- `corrupt.mp3` (damaged file)

### Upload via cURL

```bash
curl -X POST http://localhost:8000/admin/advertisements/store \
  -F "title=Test Ad" \
  -F "audio_file=@test.mp3" \
  -F "duration=30" \
  -F "play_frequency_type=song_based" \
  -F "play_frequency_value=3" \
  -F "is_skippable=0" \
  -F "status=1" \
  -F "priority=10" \
  -F "_token=YOUR_CSRF_TOKEN"
```

---

## Admin Panel Navigation

1. Login to admin: `/login`
2. Navigate to: `/admin/advertisements`
3. Click "Add Advertisement"
4. Fill form and upload MP3
5. Submit
6. View in data table
7. Toggle status switch
8. Edit/Delete as needed

---

## Production Deployment Checklist

- [ ] Run migration on production DB
- [ ] Create uploads directory with correct permissions
- [ ] Upload test advertisement
- [ ] Test API endpoint returns data
- [ ] Test frontend player integration
- [ ] Verify controls disable properly
- [ ] Monitor server logs for errors
- [ ] Set up backup for uploaded audio files
- [ ] Configure CDN for audio delivery (optional)
- [ ] Add admin auth middleware to routes

---

**End of Testing Guide**
