it works fine when scheduling date start form today's date, if i start from 1 july suppose today 26 june,  my timestam are 4am 6am 9pm, suppose it's 7pm, it not only skips two time stamp 4 am 6am but also skip two videos, i want it use diffrent logic not exactly when start from today's date , some timestmps passed so upcoming timestamp is the starting timestamp, but when start from 1 july there is no passsed timestamp so include diffrent individual logic for that when schedule starting date is not today. {% 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%';

  // Prepare initial schedule queue
  let scheduleQueue;
  // If start date is today, filter out passed times
  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 {
    // For any date in the future, keep all times untouched
    scheduleQueue = [...selectedTimes];
  }

  if (scheduleQueue.length === 0) {
    alert("No upload times remain on the start scheduling day after filtering out past times.");
    return;
  }

  let baseDayOffset = 0; // days added to startDate

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

  for (let i = 0; i < files.length; i++) {
    if (scheduleQueue.length === 0) {
      // Move forward skipDays + 1 days
      baseDayOffset += (1 + skipDays);
      // Reset scheduleQueue with full times on new day -- no filtering needed for future days
      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 datetime string for server
    const yyyy = scheduledDate.getFullYear();
    const MMm = String(scheduledDate.getMonth() + 1).padStart(2, '0');
    const dd = String(scheduledDate.getDate()).padStart(2, '0');
    const HH = String(scheduledDate.getHours()).padStart(2, '0');
    const mmStr = String(scheduledDate.getMinutes()).padStart(2, '0');
    const localDatetime = `${yyyy}-${MMm}-${dd}T${HH}:${mmStr}`;

    // Prepare form data and upload logic as before...
    // (same as your existing code below)
    
    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]);

    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 %}