<!--start main wrapper-->
<main class="main-wrapper">
  <div class="main-content">
    <div class="row my-2">
      <div class="col-md-6">
        <h4>Content Management</h4>
      </div>
      <div class="col-md-6 text-end">
        <div class="btn-group">
          <a href="<?= base_url('content/addPrioritizedVideo'); ?>" class="btn btn-primary">
            <i class="bi bi-camera-video"></i> Add Video
          </a>
          <a href="<?= base_url('content/addAdvertisement'); ?>" class="btn btn-success">
            <i class="bi bi-badge-ad"></i> Add Advertisement
          </a>
        </div>
      </div>
    </div>

    <!-- Tabs -->
    <ul class="nav nav-tabs custom-tabs" id="contentTabs" role="tablist">
      <li class="nav-item" role="presentation">
        <button class="nav-link active" id="videos-tab" data-bs-toggle="tab" data-bs-target="#videos" type="button">
          <i class="bi bi-camera-video-fill"></i> Prioritized Videos (<?= count($videos); ?>)
        </button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="ads-tab" data-bs-toggle="tab" data-bs-target="#ads" type="button">
          <i class="bi bi-badge-ad-fill"></i> Advertisements (<?= count($advertisements); ?>)
        </button>
      </li>
    </ul>

    <?php
    $success = $this->session->flashdata('success');
    $error = $this->session->flashdata('error');
    
    if(!empty($success)): ?>
        <div class="alert alert-success alert-dismissible fade show mt-3" role="alert">
            <?= $success; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif;
    
    if(!empty($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show mt-3" role="alert">
            <?= $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="tab-content p-3 border border-top-0" id="contentTabsContent">
      
      <!-- Prioritized Videos Tab -->
      <div class="tab-pane fade show active" id="videos" role="tabpanel">
        <div class="table-responsive">
          <table class="table table-bordered align-middle">
            <thead>
              <tr>
                <th>#</th>
                <th>Thumbnail</th>
                <th>Title</th>
                <th>Priority</th>
                <th>Views</th>
                <th>Likes</th>
                <th>Status</th>
                <th>Created</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php
              if(!empty($videos)) {
                  $count = 1;
                  foreach($videos as $videoId => $video) {
                      $title = isset($video['title']) ? $video['title'] : 'N/A';
                      $thumbnailUrl = isset($video['thumbnailUrl']) ? $video['thumbnailUrl'] : '';
                      $priority = isset($video['priority']) ? $video['priority'] : 0;
                      $views = isset($video['views']) ? $video['views'] : 0;
                      $likes = isset($video['likes']) ? $video['likes'] : 0;
                      $isActive = isset($video['isActive']) ? $video['isActive'] : true;
                      $createdDate = isset($video['createdDate']) ? date('Y-m-d', $video['createdDate'] / 1000) : 'N/A';
                      
                      $statusClass = $isActive ? 'status-proceed' : 'status-reject';
                      $statusText = $isActive ? 'Active' : 'Inactive';
              ?>
              <tr>
                <td><?= $count++; ?></td>
                <td>
                  <?php if(!empty($thumbnailUrl)): ?>
                    <img src="<?= htmlspecialchars($thumbnailUrl); ?>" alt="Thumbnail" style="width: 80px; height: 45px; object-fit: cover; border-radius: 4px;">
                  <?php else: ?>
                    <div style="width: 80px; height: 45px; background: #e9ecef; display: flex; align-items: center; justify-content: center; border-radius: 4px;">
                      <i class="bi bi-camera-video" style="font-size: 24px; color: #6c757d;"></i>
                    </div>
                  <?php endif; ?>
                </td>
                <td><strong><?= htmlspecialchars($title); ?></strong></td>
                <td><span class="badge bg-info"><?= $priority; ?></span></td>
                <td><i class="bi bi-eye"></i> <?= number_format($views); ?></td>
                <td><i class="bi bi-heart-fill text-danger"></i> <?= number_format($likes); ?></td>
                <td class="<?= $statusClass; ?>">
                  <span class="status-dot"></span><?= $statusText; ?>
                </td>
                <td><?= $createdDate; ?></td>
                <td>
                  <a href="<?= base_url('content/viewVideo/'.$videoId); ?>" class="btn btn-sm btn-info" title="View">
                    <i class="bi bi-eye"></i>
                  </a>
                  <a href="<?= base_url('content/editVideo/'.$videoId); ?>" class="btn btn-sm btn-warning" title="Edit">
                    <i class="bi bi-pencil"></i>
                  </a>
                  <button class="btn btn-sm <?= $isActive ? 'btn-secondary' : 'btn-success'; ?> toggleVideoStatus" 
                          data-videoid="<?= $videoId; ?>" data-active="<?= $isActive ? 'true' : 'false'; ?>" 
                          title="<?= $isActive ? 'Deactivate' : 'Activate'; ?>">
                    <i class="bi bi-<?= $isActive ? 'dash-circle' : 'check-circle'; ?>"></i>
                  </button>
                  <button class="btn btn-sm btn-danger deleteVideo" data-videoid="<?= $videoId; ?>" data-title="<?= htmlspecialchars($title); ?>" title="Delete">
                    <i class="bi bi-trash"></i>
                  </button>
                </td>
              </tr>
              <?php
                  }
              } else {
              ?>
              <tr>
                <td colspan="9" class="text-center">No prioritized videos found</td>
              </tr>
              <?php } ?>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Advertisements Tab -->
      <div class="tab-pane fade" id="ads" role="tabpanel">
        <div class="table-responsive">
          <table class="table table-bordered align-middle">
            <thead>
              <tr>
                <th>#</th>
                <th>Preview</th>
                <th>Title</th>
                <th>Type</th>
                <th>Campaign Period</th>
                <th>Duration</th>
                <th>Impressions</th>
                <th>Clicks</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php
              if(!empty($advertisements)) {
                  $count = 1;
                  foreach($advertisements as $adId => $ad) {
                      $title = isset($ad['title']) ? $ad['title'] : 'N/A';
                      $mediaUrl = isset($ad['mediaUrl']) ? $ad['mediaUrl'] : '';
                      $adType = isset($ad['adType']) ? $ad['adType'] : 'banner';
                      $duration = isset($ad['duration']) ? $ad['duration'] : 0;
                      $impressions = isset($ad['impressions']) ? $ad['impressions'] : 0;
                      $clicks = isset($ad['clicks']) ? $ad['clicks'] : 0;
                      $isActive = isset($ad['isActive']) ? $ad['isActive'] : true;
                      $startDate = isset($ad['startDate']) ? date('Y-m-d', $ad['startDate'] / 1000) : 'N/A';
                      $endDate = isset($ad['endDate']) ? date('Y-m-d', $ad['endDate'] / 1000) : 'N/A';
                      
                      // Check if campaign is currently running
                      $now = time() * 1000;
                      $isRunning = false;
                      if(isset($ad['startDate']) && isset($ad['endDate'])) {
                          $isRunning = ($now >= $ad['startDate'] && $now <= $ad['endDate']);
                      }
                      
                      $statusClass = $isActive ? 'status-proceed' : 'status-reject';
                      $statusText = $isActive ? 'Active' : 'Inactive';
                      
                      // Ad type badge
                      $typeBadge = 'bg-secondary';
                      $typeIcon = 'image';
                      if($adType === 'banner') {
                          $typeBadge = 'bg-info';
                          $typeIcon = 'layout-text-window';
                      } elseif($adType === 'popup') {
                          $typeBadge = 'bg-warning';
                          $typeIcon = 'window-stack';
                      } elseif($adType === 'video') {
                          $typeBadge = 'bg-primary';
                          $typeIcon = 'camera-video';
                      }
              ?>
              <tr>
                <td><?= $count++; ?></td>
                <td>
                  <?php if(!empty($mediaUrl)): ?>
                    <?php if($adType === 'video'): ?>
                      <video src="<?= htmlspecialchars($mediaUrl); ?>" style="width: 80px; height: 45px; object-fit: cover; border-radius: 4px;"></video>
                    <?php else: ?>
                      <img src="<?= htmlspecialchars($mediaUrl); ?>" alt="Ad" style="width: 80px; height: 45px; object-fit: cover; border-radius: 4px;">
                    <?php endif; ?>
                  <?php else: ?>
                    <div style="width: 80px; height: 45px; background: #e9ecef; display: flex; align-items: center; justify-content: center; border-radius: 4px;">
                      <i class="bi bi-badge-ad" style="font-size: 24px; color: #6c757d;"></i>
                    </div>
                  <?php endif; ?>
                </td>
                <td><strong><?= htmlspecialchars($title); ?></strong></td>
                <td>
                  <span class="badge <?= $typeBadge; ?>">
                    <i class="bi bi-<?= $typeIcon; ?>"></i> <?= ucfirst($adType); ?>
                  </span>
                </td>
                <td>
                  <small>
                    📅 <?= $startDate; ?><br>
                    🏁 <?= $endDate; ?>
                    <?php if($isRunning): ?>
                      <br><span class="badge bg-success">Running</span>
                    <?php elseif($now < $ad['startDate']): ?>
                      <br><span class="badge bg-secondary">Scheduled</span>
                    <?php else: ?>
                      <br><span class="badge bg-dark">Ended</span>
                    <?php endif; ?>
                  </small>
                </td>
                <td><?= $duration; ?>s</td>
                <td><?= number_format($impressions); ?></td>
                <td><?= number_format($clicks); ?></td>
                <td class="<?= $statusClass; ?>">
                  <span class="status-dot"></span><?= $statusText; ?>
                </td>
                <td>
                  <a href="<?= base_url('content/viewAdvertisement/'.$adId); ?>" class="btn btn-sm btn-info" title="View">
                    <i class="bi bi-eye"></i>
                  </a>
                  <a href="<?= base_url('content/editAdvertisement/'.$adId); ?>" class="btn btn-sm btn-warning" title="Edit">
                    <i class="bi bi-pencil"></i>
                  </a>
                  <button class="btn btn-sm <?= $isActive ? 'btn-secondary' : 'btn-success'; ?> toggleAdStatus" 
                          data-adid="<?= $adId; ?>" data-active="<?= $isActive ? 'true' : 'false'; ?>" 
                          title="<?= $isActive ? 'Deactivate' : 'Activate'; ?>">
                    <i class="bi bi-<?= $isActive ? 'dash-circle' : 'check-circle'; ?>"></i>
                  </button>
                  <button class="btn btn-sm btn-danger deleteAd" data-adid="<?= $adId; ?>" data-title="<?= htmlspecialchars($title); ?>" title="Delete">
                    <i class="bi bi-trash"></i>
                  </button>
                </td>
              </tr>
              <?php
                  }
              } else {
              ?>
              <tr>
                <td colspan="9" class="text-center">No advertisements found</td>
              </tr>
              <?php } ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</main>
<!--end main wrapper-->

<script>
$(document).ready(function() {
    // Delete Video
    $('.deleteVideo').click(function(e) {
        e.preventDefault();
        var videoId = $(this).data('videoid');
        var title = $(this).data('title');
        
        Swal.fire({
            title: 'Delete Video?',
            html: '<strong>' + title + '</strong><br><br><span style="color: #dc3545;">This action cannot be undone!</span>',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<i class="bi bi-trash"></i> Delete',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Deleting...',
                    allowOutsideClick: false,
                    didOpen: () => { Swal.showLoading(); }
                });
                
                $.ajax({
                    url: '<?= base_url('content/deleteVideo'); ?>',
                    type: 'POST',
                    data: { videoId: videoId },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire({
                                title: 'Deleted!',
                                text: response.message,
                                icon: 'success',
                                confirmButtonColor: '#198754'
                            }).then(() => { location.reload(); });
                        } else {
                            Swal.fire('Error', response.message, 'error');
                        }
                    }
                });
            }
        });
    });

    // Delete Advertisement
    $('.deleteAd').click(function(e) {
        e.preventDefault();
        var adId = $(this).data('adid');
        var title = $(this).data('title');
        
        Swal.fire({
            title: 'Delete Advertisement?',
            html: '<strong>' + title + '</strong><br><br><span style="color: #dc3545;">This action cannot be undone!</span>',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            confirmButtonText: '<i class="bi bi-trash"></i> Delete'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Deleting...',
                    allowOutsideClick: false,
                    didOpen: () => { Swal.showLoading(); }
                });
                
                $.ajax({
                    url: '<?= base_url('content/deleteAdvertisement'); ?>',
                    type: 'POST',
                    data: { adId: adId },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire('Deleted!', response.message, 'success').then(() => { location.reload(); });
                        } else {
                            Swal.fire('Error', response.message, 'error');
                        }
                    }
                });
            }
        });
    });

    // Toggle Video Status
    $('.toggleVideoStatus').click(function(e) {
        e.preventDefault();
        var videoId = $(this).data('videoid');
        var isActive = $(this).data('active') === 'true';
        var action = isActive ? 'deactivate' : 'activate';
        
        Swal.fire({
            title: action === 'activate' ? 'Activate Video?' : 'Deactivate Video?',
            text: action === 'activate' ? 'Video will be visible to users' : 'Video will be hidden from users',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: action === 'activate' ? '#198754' : '#ffc107',
            confirmButtonText: action === 'activate' ? '<i class="bi bi-check-circle"></i> Activate' : '<i class="bi bi-dash-circle"></i> Deactivate'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '<?= base_url('content/toggleVideoStatus'); ?>',
                    type: 'POST',
                    data: { videoId: videoId, currentStatus: isActive },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire('Success!', response.message, 'success').then(() => { location.reload(); });
                        } else {
                            Swal.fire('Error', response.message, 'error');
                        }
                    }
                });
            }
        });
    });

    // Toggle Ad Status
    $('.toggleAdStatus').click(function(e) {
        e.preventDefault();
        var adId = $(this).data('adid');
        var isActive = $(this).data('active') === 'true';
        var action = isActive ? 'deactivate' : 'activate';
        
        Swal.fire({
            title: action === 'activate' ? 'Activate Advertisement?' : 'Deactivate Advertisement?',
            text: action === 'activate' ? 'Ad will be shown to users' : 'Ad will be hidden from users',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: action === 'activate' ? '#198754' : '#ffc107',
            confirmButtonText: action === 'activate' ? 'Activate' : 'Deactivate'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '<?= base_url('content/toggleAdStatus'); ?>',
                    type: 'POST',
                    data: { adId: adId, currentStatus: isActive },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire('Success!', response.message, 'success').then(() => { location.reload(); });
                        } else {
                            Swal.fire('Error', response.message, 'error');
                        }
                    }
                });
            }
        });
    });
});
</script>

