// mailer.js

const statusIndicator = document.getElementById('statusIndicator');
const sentCount = document.getElementById('sentCount');
const failedCount = document.getElementById('failedCount');
const remainingCount = document.getElementById('remainingCount');
const startButton = document.getElementById('startButton');
const pauseButton = document.getElementById('pauseButton');
const resumeButton = document.getElementById('resumeButton');
const stopButton = document.getElementById('stopButton');
const resetButton = document.getElementById('resetButton');
const retryButton = document.getElementById('retryButton');
const saveConfigButton = document.getElementById('saveConfigButton');
const notification = document.getElementById('notification');
const emailConfigForm = document.getElementById('emailConfigForm');

let batchProcessInterval, statusCheckInterval;

function showNotification(msg, type='success') {
  notification.textContent = msg;
  notification.className = `notification ${type} show`;
  setTimeout(()=> notification.className='notification', 2500);
}
async function callAPI(action,data={}) {
  const formData = new FormData();
  formData.append('action', action);
  for (let k in data) formData.append(k,data[k]);
  try {
    const res = await fetch('api.php',{method:'POST',body:formData});
    return await res.json();
  }catch(err){
    console.error(err);showNotification('Connection error','error');return {error:err.message};
  }
}
function updateUI(data){
  sentCount.textContent = data.sent_count||0;
  failedCount.textContent = data.failed_count||0;
  remainingCount.textContent = Math.max(0,(data.queue_length||0) - (data.current_index||0));
  statusIndicator.textContent = "Status: "+(data.status||'idle').toUpperCase();
}
async function saveConfig(){
  const data = Object.fromEntries(new FormData(emailConfigForm));
  const r = await callAPI('save_config',data);
  if(!r.error) showNotification('Config saved');
}
async function startSending(){ await saveConfig(); const r=await callAPI('start_sending');
  if(!r.error){ showNotification('Started'); processBatch(); statusCheckInterval=setInterval(checkStatus,2000);} }
async function pauseSending(){await callAPI('pause_sending'); showNotification('Paused');}
async function resumeSending(){await callAPI('resume_sending');showNotification('Resumed');processBatch();}
async function stopSending(){await callAPI('stop_sending');showNotification('Stopped');clearInterval(statusCheckInterval);}
async function resetCounters(){await callAPI('reset_counters');showNotification('Counters reset');}
async function retryFailedEmails(){await callAPI('retry_failed');showNotification('Retry queued');}
async function checkStatus(){const r=await callAPI('get_status'); if(!r.error) updateUI(r);}
async function processBatch(){const r=await callAPI('process_batch'); if(!r.error){updateUI(r);
  if(r.status==='running'){batchProcessInterval=setTimeout(processBatch,1000);} }}

startButton.addEventListener('click', startSending);
pauseButton.addEventListener('click', pauseSending);
resumeButton.addEventListener('click', resumeSending);
stopButton.addEventListener('click', stopSending);
resetButton.addEventListener('click', resetCounters);
retryButton.addEventListener('click', retryFailedEmails);
saveConfigButton.addEventListener('click', saveConfig);

checkStatus();