# Advertisement System - Debug & Testing Guide

## ✅ What Was Fixed

### **Problem Identified**

The `audio-player-videojs.js` file was automatically calling `gmoplayer.playlist.next()` when a song ended, moving to the next track **BEFORE** the advertisement manager could check if an ad should play.

### **Solution Implemented**

1. **Modified `audio-player-videojs.js`** (Line ~95-109)

   - Added check for advertisements before auto-advancing
   - Calls `advertisementManager.onSongEnded()` instead of direct `playlist.next()`
   - Detects when ad ends and lets advertisement manager handle cleanup

2. **Modified `advertisement-manager.js`**
   - Changed event binding strategy - no longer listens to `ended` event directly
   - Added `onSongEnded()` method called by audio-player-videojs.js
   - Improved logging with detailed console messages
   - Fixed playlist advancement when no ad should play
   - Added 100ms delay before playing ad to ensure proper loading

---

## 🧪 Testing Instructions

### **Step 1: Clear Browser Cache**

```
Press: Ctrl + Shift + Delete
Select: Cached images and files
Click: Clear data
```

### **Step 2: Open Developer Console**

```
Press F12
Click "Console" tab
```

### **Step 3: Load the Page**

You should see:

```
Document ready - Initializing advertisement manager...
Attempt 1/10: Waiting for gmoplayer...
✓ Advertisement Manager initialized successfully
✓ Player found and ready
API Response: {status: 1, data: Array(1)}
Loaded 1 active advertisements
```

### **Step 4: Play a Song**

Click any song to start playback.

### **Step 5: Let Song Finish Completely**

Wait for the song to end naturally (don't skip).

When the song ends, you should see:

```
onSongEnded called by audio-player-videojs.js
Song ended. Total songs played: 1
Checking if ad should play. Songs played: 1
Ad: Your Ad Title | Frequency: 1 | Should play: true
Ad selected to play: Your Ad Title
=== PLAYING ADVERTISEMENT ===
Ad Title: Your Ad Title
Ad Duration: 15 seconds
Ad URL: http://localhost:8000/uploads/advertisements/xxxxx.mp3
Paused song index: 0
Adding ad to playlist
Ad playback started
=== ADVERTISEMENT SETUP COMPLETE ===
```

### **Step 6: Verify Ad Plays**

- ✅ Red banner appears at top: "Advertisement - Playing: [Title]"
- ✅ Player controls are disabled (grayed out)
- ✅ Ad audio plays
- ✅ After 15 seconds, ad ends and song resumes

When ad ends:

```
Advertisement ended - handled by advertisement manager
=== ADVERTISEMENT ENDED ===
Removing ad at index: 1
Song resumed
=== ADVERTISEMENT CLEANUP COMPLETE ===
```

---

## 🔍 Manual Testing Commands

Open browser console (F12) and type:

### Check if Advertisement Manager is Loaded

```javascript
advertisementManager;
```

Should return: `Object {activeAds: Array, songPlayCount: 0, ...}`

### Check Active Ads

```javascript
advertisementManager.activeAds;
```

Should return: Array with your advertisement(s)

### Check Song Count

```javascript
advertisementManager.songPlayCount;
```

Should return: Number of songs played

### Check API Directly

```javascript
fetch("/api/advertisements/active")
  .then((r) => r.json())
  .then(console.log);
```

Should return: `{status: 1, data: [...]}`

### Force Play Ad (Testing)

```javascript
if (advertisementManager.activeAds.length > 0) {
  advertisementManager.playAdvertisement(advertisementManager.activeAds[0]);
}
```

Should immediately play the ad

### Reset Song Counter

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

---

## 📋 Expected Flow

### **Normal Song Playback**

1. User clicks song → Song plays
2. Song ends → `audio-player-videojs.js` `ended` event fires
3. Checks: Is this an ad? → No
4. Checks: Is repeat enabled? → No
5. Calls: `advertisementManager.onSongEnded()`
6. Advertisement manager increments song count: `songPlayCount++`
7. Advertisement manager checks: `songPlayCount % frequency === 0`
8. If YES → Play ad
9. If NO → `gmoplayer.playlist.next()` (move to next song)

### **Advertisement Playback**

1. Ad injected at index `currentIndex + 1`
2. Player switches to ad
3. Controls disabled
4. Red banner shown
5. Ad plays for duration (e.g., 15 seconds)
6. Ad ends → `ended` event fires
7. Checks: Is this an ad? → YES
8. Returns early (doesn't call `onSongEnded`)
9. Advertisement manager detects ad end
10. Removes ad from playlist
11. Resumes original song from saved position
12. Re-enables controls
13. Hides banner

---

## 🐛 Troubleshooting

### **Ad Not Playing**

**Check 1: Is the ad active?**

```javascript
advertisementManager.activeAds;
```

If empty, check database: `SELECT * FROM audio_advertisements WHERE status = 1`

**Check 2: Is frequency correct?**

- Frequency type: `song_based`
- Frequency value: `1` (play after every 1 song)

**Check 3: Is song count incrementing?**

```javascript
advertisementManager.songPlayCount;
```

Should increase after each song ends

**Check 4: Is player detected?**

```javascript
typeof gmoplayer;
```

Should return: `"object"`

**Check 5: Check for errors**
Look for red errors in console

### **Ad Plays But Doesn't End**

Check if `isAdvertisement` flag is set:

```javascript
gmoplayer.playlist()[gmoplayer.playlist.currentIndex()];
```

Should have `isAdvertisement: true`

### **Song Doesn't Resume After Ad**

Check saved state:

```javascript
advertisementManager.pausedSongIndex; // Should be >= 0
advertisementManager.pausedSongTime; // Should be > 0
```

---

## 📊 Database Check

### View All Ads

```sql
SELECT * FROM audio_advertisements;
```

### View Active Ads

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

### Your Current Ad Should Show

- `title`: Your ad title
- `duration`: 15
- `play_frequency_type`: song_based
- `play_frequency_value`: 1
- `is_skippable`: 0
- `status`: 1
- `priority`: 1

---

## ✅ Success Indicators

When working correctly:

1. ✅ Console shows "Advertisement Manager initialized"
2. ✅ Console shows "Loaded 1 active advertisements"
3. ✅ After song ends, console shows "onSongEnded called"
4. ✅ Console shows "Ad: ... | Should play: true"
5. ✅ Red banner appears
6. ✅ Controls become disabled (gray/unclickable)
7. ✅ Ad audio plays
8. ✅ After ad, original song resumes
9. ✅ Controls re-enabled
10. ✅ Banner disappears

---

## 🎯 Current Settings Explanation

**Your Advertisement Settings:**

- **Duration**: 15 seconds → Ad plays for 15 seconds
- **Frequency Type**: song_based → Triggered after X songs
- **Frequency Value**: 1 → Play after every 1 song
- **Priority**: 1 → If multiple ads, higher priority plays first
- **Skip**: Disabled → Users cannot skip (controls disabled)

**This Means:**

- Play 1 song → Ad plays
- Play another song → Ad plays again
- And so on...

If you want ad to play after every 3 songs, change `play_frequency_value` to `3`.

---

## 📞 Still Not Working?

Take a screenshot of:

1. Browser console output (F12)
2. Network tab showing `/api/advertisements/active` response
3. Database record for your advertisement

This will help diagnose the exact issue.
