the problem is it does not woring effienciently for skip days logic, suppose if igive time 4 am, 5am, 6pm   all time passed of today, then it start scheduling from next possible timestamps that could be next day, two days later, 5 days later, if i start from a day suppose 7 days later, what it does it skips the 3 videos then start from next possible timestamps not exactly at 7 days later, fix the problem,     {% extends 'layout.html' %}
{% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Schedule Video Uploads</title>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet" />
  <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
  <style>
    .popup {
      display: none;
      position: fixed;
      top: 10%;
      left: 50%;
      transform: translateX(-50%);
      width: 600px;
      height: 550px;
      background: white;
      padding: 15px;
      border: 1px solid #ccc;
      z-index: 1000;
      box-shadow: 0 0 15px rgba(0,0,0,0.3);
      font-size: 13px;
      overflow-y: auto;
      border-radius: 8px;
    }
    .overlay {
      display: none;
      position: fixed;
      top: 0; left: 0; width: 100%; height: 100%;
      background: rgba(0,0,0,0.4);
      z-index: 999;
    }
    .grid {
      display: grid;
      grid-template-columns: repeat(6, 1fr);
      gap: 8px;
    }
    .hour-box {
      background: #f9f9f9;
      padding: 5px;
      border-radius: 5px;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      font-size: 12px;
    }
    .hour-box select {
      width: 40px;
      font-size: 11px;
      margin-top: 4px;
      padding: 2px;
    }
    #timeList li {
      font-size: 14px;
      margin-bottom: 4px;
    }
    #timeList li button {
      font-size: 11px;
      background: #dc3545;
      color: white;
      border: none;
      border-radius: 3px;
      margin-left: 8px;
    }
  </style>
</head>
<body>
<div class="main-content">
  <div class="form-section">
    <h1>Schedule Multiple Video Uploads</h1>
    <form method="POST" enctype="multipart/form-data" id="uploadForm">
      <label for="channel_id">Select Channel:</label>
      <select name="channel_id" id="channel_id" required>
        <option value="" disabled selected>Select a channel</option>
        {% for channel in channels %}
          <option value="{{ channel.id }}">{{ channel.name }}</option>
        {% endfor %}
      </select>

      <label for="title">Video Title:</label>
      <input type="text" name="title" id="title" value="#shorts #viral #viralshorts" required />

      <label for="start_index">Starting Number for Title:</label>
      <input type="number" name="start_index" id="start_index" value="1" min="1" />

      <label for="description">Description:</label>
      <textarea name="description" id="description" rows="4" placeholder="Enter description (optional)"></textarea>

      <label for="tags">Tags (comma separated):</label>
      <input type="text" name="tags" id="tags" placeholder="tag1, tag2, tag3" />

      <label>Select Upload Times:</label>
      <button type="button" onclick="openHourPopup()">+ Select Times</button>
      <ul id="timeList"></ul>
      <input type="hidden" id="dailyTimesInput" name="daily_times_json" />

      <div style="display: flex; align-items: center; gap: 20px; margin-top: 10px;">
        <div style="flex: 1;">
          <label for="skip_days">Skip for Days:</label>
          <input type="number" id="skip_days" name="skip_days" value="0" min="0" />
        </div>
        <div style="flex: 1;">
          <label for="start_schedule_date">Start Scheduling From:</label>
          <input type="date" id="start_schedule_date" name="start_schedule_date"
                 value="{{ current_date }}" required />
        </div>
      </div>

      <label for="video_files" style="margin-top: 10px;">Select Videos:</label>
      <input type="file" name="video_files" id="video_files" multiple required />

      <button type="submit" style="margin-top: 15px;">Upload</button>
    </form>

    <div id="progressContainer" style="display: none;">
      <h3>Upload Progress</h3>
      <div class="progress-container" style="width: 100%; background: #eee; border-radius: 6px; overflow: hidden; height: 20px;">
        <div class="progress-fill" id="overallProgress" style="height: 100%; background: #28a745; width: 0%; transition: width 0.3s;"></div>
      </div>
      <span id="progressText">0%</span>
      <div id="fileStatusContainer" style="margin-top: 10px;"></div>
    </div>
  </div>
</div>

<div id="hourPopup" class="popup">
  <h3>Select Upload Hours</h3>
  <div id="hourGrid" class="grid">
    {% for h in range(0, 24) %}
      {% set hour_display = h % 12 if h % 12 != 0 else 12 %}
      {% set meridian = 'AM' if h < 12 else 'PM' %}
      <div class="hour-box">
        <label><input type="checkbox" id="hour{{h}}" value="{{ h }}"> {{ hour_display }} {{ meridian }}</label>
        <select id="min{{h}}">
          {% for m in range(0, 60) %}
            <option value="{{ '%02d' % m }}">{{ '%02d' % m }}</option>
          {% endfor %}
        </select>
      </div>
    {% endfor %}
  </div>
  <div style="text-align: right; margin-top: 10px;">
    <button onclick="confirmHourSelection()">Done</button>
    <button onclick="closeHourPopup()">Cancel</button>
  </div>
</div>
<div class="overlay" id="popupOverlay" onclick="closeHourPopup()"></div>

<script>
let selectedTimes = [];

function openHourPopup() {
  document.getElementById('hourPopup').style.display = 'block';
  document.getElementById('popupOverlay').style.display = 'block';
}
function closeHourPopup() {
  document.getElementById('hourPopup').style.display = 'none';
  document.getElementById('popupOverlay').style.display = 'none';
}
function confirmHourSelection() {
  selectedTimes = [];
  for (let h = 0; h < 24; h++) {
    const checkbox = document.getElementById('hour' + h);
    const minute = document.getElementById('min' + h).value;
    if (checkbox.checked) {
      selectedTimes.push(`${String(h).padStart(2, '0')}:${minute}`);
    }
  }
  selectedTimes.sort();
  document.getElementById('dailyTimesInput').value = JSON.stringify(selectedTimes);
  renderTimeList();
  closeHourPopup();
}
function renderTimeList() {
  const ul = document.getElementById('timeList');
  ul.innerHTML = '';
  selectedTimes.forEach((time, index) => {
    const [h, m] = time.split(':');
    const hour = parseInt(h);
    const ampm = hour < 12 ? 'AM' : 'PM';
    const hour12 = hour % 12 || 12;
    const label = `${hour12}:${m} ${ampm}`;
    const li = document.createElement('li');
    li.textContent = label;
    const del = document.createElement('button');
    del.textContent = 'Remove';
    del.onclick = () => {
      selectedTimes.splice(index, 1);
      document.getElementById('dailyTimesInput').value = JSON.stringify(selectedTimes);
      renderTimeList();
    };
    li.appendChild(del);
    ul.appendChild(li);
  });
}

document.getElementById('uploadForm').addEventListener('submit', async function(event) {
  event.preventDefault();

  const files = document.getElementById('video_files').files;
  if (!files.length) {
    alert("Please select video files.");
    return;
  }

  const selectedTimes = JSON.parse(document.getElementById('dailyTimesInput').value || '[]');
  if (!selectedTimes.length) {
    alert("Please select at least one upload time.");
    return;
  }

  const skipDays = parseInt(document.getElementById('skip_days').value) || 0;
  const startDateInput = document.getElementById('start_schedule_date').value;
  if (!startDateInput) {
    alert("Please select a start scheduling date.");
    return;
  }

  const startDate = new Date(startDateInput + "T00:00:00");
  const now = new Date();

  const form = event.target;
  const progressContainer = document.getElementById('progressContainer');
  const overallProgress = document.getElementById('overallProgress');
  const progressText = document.getElementById('progressText');
  const fileStatusContainer = document.getElementById('fileStatusContainer');

  progressContainer.style.display = 'block';
  fileStatusContainer.innerHTML = '';
  overallProgress.style.width = '0%';
  progressText.textContent = '0%';

  // Filter out times already passed today only for the first scheduling day (startDate)
  let scheduleQueue = [];
  if (startDate.toDateString() === now.toDateString()) {
    scheduleQueue = selectedTimes.filter(t => {
      const [h, m] = t.split(':');
      const temp = new Date();
      temp.setHours(parseInt(h), parseInt(m), 0, 0);
      return temp > now;
    });
  } else {
    scheduleQueue = [...selectedTimes];
  }

  let baseDayOffset = 0; // Number of days added to startDate for scheduling

  let uploadedCount = 0;
  let successfulUploads = 0;
  let failedUploads = 0;

  for (let i = 0; i < files.length; i++) {
    if (scheduleQueue.length === 0) {
      // Finished all slots on current day, skip days then reset scheduleQueue
      baseDayOffset += (1 + skipDays);
      scheduleQueue = [...selectedTimes];
    }

    const scheduledTimeStr = scheduleQueue.shift();
    const [hh, mm] = scheduledTimeStr.split(':');

    const scheduledDate = new Date(startDate);
    scheduledDate.setDate(startDate.getDate() + baseDayOffset);
    scheduledDate.setHours(parseInt(hh), parseInt(mm), 0, 0);

    // Format date-time string
    const yyyy = scheduledDate.getFullYear();
    const MM = String(scheduledDate.getMonth() + 1).padStart(2, '0');
    const dd = String(scheduledDate.getDate()).padStart(2, '0');
    const HH = String(scheduledDate.getHours()).padStart(2, '0');
    const MMm = String(scheduledDate.getMinutes()).padStart(2, '0');
    const localDatetime = `${yyyy}-${MM}-${dd}T${HH}:${MMm}`;

    // Prepare form data
    const formData = new FormData();
    formData.append('channel_id', form.channel_id.value);
    const startIndex = parseInt(form.start_index.value) || 1;
    const customTitle = `${form.title.value} (${startIndex + i})`;
    formData.append('title', customTitle);
    formData.append('description', form.description.value);
    formData.append('tags', form.tags.value);
    formData.append('scheduled_time', localDatetime);
    formData.append('timezone_offset', new Date().getTimezoneOffset());
    formData.append('video_files', files[i]);

    // Show status
    const statusDiv = document.createElement('div');
    statusDiv.className = 'file-status';
    statusDiv.innerHTML = `<span class="status-icon">⏳</span><span class="file-name">${files[i].name}</span><span class="status-text" style="margin-left: auto;">Uploading...</span>`;
    fileStatusContainer.appendChild(statusDiv);

    try {
      const response = await fetch('/upload', { method: 'POST', body: formData });
      const data = await response.json();
      if (data.success) {
        statusDiv.querySelector('.status-icon').textContent = '✅';
        statusDiv.querySelector('.status-text').textContent = 'Uploaded successfully';
        successfulUploads++;
      } else {
        throw new Error(data.error || 'Upload failed');
      }
    } catch (error) {
      statusDiv.querySelector('.status-icon').textContent = '❌';
      statusDiv.querySelector('.status-text').textContent = `Error: ${error.message}`;
      failedUploads++;
    }

    uploadedCount++;
    const progress = Math.round((uploadedCount / files.length) * 100);
    overallProgress.style.width = `${progress}%`;
    progressText.textContent = `${progress}%`;
  }

  const completionMsg = document.createElement('div');
  completionMsg.innerHTML = `<strong>${successfulUploads} of ${files.length} uploaded successfully.</strong>${failedUploads > 0 ? ` (${failedUploads} failed)` : ''}`;
  fileStatusContainer.appendChild(completionMsg);
});
</script>

</body>
</html>
{% endblock %}