# Audio Advertisement System - Setup Guide

## Overview

Complete advertisement audio system integrated with your Laravel + video.js player. Ads play at specified frequencies with full control over skippability and playback.

---

## 📁 Files Created

### Backend Files

1. **Migration**: `database/migrations/2025_12_12_000001_create_audio_advertisements_table.php`
2. **Model**: `app/Models/AudioAdvertisement.php`
3. **Controller**: `app/Http/Controllers/Admin/AdvertisementController.php`
4. **Routes**: Added to `routes/web.php`
5. **Admin Views**:
   - `resources/views/admin/advertisements/index.blade.php`
   - `resources/views/admin/advertisements/addEdit.blade.php`

### Frontend Files

1. **JavaScript**: `public/assets/js/advertisement-manager.js`
2. **Updated**: `resources/views/layouts/front/main.blade.php` (added script include)
3. **Updated**: `resources/views/layouts/front/audio_player.blade.php` (added CSS styles)

---

## 🚀 Installation Steps

### 1. Run Database Migration

```bash
php artisan migrate
```

This creates the `audio_advertisements` table with fields:

- `id`, `title`, `audio_file`, `duration`
- `play_frequency_type` (song_based / time_based)
- `play_frequency_value` (integer)
- `is_skippable` (boolean)
- `status` (active/inactive)
- `priority` (higher plays first)

### 2. Create Upload Directory

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

### 3. Set Folder Permissions

Ensure the `public/uploads/advertisements` folder is writable:

```powershell
icacls "public\uploads\advertisements" /grant Users:F /T
```

### 4. Clear Cache

```bash
php artisan config:clear
php artisan route:clear
php artisan view:clear
```

---

## 🎯 Usage

### Admin Panel

**Access**: Navigate to `/admin/advertisements`

**Add Advertisement**:

1. Click "Add Advertisement"
2. Fill in:
   - **Title**: Advertisement name
   - **Audio File**: Upload MP3/WAV (max 10MB)
   - **Duration**: Length in seconds
   - **Frequency Type**:
     - `Song Based`: Play after every X songs
     - `Time Based`: Play at X seconds (future feature)
   - **Frequency Value**: Number (e.g., 3 = every 3 songs)
   - **Allow Skip**: Enable/disable skip option
   - **Priority**: Higher number plays first
   - **Status**: Active/Inactive

**Manage Advertisements**:

- View all ads in data table
- Toggle status with switch
- Edit or delete ads
- Preview audio inline

---

## ⚙️ How It Works

### Frontend Flow

1. **Page Load**:

   - `advertisement-manager.js` fetches active ads from API endpoint
   - Stores ads in memory

2. **Song Playback**:

   - Tracks number of songs played (`songPlayCount`)
   - After every X songs (based on frequency), checks if ad should play

3. **Ad Triggered**:

   - Pauses current song and saves position
   - Inserts ad into playlist at current position + 1
   - Plays advertisement
   - **Disables Controls**:
     - Previous/Next buttons
     - 15-second skip buttons
     - Seek/progress slider
     - Shuffle/Repeat buttons
     - Download/Queue options
   - Shows red banner: "Advertisement - Cannot skip" or "Skip available"

4. **Ad Ends**:
   - Removes ad from playlist
   - Re-enables all controls
   - Resumes original song from paused position
   - Increments song counter

### API Endpoint

**URL**: `GET /api/advertisements/active`

**Response**:

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

---

## 🎛️ Configuration Options

### Advertisement Model Properties

```php
protected $fillable = [
    'title',
    'audio_file',
    'duration',
    'play_frequency_type',  // 'song_based' or 'time_based'
    'play_frequency_value',  // Integer
    'is_skippable',          // Boolean
    'status',                // Boolean
    'priority'               // Integer
];
```

### JavaScript Manager Methods

**Core Functions**:

- `init()` - Initialize and fetch ads
- `fetchActiveAds()` - Load ads from API
- `checkIfAdShouldPlay()` - Determines if ad triggers
- `playAdvertisement(ad)` - Inject and play ad
- `disableControls()` - Hide/disable player controls
- `enableControls()` - Restore player controls
- `adEnded()` - Cleanup and resume playback

**Global Access**:

```javascript
window.advertisementManager.activeAds; // View loaded ads
window.advertisementManager.songPlayCount; // Current count
window.advertisementManager.isPlayingAd; // Boolean
```

---

## 🔧 Customization

### Change Ad Frequency Logic

Edit `advertisement-manager.js`, line ~45:

```javascript
checkIfAdShouldPlay: function() {
    const adToPlay = this.activeAds.find(ad => {
        if (ad.play_frequency_type === 'song_based') {
            // Play after every X songs
            return this.songPlayCount > 0 && this.songPlayCount % ad.play_frequency_value === 0;
        }
        // Add time-based logic here
        return false;
    });
}
```

### Customize Ad Banner

Edit `advertisement-manager.js`, line ~120:

```javascript
showAdIndicator: function(ad) {
    const adBanner = `
        <div id="ad-playing-banner" style="...">
            <strong>Your Custom Text</strong>
        </div>
    `;
    $('body').prepend(adBanner);
}
```

### Change Disabled Control Styles

Edit `audio_player.blade.php`:

```css
.jp-controls button.disabled {
  opacity: 0.3; /* Change opacity */
  cursor: not-allowed;
}
```

---

## 🧪 Testing

### Test Advertisement Upload

1. Go to `/admin/advertisements/create`
2. Upload a short MP3 (10-15 seconds)
3. Set frequency: "Song Based", value: 2
4. Set skippable: No
5. Save

### Test Frontend Playback

1. Open homepage
2. Play 2 songs completely
3. After 2nd song ends, ad should auto-play
4. Verify:
   - Controls are disabled
   - Red banner appears
   - Cannot skip/seek
   - Volume works
   - After ad ends, song resumes

---

## 🐛 Troubleshooting

### Ads Not Playing

- Check browser console for errors
- Verify API endpoint returns data: `/api/advertisements/active`
- Ensure ad status is "Active"
- Check `songPlayCount` in console: `window.advertisementManager.songPlayCount`

### Controls Not Disabled

- Clear browser cache (Ctrl+Shift+Delete)
- Check `isPlayingAd` flag: `window.advertisementManager.isPlayingAd`
- Verify CSS is loaded (inspect element classes)

### Upload Fails

- Check folder permissions: `public/uploads/advertisements`
- Verify file size < 10MB
- Ensure file is MP3 or WAV format

### Ad Doesn't Resume Song

- Check console for `pausedSongIndex` and `pausedSongTime`
- Verify playlist array isn't corrupted
- Test with simple 2-song playlist

---

## 📊 Database Schema

```sql
CREATE TABLE `audio_advertisements` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `audio_file` varchar(255) NOT NULL,
  `duration` int NOT NULL DEFAULT '0',
  `play_frequency_type` enum('time_based','song_based') NOT NULL DEFAULT 'song_based',
  `play_frequency_value` int NOT NULL DEFAULT '3',
  `is_skippable` tinyint(1) NOT NULL DEFAULT '0',
  `status` tinyint(1) NOT NULL DEFAULT '1',
  `priority` int NOT NULL DEFAULT '0',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
);
```

---

## 🔐 Security Notes

- Audio files stored in `public/uploads/advertisements` (publicly accessible)
- Admin routes should be protected with auth middleware
- File upload validates: max 10MB, MP3/WAV only
- API endpoint is public (no authentication required)

---

## 🚀 Future Enhancements

- [ ] Time-based ad triggering (play at specific timestamps)
- [ ] Skip after X seconds (countdown timer)
- [ ] Analytics: track ad impressions and completion rate
- [ ] A/B testing: rotate multiple ads
- [ ] Geo-targeting: show ads based on user location
- [ ] Scheduling: ads active only during certain dates/times

---

## 📝 Routes Reference

### Admin Routes

- `GET /admin/advertisements` - List all ads
- `GET /admin/advertisements/create` - Show create form
- `POST /admin/advertisements/store` - Save new ad
- `GET /admin/advertisements/{id}/edit` - Edit form
- `POST /admin/advertisements/{id}/update` - Update ad
- `DELETE /admin/advertisements/{id}/destroy` - Delete ad
- `POST /admin/advertisements/{id}/toggle-status` - Toggle active/inactive

### API Routes

- `GET /api/advertisements/active` - Fetch active ads for player

---

## ✅ Checklist

- [x] Migration created and run
- [x] Model with relationships
- [x] Admin controller (CRUD)
- [x] Admin views (index, add/edit)
- [x] Routes registered
- [x] JavaScript manager
- [x] API endpoint
- [x] CSS styling for disabled state
- [x] Upload directory created
- [x] Frontend integration complete

---

**System Status**: ✅ Fully Functional

All components are integrated and ready to use. Upload your first advertisement and test the system!
