function openform(fdate, edate) {
  $(".fluid-container.data-form").show();
  $("#send_time").attr('data-jDate', fdate);
  $("#send_time").attr('data-gDate', edate);
  $("#send_time").val(fdate);
  $("#gsend_time").val(edate);

  let myedate = edate.split(" ");
  myedate_el = myedate[0].split("/");

  if (myedate_el[1].length == 1) {
    myedate_el[1] = myedate_el[1].charAt(0).replace("", "0").concat(myedate_el[1].charAt(1));
  }
  if (myedate_el[2].length == 1) {
    myedate_el[2] = myedate_el[2].charAt(0).replace("", "0").concat(myedate_el[2].charAt(1));
  }


  myedate_el = myedate_el.toString();
  myedate_el = myedate_el.replaceAll(",", "-");

  var dateformData = {
    action: "get_reminder_data",
    date: myedate_el,

  };

  $.ajax({
    type: "POST",
    url: "recent-reminder.php",
    data: dateformData,
    dataType: "json",
    encode: true,
  }).done(function (data) {

    if (data) {

      $("#complete-reminder-tablebody").html("");
      $("#pending-reminder-tablebody").html("");
      for (let i = 0; i < data.length; i++) {
        if (data[i].status == "completed") {
          $("#complete-reminder-tablebody").append("<tr><td>" + data[i].phone + "</td><td>" + data[i].send_time + "</td><td>" + decodeURIComponent(escape(data[i].massage)) + "</td><td>" + data[i].status + "</td></tr>");
        } else {
          $("#pending-reminder-tablebody").append("<tr><td>" + data[i].phone + "</td><td>" + data[i].send_time + "</td><td>" + decodeURIComponent(escape(data[i].massage)) + "</td><td>" + data[i].status + "</td><td><div class='btn-group'><button class='btn btn-success btn-sm' >تکمیل شده</button><button class='btn btn-primary btn-sm' >ویرایش</button></td>");

        }
      }





    } else {
      $("#pending-reminder-tablebody").append("<h2>هیچ یادآور تکمیل شده ای یافت نشد</h2>");
    }
  });
}
function all_recent_reminder() {
  var dateformData = {
    action: "get_all_reminder_data",
  };

  $.ajax({
    type: "POST",
    url: "recent-reminder.php",
    data: dateformData,
    dataType: "json",
    encode: true,
  }).done(function (data) {

    if (data) {

      $("#complete-reminder-tablebody").html("");
      $("#pending-reminder-tablebody").html("");
      for (let i = 0; i < data.length; i++) {
        if (data[i].status == "completed") {
          $("#complete-reminder-tablebody").append("<tr><td>" + data[i].phone + "</td><td>" + data[i].send_time + "</td><td>" + decodeURIComponent(escape(data[i].massage)) + "</td><td>" + data[i].status + "</td></tr>");
        } else {
          $("#pending-reminder-tablebody").append("<tr><td>" + data[i].phone + "</td><td>" + data[i].send_time + "</td><td>" + decodeURIComponent(escape(data[i].massage)) + "</td><td>" + data[i].status + "</td><td><div class='btn-group'><button class='btn btn-success btn-sm' >تکمیل شده</button><button class='btn btn-primary btn-sm' >ویرایش</button></td>");

        }
      }





    } else {
      $("#pending-reminder-tablebody").append("<h2>هیچ یادآور تکمیل شده ای یافت نشد</h2>");
    }
  });
}
function close_form() {
  $(".fluid-container.data-form").hide();
}
function close_recent_reminders() {
  $("#recent-reminders").hide();
}
$(document).ready(function () {


  ///show status   
   $.ajax({
    url: 'function.php',
    method: 'POST',
    data: { action: "showstatus"},
    success: function(data) {
       let alldata= JSON.parse(data);
        console.log(alldata);
       let alldays= $(".pdp-default .day.cell:not(.friday)");
       data.each(function (index) {
          
            console.log(data[index]);
       });
      
    },
    error: function() {
      console.error("خطا در دریافت داده‌ها از سرور");
      
    }
  });


  /// end show status
  
  
  $("#time").change(function () {

    let time = [];
    $("#gsend_time").val().split(" ")[1] = $("#time").val();
    time[0] = $("#gsend_time").val().split(" ")[0];
    time[1] = $("#time").val();
    let datetime = time.toString().replace(",", " ");

    $("#gsend_time").val(datetime);
    $("#send_time").attr('data-gDate', datetime);


    let jtime = [];

    $("#send_time").attr("data-jdate").split(" ")[1] = $("#time").val();
    jtime[0] = $("#send_time").attr("data-jdate").split(" ")[0];
    jtime[1] = $("#time").val();
    let jdatetime = jtime.toString().replace(",", " ");
    $("#send_time").attr('data-jDate', jdatetime);
    $("#send_time").val(jdatetime);

  });
  $("#send_time").change(function () {
    $("#gsend_time").val(this.val());
  });

//send register form request 
  $("#register-form").submit(function (event) {

    var formData = {
      phone: $("#phone").val(),
      telegram_usern: $("#telegram_usern").val(),
      first_name: $("#first_name").val(),
    };

    $.ajax({
      type: "POST",
      url: "register-form.php",
      data: formData,
      dataType: "json",
      encode: true,
    }).done(function (data) {
      if (data) {

        popnote(data[0], data[1]);


      }
    });

    event.preventDefault();
  });

//end send register form request 
//send set random user request 

 $("#set-user-random").click(function (event) {
     
     

 $.ajax({
      type: "POST",
      url: "function.php",
      data: { action: "getuser"},
    }).done(function (data) {
      if (data) {
          
         let user_result = jQuery.parseJSON(data);
          

         let allusers = user_result.map(p => `${p.id}: ${p.name}`);


        
           user_data= distributeRandomNames(".pdp-default .day.cell:not(.friday)", allusers);
          
          
         save_user_reminder_date(user_data);

      }
    });
    
     event.preventDefault();
    
 });
function save_user_reminder_date(data){
    
   $.ajax({
  type: "POST",
  url: "set-reminder-date.php",
  data: {
    action: "saveUsersWithDates",
    users: JSON.stringify(data)
  },
  success: function(response) {
    console.log("پاسخ از سرور:", response);
  },
  error: function(xhr, status, error) {
    console.error("خطا در ارسال:", error);
  }
});

} 
  

//end send set random user request 
  $("#show-recent").click(function (event) {

    $("#recent-reminders").show();

  });
  $("#all-reminder").click(function (event) {
    $("#recent-reminders").show();
    all_recent_reminder();
  });

  $("#register-reminder").click(function (event) {

    $(".fluid-container.register-form").show();

  });

  //show alert

  function popnote(message, status = 'info') {
    const allowed = ['success', 'danger', 'warning', 'info'];
    if (!allowed.includes(status)) status = 'info';
    let container = 'body';
    const $container = $(container);
    if (!$container.length) $container = $('body');


    const $alert = $(`
            <div  class="alert alert-${status} alert-dismissible fade show popnote-custom " role="alert" id="custom_alert" >
                ${$('<div>').text(message).html()}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `);

    $container.prepend($alert);
    $alert.slideDown(200);

    const timer = setTimeout(() => {
      $alert.fadeTo(500, 0, function () {
        $(this).slideUp(200, function () { $(this).remove(); });
      });
    }, 3000);

    $alert.on('click', 'button.btn-close', function () {
      clearTimeout(timer);
      $alert.stop(true).fadeOut(200, function () { $(this).remove(); });
    });
  }
  window.popnote = popnote;

  //set random user


  function distributeRandomNames(boxSelector, namesArray, avoidRepeat = 5) {
    const boxes = $(boxSelector);
    const boxCount = boxes.length;

    let result = [];
    let dates=[];

    function shuffle(array) {
      let a = array.slice();
      for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
      }
      return a;
    }

    while (result.length < boxCount) {
        
      const shuffled = shuffle(namesArray);
      for (let i = 0; i < shuffled.length && result.length < boxCount; i++) {
          
            let parts = shuffled[i].split(":");
         let id = parts[0].trim();    
        const name = parts[1].trim();
        const recent = result.slice(-avoidRepeat); 
        if (!recent.includes(name)) {
          result.push({name , id});
        }
      }
    }
   
    boxes.each(function (index) {
         
        if(result[index]){
            
            dates[index]=$(this).attr("data-gdate") ;
            $(this).find('.user-first-name').text(result[index].name);
        }
      
    });
    
    result.forEach(function(person, index) {
         person.date = dates[index] || null;  
      });
    
   return result;
  }
  






});


