var activityid = null;
var eventid = null;
var packnumber = null;
var packtoken = null;
var bookingnumber = null;
var activitydate, activityyear, activitymonth, activityday, activityname, activitytitle;
var eventdate, eventyear, eventmonth, eventday, eventname, eventtitle;
// Booking columns;
var bcolumns;
// Remote links
//var remotelinks;
// Last tabs for each pill box
var lastTabPaneEvent;
// base url of dream
var url_dream;
// TEST mode
var test = false;
// JSON edit
var currentEdit = null;

//
// get URL parameters
//
const searchParams = new URLSearchParams(window.location.search);

// check if TEST mode is enabled
if( searchParams.has("test")===true ) {
    test = true;
}

// check if there's a token in the URL (packtoken)
if( searchParams.has("booking")===true ) {
    bookingnumber = searchParams.get("booking");
}
if( searchParams.has("pack")===true ) {
    packnumber  = searchParams.get("pack");
}
if( searchParams.has("event")===true ) {
    eventid     = searchParams.get("event");
    eventtitle  = searchParams.get("title");
    eventyear   = eventid.split("/")[0];
    eventmonth  = eventid.split("/")[1];
    eventday    = eventid.split("/")[2];
    eventdate   = eventyear + '/' + eventmonth + '/' + eventday;
    lastTabPaneEvent  = searchParams.get("lastTabPaneEvent");
}
if( searchParams.has("activity")===true ) {
    activityid        = searchParams.get("activity");
    activitytitle     = searchParams.get("title");
}

$(document).ready( function () {

  url_dream = window.location.protocol + "//"
                  + window.location.hostname
                  + window.location.pathname.substring(0, window.location.pathname.lastIndexOf("manage/index.html"));

  if( bookingnumber ) {
    const urlhtml = '../event/' + eventid + '/index.html';
    createBookingColumns(urlhtml)
    .then( (data) => {
      getBookingDetails();
    })
    .catch((error) => {
      console.log(error)
    })    
  } else if( packnumber ) {
    const urlhtml = '../event/' + eventid + '/index.html';
    createBookingColumns(urlhtml)
    .then( (data) => {
      loadPackDetails();
    })
    .catch((error) => {
      console.log(error)
    })    
  } else if( eventid )
    loadEventDetails();
  else if( activityid )
    loadEvents();
  else
    loadPageHome();
});

//////////////////////////////////////////////////////////////
//
//  Activities
//
//////////////////////////////////////////////////////////////

function loadPageHome() {
  $.ajax({
    type: "POST",
    url: "views/home.html",
    dataType: 'text',
    success: function(result){
      $('#conteudo').html(result);
      prepareActivities();
      prepareEvents();
    }
  });
}

function prepareActivities() {
  var dtableActivities = createTableActivities();
  var dtableActivitiesHistory = createTableActivitiesHistory();
  populateTablesActivities(dtableActivities,dtableActivitiesHistory);
  handlerTableActivities(dtableActivities);
  handlerTableActivitiesHistory(dtableActivitiesHistory);
  handlerButtonsActivities(dtableActivities,dtableActivitiesHistory);
  //handlerFormsActivities(dtableActivities,dtableActivitiesHistory);
}

function createTableActivities() {
  return $('#tableActivities').DataTable( {
      orderCellsHome: true,
      fixedHeader: true,
      paginate: false,
      select : false,
      columns: [
        { title: "Data",  width: "10%", data: "begin" },
        { title: "Nome",  width: "10%", data: "name" },
        { title: "Dias",  width: "10%", data: "ndays" },
        { title: "Título",width: "70%", data: "title" }
      ],
      columnDefs: [
        {
          targets: [0,1,2],
          className: 'dt-center'
        }
      ],
      initComplete: function () {
        $('#tableActivities thead tr')
          .clone(true)
          .addClass('filters')
          .appendTo('#tableActivities thead');
        $('#tableActivities thead tr.filters th')
          .off('click')
          .removeClass('sorting')
          .removeClass('sorting_asc');
        var tableActivities = this.api();
        tableActivities
          .columns()
          .eq(0)
          .each(function (colIdx) {
            var cell = $('#tableActivities thead tr.filters th').eq(
              $(tableActivities.column(colIdx).header()).index()
            );
            var title = $(cell).text();
            $(cell).html('<input type="text" name="filter" style="width: 100%" />');
            $('input', $('#tableActivities thead tr.filters th').eq($(tableActivities.column(colIdx).header()).index()))
              .off('keyup change')
              .on('keyup change', function (e) {
                e.stopPropagation();
                $(this).attr('title', $(this).val());
                var regexr = '({search})';
                var cursorPosition = this.selectionStart;
                tableActivities
                  .column(colIdx)
                  .search(
                    this.value != ''
                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                        : '',
                    this.value != '',
                    this.value == ''
                  )
                  .draw();
                $(this)
                  .focus()[0]
                  .setSelectionRange(cursorPosition, cursorPosition);
              });
          });
      }  
    });
}

function createTableActivitiesHistory() {
  return $('#tableActivitiesHistory').DataTable( {
      orderCellsHome: true,
      fixedHeader: true,
      paginate: false,
      select : false,
      columns: [
        { title: "Data",  width: "10%", data: "begin" },
        { title: "Nome",  width: "10%", data: "name" },
        { title: "Dias",  width: "10%", data: "ndays" },
        { title: "Título",width: "70%", data: "title" }
      ],
      columnDefs: [
        {
          targets: [0,1,2],
          className: 'dt-center'
        }
      ],
      initComplete: function () {
        $('#tableActivitiesHistory thead tr')
          .clone(true)
          .addClass('filters')
          .appendTo('#tableActivitiesHistory thead');
        $('#tableActivitiesHistory thead tr.filters th')
          .off('click')
          .removeClass('sorting')
          .removeClass('sorting_asc');
        var tableActivitiesHistory = this.api();
        tableActivitiesHistory
          .columns()
          .eq(0)
          .each(function (colIdx) {
            var cell = $('#tableActivitiesHistory thead tr.filters th').eq(
              $(tableActivitiesHistory.column(colIdx).header()).index()
            );
            var title = $(cell).text();
            $(cell).html('<input type="text" name="filter" style="width: 100%" />');
            $('input', $('#tableActivitiesHistory thead tr.filters th').eq($(tableActivitiesHistory.column(colIdx).header()).index()))
              .off('keyup change')
              .on('keyup change', function (e) {
                e.stopPropagation();
                $(this).attr('title', $(this).val());
                var regexr = '({search})';
                var cursorPosition = this.selectionStart;
                tableActivitiesHistory
                  .column(colIdx)
                  .search(
                    this.value != ''
                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                        : '',
                    this.value != '',
                    this.value == ''
                  )
                  .draw();
                $(this)
                  .focus()[0]
                  .setSelectionRange(cursorPosition, cursorPosition);
              });
          });
      }  
    });
}

function populateTablesActivities(dtableActivities,dtableActivitiesHistory) {
  $.ajax({
      type: "POST",
      url: "../server/manage/tableactivities.php",
      dataType: "json",
      success: function(result){
          dtableActivities.rows.add(result.activities);
          dtableActivities.draw();
          dtableActivitiesHistory.rows.add(result.history);
          dtableActivitiesHistory.draw();
      }
  });
}

function handlerTableActivities(dtableActivities) {
  $('#tableActivities tbody').on('click', 'tr', function () {
    var data = dtableActivities.row( this ).data();
    activitydate  = data.begin;
    activityname  = data.name;
    activitytitle = data.title;
    activityyear  = activitydate.split("-")[0];
    activitymonth = activitydate.split("-")[1];
    activityday   = activitydate.split("-")[2];
    activityid    = activityyear + '/' + activitymonth + '/' + activityday + '/' + activityname;
    loadActivityEvents();
  });
}

function handlerTableActivitiesHistory(dtableActivitiesHistory) {
  $('#tableActivitiesHistory tbody').on('click', 'tr', function () {
    var data = dtableActivitiesHistory.row( this ).data();
    activitydate  = data.begin;
    activityname  = data.name;
    activitytitle = data.title;
    activityyear  = activitydate.split("-")[0];
    activitymonth = activitydate.split("-")[1];
    activityday   = activitydate.split("-")[2];
    activityid    = activityyear + '/' + activitymonth + '/' + activityday + '/' + activityname;
    loadActivityEvents();
  });
}

function handlerButtonsActivities(dtableActivities,dtableActivitiesHistory) {
  $('#clearActivitiesFilter').on('click', function(){
    dtableActivities
        .search( '' )
        .columns().search( '' )
        .draw();
    dtableActivitiesHistory
        .search( '' )
        .columns().search( '' )
        .draw();
    $('input[name="filter"]').val( '' );
  });

  /*
  // Detect if click is short or long
  // If it's long then select row
  let mousedownTime;
  $('#tableActivities tbody').on('mousedown', 'tr', function (e) {          
    mousedownTime = new Date().getTime();
  });
  $('#tableActivities tbody').on('mouseup', 'tr', function (e) {          
    //console.log('mouseup');
    const mouseupTime = new Date().getTime(),
    timeDifference = mouseupTime - mousedownTime;
    if (timeDifference > 300) {  // 0,3 second
      dtableActivities.rows().deselect();
      dtableActivitiesHistory.rows().deselect();
      dtableActivities.row( this ).select();
      //console.log('long press');
      window.addEventListener('click', captureActivityClick, true); // <-- The "true" registeres this listener for the capture phase
    }
  });
  // Detect if click is short or long
  // If it's long then select row
  $('#tableActivitiesHistory tbody').on('mousedown', 'tr', function (e) {          
    mousedownTime = new Date().getTime();
  });
  $('#tableActivitiesHistory tbody').on('mouseup', 'tr', function (e) {          
    //console.log('mouseup');
    const mouseupTime = new Date().getTime(),
    timeDifference = mouseupTime - mousedownTime;
    if (timeDifference > 300) {  // 0,3 second
      dtableActivities.rows().deselect();
      dtableActivitiesHistory.rows().deselect();
      dtableActivitiesHistory.row( this ).select();
      //console.log('long press');
      window.addEventListener('click', captureActivityClick, true); // <-- The "true" registeres this listener for the capture phase
    }
  });
  */
}

/*
// Function that is part of the click detection (short or long)
function captureActivityClick(e) {
  e.stopPropagation(); // Stop the click from being propagated.
  //console.log('click captured');
  window.removeEventListener('click', captureActivityClick, true); // cleanup
  $('#CloneActivity').prop("disabled", false);
}
*/

function handlerFormsActivities(dtableActivities,dtableActivitiesHistory) {
}

function loadActivityEvents() {
  $.ajax({
    type: "POST",
    url: "views/activitydetails.html",
    dataType: 'text',
    success: function(result){
      $('#conteudo').html(result);
      //$('#breadcrumbEvents').text("Atividade: " + activitytitle);
      //$('#breadcrumbEvents').attr("href", "?activity=" + activityid + "&title=" + activitytitle);
      prepareActivityEvents();
    }
  });
}

function prepareEvents() {
  var dtableEvents = createTableEvents();
  var dtableEventsHistory = createTableEventsHistory();
  populateTablesEvents(dtableEvents,dtableEventsHistory);
  handlerTableEvents(dtableEvents);
  handlerTableEventsHistory(dtableEventsHistory);
  handlerButtonsEvents(dtableEvents,dtableEventsHistory);
  //handlerFormsEvents(dtableEvents,dtableEventsHistory);
}


//////////////////////////////////////////////////////////////
//
//  Events
//
//////////////////////////////////////////////////////////////

function loadEvents() {
  $.ajax({
    type: "POST",
    url: "views/events.html",
    dataType: 'text',
    success: function(result){
      $('#conteudo').html(result);
      //$('#breadcrumbEvents').text("Atividade: " + activitytitle);
      //$('#breadcrumbEvents').attr("href", "?activity=" + activityid + "&title=" + activitytitle);
      prepareEvents();
    }
  });
}

function prepareEvents() {
  var dtableEvents = createTableEvents();
  var dtableEventsHistory = createTableEventsHistory();
  populateTablesEvents(dtableEvents,dtableEventsHistory);
  handlerTableEvents(dtableEvents);
  handlerTableEventsHistory(dtableEventsHistory);
  handlerButtonsEvents(dtableEvents,dtableEventsHistory);
  //handlerFormsEvents(dtableEvents,dtableEventsHistory);
}

function createTableEvents() {
  return $('#tableEvents').DataTable( {
      orderCellsHome: true,
      fixedHeader: true,
      paginate: false,
      select : false,
      columns: [
        { title: "Data",  width: "10%", data: "begin" },
        { title: "Nome",  width: "10%", data: "name" },
        { title: "Dias",  width: "10%", data: "ndays" },
        { title: "Título",width: "70%", data: "title" }
      ],
      columnDefs: [
        {
          targets: [0,1,2],
          className: 'dt-center'
        }
      ],
      initComplete: function () {
        $('#tableEvents thead tr')
          .clone(true)
          .addClass('filters')
          .appendTo('#tableEvents thead');
        $('#tableEvents thead tr.filters th')
          .off('click')
          .removeClass('sorting')
          .removeClass('sorting_asc');
        var tableEvents = this.api();
        tableEvents
          .columns()
          .eq(0)
          .each(function (colIdx) {
            var cell = $('#tableEvents thead tr.filters th').eq(
              $(tableEvents.column(colIdx).header()).index()
            );
            var title = $(cell).text();
            $(cell).html('<input type="text" name="filter" style="width: 100%" />');
            $('input', $('#tableEvents thead tr.filters th').eq($(tableEvents.column(colIdx).header()).index()))
              .off('keyup change')
              .on('keyup change', function (e) {
                e.stopPropagation();
                $(this).attr('title', $(this).val());
                var regexr = '({search})';
                var cursorPosition = this.selectionStart;
                tableEvents
                  .column(colIdx)
                  .search(
                    this.value != ''
                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                        : '',
                    this.value != '',
                    this.value == ''
                  )
                  .draw();
                $(this)
                  .focus()[0]
                  .setSelectionRange(cursorPosition, cursorPosition);
              });
          });
      }  
    });
}

function createTableEventsHistory() {
  return $('#tableEventsHistory').DataTable( {
      orderCellsHome: true,
      fixedHeader: true,
      paginate: false,
      select : false,
      columns: [
        { title: "Data",  width: "10%", data: "begin" },
        { title: "Nome",  width: "10%", data: "name" },
        { title: "Dias",  width: "10%", data: "ndays" },
        { title: "Título",width: "70%", data: "title" }
      ],
      columnDefs: [
        {
          targets: [0,1,2],
          className: 'dt-center'
        }
      ],
      initComplete: function () {
        $('#tableEventsHistory thead tr')
          .clone(true)
          .addClass('filters')
          .appendTo('#tableEventsHistory thead');
        $('#tableEventsHistory thead tr.filters th')
          .off('click')
          .removeClass('sorting')
          .removeClass('sorting_asc');
        var tableEventsHistory = this.api();
        tableEventsHistory
          .columns()
          .eq(0)
          .each(function (colIdx) {
            var cell = $('#tableEventsHistory thead tr.filters th').eq(
              $(tableEventsHistory.column(colIdx).header()).index()
            );
            var title = $(cell).text();
            $(cell).html('<input type="text" name="filter" style="width: 100%" />');
            $('input', $('#tableEventsHistory thead tr.filters th').eq($(tableEventsHistory.column(colIdx).header()).index()))
              .off('keyup change')
              .on('keyup change', function (e) {
                e.stopPropagation();
                $(this).attr('title', $(this).val());
                var regexr = '({search})';
                var cursorPosition = this.selectionStart;
                tableEventsHistory
                  .column(colIdx)
                  .search(
                    this.value != ''
                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                        : '',
                    this.value != '',
                    this.value == ''
                  )
                  .draw();
                $(this)
                  .focus()[0]
                  .setSelectionRange(cursorPosition, cursorPosition);
              });
          });
      }  
    });
}

function populateTablesEvents(dtableEvents,dtableEventsHistory) {
  const params = {activity: activityid};  
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tableevents.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      dtableEvents.rows.add(result.events);
      dtableEvents.draw();
      dtableEventsHistory.rows.add(result.history);
      dtableEventsHistory.draw();
    }
  });
}

function handlerTableEvents(dtableEvents) {
  $('#tableEvents tbody').on('click', 'tr', function () {
    var data = dtableEvents.row( this ).data();
    eventdate  = data.begin;
    eventname  = data.name;
    eventtitle = data.title;
    eventyear  = eventdate.split("-")[0];
    eventmonth = eventdate.split("-")[1];
    eventday   = eventdate.split("-")[2];
    eventid    = eventyear + '/' + eventmonth + '/' + eventday + '/' + eventname;
    loadEventDetails();
  });
}

function handlerTableEventsHistory(dtableEventsHistory) {
  $('#tableEventsHistory tbody').on('click', 'tr', function () {
    var data = dtableEventsHistory.row( this ).data();
    eventdate  = data.begin;
    eventname  = data.name;
    eventtitle = data.title;
    eventyear  = eventdate.split("-")[0];
    eventmonth = eventdate.split("-")[1];
    eventday   = eventdate.split("-")[2];
    eventid    = eventyear + '/' + eventmonth + '/' + eventday + '/' + eventname;
    loadEventDetails();
  });
}

function handlerButtonsEvents(dtableEvents,dtableEventsHistory) {
  $('#cloneActivity').on('click', function(){
    $('#modalCloneActivity').modal('show');
    $('#activityClone').val(activityid);
    $('#activityTitle').val(activitytitle);
  });  
  $('#cancelCloneActivity').on('click', function(){
    $('#modalCloneActivity').modal('hide');
  });  
  $('#clearEventsFilter').on('click', function(){
    dtableEvents
        .search( '' )
        .columns().search( '' )
        .draw();
    dtableEventsHistory
        .search( '' )
        .columns().search( '' )
        .draw();
    $('input[name="filter"]').val( '' );
  });
}

function handlerFormsEvents(dtableEvents,dtableEventsHistory) {
  var formCloneActivity = document.getElementById('formCloneActivity');
  formCloneActivity.addEventListener('submit', function (event) {
      event.preventDefault();
      event.stopPropagation();
      inputFields = convertFormToJSON(formCloneActivity);
      if( test===true )
        inputFields.test = true;
      $.ajax({
        type: "POST",
        url: "../server/manage/cloneactivity.php",
        cache: false,
        dataType: 'json',
        data: JSON.stringify(inputFields),
        success: function(result){
          $('#modalCloneActivity').modal('hide');
        }
      });   
  }, false)
}

//////////////////////////////////////////////////////////////
//
//  Event details
//
//////////////////////////////////////////////////////////////

function loadEventDetails() {
  // load the event details page
  $.ajax({
    type: "get",
    url: "views/eventdetails.html",
    async: true,
    success: function(result){
      $('#conteudo').html(result);
      //$('#breadcrumbEvents').text("Atividade: " + activitytitle);
      //$('#breadcrumbEvents').attr("href", "?activity=" + activityid + "&title=" + activitytitle);
      $('#breadcrumbEvent').text("Evento: " + eventdate);
      $('#breadcrumbEvent').attr("href", "?event=" + eventid + "&title=" + eventtitle + "&date=" + eventdate + "&lastTabPaneEvent=" + lastTabPaneEvent);
      if( lastTabPaneEvent!==undefined )
        activateTabPaneById(lastTabPaneEvent);

      const urlhtml = '../event/' + eventid + '/index.html';
      const urljson = '../../event/' + eventid + '/config.json';
      createBookingColumns(urlhtml)
      .then( () => {
        prepareEventDetails(urlhtml,urljson);
      })
      .catch((error) => {
          console.log(error)
      })
    }
  });
}

function createBookingColumns(urlhtml) {

  return new Promise((resolve, reject) => {
    // Prepare columns for table Bookings
    // Global variable
    bcolumns = [];
    activityinputids = [];
    activityinputnames = [];
    activityinputradiovalues = [];
    fetch(urlhtml, { cache: 'no-store' })
      .then((response) => response.text())
      .then((text) => new DOMParser().parseFromString(text, "text/html"))
      .then((dom) => dom.getElementById("formBooking"))
      /*
      // debug
      .then(dom => {
        console.log(dom.getElementById("formBooking").innerHTML);
        return dom.getElementById("formBooking");
      })
      */
      .then((formBooking) => {
        formBooking.querySelectorAll('input[type="text"]').forEach( input => {
          if(input.id) {
            activityinputids.push(input.id);
            arr = input.id.split(".");
            activityinputnames.push( arr[0] ); // remove value from id for radios, checkboxes ...
          }
        });
        formBooking.querySelectorAll('input[type="email"]').forEach( input => {
          if(input.id) {
            activityinputids.push(input.id);
            arr = input.id.split(".");
            activityinputnames.push( arr[0] ); // remove value from id for radios, checkboxes ...
          }
        });
        formBooking.querySelectorAll('input[type="radio"]').forEach( input => {
          //console.log(this.constructor.name); // Window
          if(input.id) {
            activityinputids.push(input.id);
            arr = input.id.split(".");
            activityinputnames.push( arr[0] ); // remove value from id for radios, checkboxes ...
            if( arr.length>1 ) {
              if( activityinputradiovalues[arr[0]]===undefined ) activityinputradiovalues[arr[0]] = [];
              activityinputradiovalues[arr[0]].push(arr[1]);
            }
          }
        });
        formBooking.querySelectorAll('input[type="checkbox"]').forEach( input => {
          //console.log(this.constructor.name); // Window
          if(input.id) {
            activityinputids.push(input.id);
            arr = input.id.split(".");
            activityinputnames.push( arr[0] ); // remove value from id for radios, checkboxes ...
            if( arr.length>1 ) {
              if( activityinputradiovalues[arr[0]]===undefined ) activityinputradiovalues[arr[0]] = [];
              activityinputradiovalues[arr[0]].push(arr[1]);
            }
          }
        });
        formBooking.querySelectorAll('input[type="hidden"]').forEach( input => {
          if(input.id) {
            activityinputids.push(input.id);
            arr = input.id.split(".");
            activityinputnames.push( arr[0] ); // remove value from id for radios, checkboxes ...
          }
        });
        // unique input names (without appended value)
        activityinputnames = Array.from(new Set(activityinputnames));
        //
        // booking columns selection and order
        //
        bcolumns.push({ title: "created", width: "10%", data: "created" }); 
        bcolumns.push({ title: "pack",    width: "4%",  data: "packnumber" }); 
        bcolumns.push({ title: "number",  width: "4%",  data: "number" }); 
        $.each( activityinputnames, function( key, val ) {
          if( val=="terms" || val=="policy" ) return;
          bcolumns.push({ title: val, width: "4%", data: val });
          if( val=="name" ) {
            bcolumns.push({ title: "price",   width: "4%",  data: "price" }); 
            bcolumns.push({ title: "deposit", width: "4%",  data: "deposit" }); 
            bcolumns.push({ title: "paid",    width: "4%",  data: "paid" }); 
            bcolumns.push({ title: "rooms",   width: "4%",  data: "rooms" }); 
          } else if( val=="email" ) {
            bcolumns.push({ title: "lang",    width: "4%",  data: "lang" }); 
          }
        });
        resolve(bcolumns);
      })
      .catch(error => {
          if (typeof error.json === "function") {
              error.json().then(jsonError => {
                  console.log("Json error from API");
                  console.log(jsonError);
              }).catch(genericError => {
                  console.log("Generic error from API");
                  console.log(error.statusText);
              });
          } else {
              console.log("Fetch error");
              console.log(error);
          }
          reject(error);
      });
  })
}

function prepareEventDetails(urlhtml,urljson) {
  prepareEventResources();
  prepareEventBookings(urlhtml,urljson);
  prepareEventPayments();
  prepareEventEmails();
  prepareEventLogs();
  prepareEventConfig();
  //handlerTableEvents(dtableEvents);
  //handlerTableEventsHistory(dtableEventsHistory);
  //handlerButtonsEventDetails(dtablesessions,dtablemeals,dtableaccommodations);
  //handlerFormsEventDetails();
}

//////////////////////////////////////////////////////////////
//
//  Event Resources
//
//////////////////////////////////////////////////////////////

function prepareEventResources() {
  // Prepare resources table
  const params = {event: eventid};  
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/getintervals.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      var intervals = [];
      biggest="";
      length=0;
      var tfoot = '<tfoot><tr><td></td><td></td><td class="columnTotal"></td><td class="columnSum"></td><td class="columnSum"></td>';
      $.each( result, function( key, val ) {
        intervals[key] = val.length;            
        if(val.length > length) { biggest = key; length = val.length; }
        tfoot += '<td class="columnSum"></td>';
      });
      tfoot += '<td></td></tr></tfoot>';
      var columns = [];
      columns.push({ title: "Room", width: "10%" });
      columns.push({ title: "Type", width: "10%" });
      columns.push({ title: "Capacity", width: "10%" });
      columns.push({ title: "Quantity", width: "10%" });
      columns.push({ title: "Full_Bookings", width: "10%" });
      $.each( result[biggest], function( key, val ) {
        columns.push({ title: val, width: "10%" });
      });
      columns.push({ title: "Bookings", width: "10%" });

      const params = {event: eventid};  
      if( test===true )
        params.test = true;
      $.ajax({
        type: "POST",
        url: "../server/manage/check.php",
        dataType: 'json',
        data: JSON.stringify(params),
        success: function(result){
          Object.keys(intervals).forEach(key => {
            //console.log(key);
            //console.log(intervals[key]);
            let dtable = createTableEventResource(key,columns,tfoot);
            populateTablesEventResource(key,dtable,columns,result);
            handlerButtonsEventResource(key,dtable);
          });
        }
      });
    }
  });
}

function createTableEventResource(key,columns,tfoot) {
  const name = key.slice(2);
  const container = document.getElementById("tablesResource");

  const html = `
    <div class="card-body">
        <p id="pageEvent_p${name}Title"></p>
        <div class="datatable table-responsive">
            <table class="display" id="tableInfo${name}" width="100%" cellspacing="0"><caption>${name}</caption></table>
        </div>
    </div>
  `;
  container.insertAdjacentHTML('beforeend', html);
  $(`#tableInfo${name}`).append(tfoot);
  return $(`#tableInfo${name}`).DataTable( {
    ordering: false,
    fixedHeader: true,
    paginate: false,
    searching: false,
    info: false,
    select : false,
    columns: columns,
    columnDefs: [
      { targets: [0],   className: 'dt-head-left dt-body-left' },
      { targets: '_all',className: 'dt-center' }
    ],
    footerCallback: function ( row, data, start, end, display ) {
      var api = this.api();

      $( api.column( 3 ).footer() ).html('Total: ');
      const count = columns.length;
      for (let i = 4; i < count-1; i++) {
        total = api
            .column( i )
            .data()
            .reduce( function (a, b) {
              if ( typeof(a) === "undefined" && a === null ) a = 0;
              if ( typeof(b) === "undefined" && b === null ) b = 0;
              return parseInt(a) + parseInt(b);
            }, 0 );
        $( api.column( i ).footer() ).html( parseInt(total) || 0 );
      }
    }
  });
}

function populateTablesEventResource(key,dtable,columns,result) {
  var name = key.slice(2);
  $.each( result["s_" + name], function( key, val ) {
    row = [];
    row.push(key);
    row.push(val.value);
    row.push(val.capacity);
    row.push(val.quantity);
    row.push(val.nbookings);
    $.each( columns, function( key2, val2 ) {
      if( key2<5 ) return true;
      if( val.intervals[val2.title]!==undefined && val.intervals[val2.title].nbookings!==undefined )  
        row.push(val.nbookings + val.intervals[val2.title].nbookings);
      else
        row.push("-");
    });
    row.pop();
    let bookings="";
    let count=0;
    $.each( val.bookings, function( key2, val2 ) {
      bookings += val2 + " ";
      count++;
      if( count==4 ) {
        bookings += "...";
        return;
      }
    });
    row.push(bookings);
    dtable.row.add(row);
  });
  dtable.draw();
}

function handlerButtonsEventResource(dtablesessions,dtablemeals,dtableaccommodations) {
  $('#clearEventResourcesFilter').on('click', function(){
    dtablesessions
        .search( '' )
        .columns().search( '' )
        .draw();
    dtablemeals
        .search( '' )
        .columns().search( '' )
        .draw();
    dtableaccommodations
        .search( '' )
        .columns().search( '' )
        .draw();
    $('input[name="filter"]').val( '' );
  });
}



/*
function createTableSessions(columns) {
  $('#tableActivityInfoSessions').append('<tfoot><tr><td></td><td></td><td class="columnTotal"></td><td class="columnSum"></td><td class="columnSum"></td></tr></tfoot>');
  return $('#tableActivityInfoSessions').DataTable( {
    ordering: false,
    fixedHeader: true,
    paginate: false,
    searching: false,
    info: false,
    select : false,
    columns: columns,
    columnDefs: [
      { targets: [0],   className: 'dt-head-left dt-body-left' },
      { targets: '_all',className: 'dt-center' }
    ],
    footerCallback: function ( row, data, start, end, display ) {
      var api = this.api();

      $( api.column( 2 ).footer() ).html('Total: ');
      total = api
          .column( 3 )
          .data()
          .reduce( function (a, b) {
            if ( typeof(a) === "undefined" && a === null) a = 0;
            if ( typeof(b) === "undefined" && b === null) b = 0;
            return parseInt(a) + parseInt(b);
          }, 0 );
      $( api.column( 3 ).footer() ).html( parseInt(total) || 0 );
    }
  });
}

function createTableMeals(columns) {
  $('#tableActivityInfoMeals').append('<tfoot><tr><td></td><td class="columnTotal"></td><td class="columnSum"></td><td class="columnSum"></td></tr></tfoot>');
  return $('#tableActivityInfoMeals').DataTable( {
    ordering: false,
    fixedHeader: true,
    paginate: false,
    searching: false,
    info: false,
    select : false,
    columns: columns,
    columnDefs: [
      { targets: [0],   className: 'dt-head-left dt-body-left' },
      { targets: '_all',className: 'dt-center' }
    ],
    footerCallback: function ( row, data, start, end, display ) {
      var api = this.api();

      $( api.column( 2 ).footer() ).html('Total: ');
      total = api
          .column( 3 )
          .data()
          .reduce( function (a, b) {
            if ( typeof(a) === "undefined" && a === null) a = 0;
            if ( typeof(b) === "undefined" && b === null) b = 0;
            return parseInt(a) + parseInt(b);
          }, 0 );
      $( api.column( 3 ).footer() ).html( parseInt(total) || 0 );
    }
  });
}

function createTableAccommodations(columns) {
  $('#tableActivityInfoAccommodations').append('<tfoot><tr><td></td><td class="columnTotal"></td><td class="columnSum"></td><td class="columnSum"></td></tr></tfoot>');
  return $('#tableActivityInfoAccommodations').DataTable( {
    ordering: false,
    fixedHeader: true,
    paginate: false,
    searching: false,
    info: false,
    select : false,
    columns: columns,
    columnDefs: [
      { targets: [0],   className: 'dt-head-left dt-body-left' },
      { targets: '_all',className: 'dt-center' }
    ],
    footerCallback: function ( row, data, start, end, display ) {
      var api = this.api();

      $( api.column( 2 ).footer() ).html('Total: ');
      total = api
          .column( 3 )
          .data()
          .reduce( function (a, b) {
            if ( typeof(a) === "undefined" && a === null) a = 0;
            if ( typeof(b) === "undefined" && b === null) b = 0;
            return parseInt(a) + parseInt(b);
          }, 0 );
      $( api.column( 3 ).footer() ).html( parseInt(total) || 0 );
    }
  });
}

function populateTablesEventResources(dtablesessions,dtablemeals,dtableaccommodations,columns) {
  $.ajax({
    type: "POST",
    url: "../server/manage/check.php",
    dataType: 'json',
    data: JSON.stringify({"event": eventid}),
    success: function(result){
      // Sessions
      $.each( result.s_Session, function( key, val ) {
        row = [];
        row.push(key);
        row.push(val.value);
        row.push(val.capacity);
        row.push(val.quantity);
        row.push(val.nbookings);
        $.each( columns, function( key2, val2 ) {
          if( key2<5 ) return true;
          if( val.intervals[val2.title]!==undefined && val.intervals[val2.title].nbookings!==undefined )  
            row.push(val.nbookings + val.intervals[val2.title].nbookings);
          else
            row.push("-");
        });
        dtablesessions.row.add(row);
      });
      dtablesessions.draw();
      // Meals
      $.each( result.s_Meal, function( key, val ) {
        row = [];
        row.push(key);
        row.push(val.value);
        row.push(val.capacity);
        row.push(val.quantity);
        row.push(val.nbookings);
        $.each( columns, function( key2, val2 ) {
          if( key2<5 ) return true;
          if( val.intervals[val2.title]!==undefined && val.intervals[val2.title].nbookings!==undefined )  
            row.push(val.nbookings + val.intervals[val2.title].nbookings);
          else
            row.push("-");
        });
        dtablemeals.row.add(row);
      });
      dtablemeals.draw();
      // Accommodations
      $.each( result.s_Accommodation, function( key, val ) {
        row = [];
        row.push(key);
        if( val.type == "valueXOR" && val.nbookings>0 ) {
          row.push(val.value[val.selected]);
          row.push(val.capacity[val.selected]);
        } else {
          row.push(val.value);
          row.push(val.capacity);
        }
        row.push(val.quantity);
        row.push(val.nbookings);
        $.each( columns, function( key2, val2 ) {
          if( key2<5 ) return true;
          if( val.intervals[val2.title]!==undefined && val.intervals[val2.title].nbookings!==undefined )  
            row.push(val.nbookings + val.intervals[val2.title].nbookings);
          else
            row.push("-");
        });
        dtableaccommodations.row.add(row);
      });
      dtableaccommodations.draw();
    }
  });
}
*/
//////////////////////////////////////////////////////////////
//
//  Event Bookings
//
//////////////////////////////////////////////////////////////

function prepareEventBookings(urlhtml,urljson) {
  var dtableEventBookings = createTableEventBookings();
  populateTableEventBookings(dtableEventBookings);
  handlerTableEventBookings(dtableEventBookings);
  handlerButtonsEventBookings(dtableEventBookings,urlhtml,urljson);
  handlerFormsEventBookings(dtableEventBookings);
}

function createTableEventBookings() {
  var tfoot = '<tfoot><tr><td></td><td></td><td></td><td class="columnTotal"></td><td class="columnSum"></td><td class="columnSum"></td><td class="columnSum"></td></tr></tfoot>';
  $(`#tableEventBookings`).append(tfoot);

  return $('#tableEventBookings').DataTable( {
    orderCellsHome: true,
    fixedHeader: true,
    paginate: false,
    select : false,
    columns: bcolumns,
    columnDefs: [
      { targets: '_all', className: 'dt-center' }
    ],
    footerCallback: function ( row, data, start, end, display ) {
      var api = this.api();

      $( api.column( 3 ).footer() ).html('Total: ');
      //const count = columns.length;
      for (let i = 4; i < 7; i++) {
        total = api
            .column( i, { search: 'applied' } )
            .data()
            .reduce( function (a, b) {
              if ( typeof(a) === "undefined" && a === null) a = 0;
              if ( typeof(b) === "undefined" && b === null) b = 0;
              return parseFloat(a) + parseFloat(b);
            }, 0 );
        $( api.column( i ).footer() ).html( parseFloat(total).toFixed(2) || 0 );
      }
    },
    initComplete: function () {
      $('#tableEventBookings thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tableEventBookings thead');
      $('#tableEventBookings thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      var tableBookings = this.api();
      tableBookings
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('#tableEventBookings thead tr.filters th').eq(
            $(tableBookings.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $('input', $('#tableEventBookings thead tr.filters th').eq($(tableBookings.column(colIdx).header()).index()))
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              tableBookings
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
    }  
  });
}

function populateTableEventBookings(dtableEventBookings) {
  dtableEventBookings.clear();
  const params = {event: eventid};  
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tablebookings.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      dtableEventBookings.clear();
      $.each( result.rows, function( key, val ) {
          const rowObject = {};
          $.each( bcolumns, function( key2, val2 ) {
            if ( val[val2.data] !== undefined ) {
              rowObject[val2.data] = val[val2.data];
            } else if (JSON.parse(val.metadata)[val2.data] !== undefined) {
              rowObject[val2.data] = JSON.parse(val.metadata)[val2.data];
            } else {
              rowObject[val2.data] = "";
            }
          });
          dtableEventBookings.row.add(rowObject).draw();          
      });
      dtableEventBookings.draw();
    }
  });
}

function handlerTableEventBookings(dtableEventBookings) {
  $('#tableEventBookings tbody').on('click', 'tr', function () {
    var data = dtableEventBookings.row( this ).data();
    packnumber    = data.packnumber;
    bookingnumber = data.number;
    loadPackDetails();
  });

}

function handlerButtonsEventBookings(dtableEventBookings,urlhtml,urljson) {
  // Get IDs of inputs from formBooking of respective activity html
  $('#buttonBookingCreate').on('click', function(){
    // 1. Open event.html in new tab
    const newWindow = window.open('event/index.html?title=' + eventtitle + '&config=' + urljson, '_blank');
    // 2. Load urlhtml, extract its body
    fetch(urlhtml + '?t=' + Date.now(), { cache: 'no-store' })
      .then(response => response.text())
      .then(fullHtml => {
        const parser = new DOMParser();
        const doc = parser.parseFromString(fullHtml, 'text/html');

        // Remove all <script> tags inside body
        doc.body.querySelectorAll('script').forEach(script => script.remove());
        // Show private fields
        doc.body.querySelectorAll('div[name="private"]').forEach(div => {
          div.classList.remove('d-none');
        });      
       
        const bodyContent = doc.body.innerHTML;
        // 3. Function to send body content to event.html
        const sendContent = () => {
          newWindow.postMessage({
            type: 'injectBody',
            html: bodyContent
          }, window.location.origin);
        };

        // Send after event.html is loaded or fallback after delay
        newWindow.addEventListener('load', sendContent);
        setTimeout(sendContent, 1000);
      });

      /*
    fetch(url)
      .then(response => response.text())
      .then(fullHtml => {
        const parser = new DOMParser();
        const doc = parser.parseFromString(fullHtml, 'text/html');

        // Remove all scripts in body
        doc.body.querySelectorAll('script').forEach(script => script.remove());

        const bodyContent = doc.body.innerHTML;
        document.getElementById('app').innerHTML = bodyContent;
      });
      */
  });
  $('#buttonSessionLinkSend').on('click', function(){
    $('#modalSendSessionLink').modal('show');
    $('#SessionLink').val("");
    // DOM nodes: filteredNodes = dtableEventBookings.rows({ search: 'applied' }).nodes();
    filteredrows = dtableEventBookings.rows( {search:'applied'} ).data();
//console.log(filteredrows);
    let nremote = filteredrows.toArray().filter(row => row.s_Session === "remote").length;
    remotelinks.forEach(item => {
      let tsessionrows = filteredrows.toArray().filter(row => (row.s_Session === "remote" && row.t_Session === item.t_Session));
      count = tsessionrows.length;
      item.nbookings = count;
      let bnumbers = [];
      tsessionrows.forEach( row => {
        bnumbers.push(row.number);
      });
      item.bookings = bnumbers;
    });
//console.log(remotelinks);
    document.getElementById('SessionLink').textContent = JSON.stringify(remotelinks, null, 2);
console.log(document.getElementById('SessionLink').textContent);
    //$('#SessionLink').val(JSON.stringify(remotelinks));
    $('#SessionLinkSendQuantity').val(nremote);
  });
  $('#cancelSessionLinkSend').on('click', function(){
    $('#modalSendSessionLink').modal('hide');
  });  

  $('#buttonRequestDepositPayment').on('click', function(){
    $('#modalRequestPaymentDeposit').modal('show');
    $('#SessionLink').val("");
    filteredrows = dtableEventBookings.rows( {search:'applied'} ).data();
    var rows = filteredrows.toArray().filter(row => row.paid < row.deposit);
    let nremote = rows.length;
    let drows = [];
    rows.forEach(row => {
      let id = {
        packnumber: row.packnumber,
        number: row.number
      };
      drows.push(id);
    });
    document.getElementById('PaymentDeposit').textContent = JSON.stringify(drows, null, 2);
    $('#RequestPaymentDepositQuantity').val(nremote);
  });
  $('#cancelRequestPaymentDeposit').on('click', function(){
    $('#modalRequestPaymentDeposit').modal('hide');
  });  

  $('#buttonRequestFullPayment').on('click', function(){
    $('#modalRequestPaymentFull').modal('show');
    $('#SessionLink').val("");
    filteredrows = dtableEventBookings.rows( {search:'applied'} ).data();
    var rows = filteredrows.toArray().filter(row => row.paid < row.price);
    let nremote = rows.length;
    let drows = [];
    rows.forEach(row => {
      let id = {
        packnumber: row.packnumber,
        number: row.number
      };
      drows.push(id);
    });
    document.getElementById('PaymentFull').textContent = JSON.stringify(drows, null, 2);
    $('#RequestPaymentFullQuantity').val(nremote);
  });
  $('#cancelRequestPaymentFull').on('click', function(){
    $('#modalRequestPaymentFull').modal('hide');
  });  

  $('#buttonGenerateBadges').on('click', function(){
    filteredrows = dtableEventBookings.rows( {search:'applied'} ).data();
    let numbers = [];
    filteredrows.toArray().forEach(row => {
      numbers.push(row.number);
    });
    // 1. Create a form element
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '../server/manage/badges.php';
    form.target = '_blank';

    // 2. Create a hidden input with JSON-encoded attendees
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'event';
    input.value = eventid;
    form.appendChild(input);
    const input2 = document.createElement('input');
    input2.type = 'hidden';
    input2.name = 'numbers';
    input2.value = JSON.stringify(numbers);
    form.appendChild(input2);

    // 3. Add to body and submit
    document.body.appendChild(form);
    form.submit();

    // 4. Clean up
    document.body.removeChild(form);
  });

  $('#buttonGenerateCSV').on('click', function(){
    const header = [];
    // Get header texts
    $('#tableEventBookings thead th').each(function () {
      header.push($(this).text().trim());
    });
    const rows = [];
    // Loop through filtered/visible rows
    dtableEventBookings.rows({ search: 'applied' }).every(function () {
      const row = [];
      const rowIdx = this.index();

      dtableEventBookings.columns().every(function (colIdx) {
        const cellData = dtableEventBookings.cell(rowIdx, colIdx).render('display');
        row.push(cellData);
      });

      rows.push(row);
    });

    // Build CSV
    let csv = '';
    csv += header.join(',') + '\n';
    rows.forEach(row => {
      csv += row.map(cell => `"${cell}"`).join(',') + '\n';
    });

    // UTF-8 BOM for Excel compatibility
    const bom = '\uFEFF';
    const blob = new Blob([bom + csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);

    const link = document.createElement("a");
    link.setAttribute("href", url);
    link.setAttribute("download", "bookings.csv");
    link.style.display = "none";

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  });


  $('#buttonCompactExpand').on('click', function(){
    const params = {event: eventid};  
    if( test===true )
      params.test = true;
    $.ajax({
      type: "POST",
      url: "../server/manage/bookingfieldsexpanded.php",
      dataType: 'json',
      data: JSON.stringify(params),
      success: function(result){
        const hiddenDataFields = result;
        if (hiddenDataFields === undefined || hiddenDataFields.length == 0) return;

        const columnDefs = dtableEventBookings.settings().init().columns;

        // Check visibility of the first column to determine toggle direction
        const firstIndex = columnDefs.findIndex(col => col.data === hiddenDataFields[0]);
        if (firstIndex === -1) {
          console.warn(`First column not found: ${hiddenDataFields[0]}`);
          return;
        }

        const visible = !dtableEventBookings.column(firstIndex).visible();

        hiddenDataFields.forEach(dataName => {
          const columnIndex = columnDefs.findIndex(col => col.data === dataName);
          if (columnIndex >= 0) {
            // Toggle DataTable column visibility
            dtableEventBookings.column(columnIndex).visible(visible);

            // Toggle header cell
            $(dtableEventBookings.column(columnIndex).header()).css('display', visible ? '' : 'none');

            // Toggle filter row header if exists
            const headerRows = $(dtableEventBookings.table().header()).find('tr');
            if (headerRows.length > 1) {
              const filterCell = headerRows.eq(1).find('th').eq(columnIndex);
              if (filterCell.length) {
                filterCell.css('display', visible ? '' : 'none');
              }
            }
          } else {
            console.warn(`Column with data="${dataName}" not found.`);
          }
        });
      }
    });
  });

  $('#cleaEventBookingsrFilter').on('click', function(){
    dtableEventBookings
        .search( '' )
        .columns().search( '' )
        .draw();
    $('input[name="filter"]').val( '' );
  });

  // Save last tab 
  $('#pillsEventResources_button').on('click', function(){
    lastTabPaneEvent = "pillsEventResources_tab";
  });
  $('#pillsEventBookings_button').on('click', function(){
    lastTabPaneEvent = "pillsEventBookings_tab";
  });
  $('#pillsEventConfig_button').on('click', function(){
    lastTabPaneEvent = "pillsEventConfig_tab";
  });
}

function handlerFormsEventBookings(dtableEventBookings) {
  var formSessionLinkSend = document.getElementById('formSessionLinkSend');
  formSessionLinkSend.addEventListener('submit', function (event) {
      event.preventDefault();
      event.stopPropagation();
      const params = {event: eventid, links: JSON.parse(document.getElementById('SessionLink').textContent)};  
      if( test===true )
        params.test = true;
      $.ajax({
        type: "POST",
        url: "../server/manage/emailsendlink.php",
        cache: false,
        dataType: 'json',
        data: JSON.stringify(params),
        success: function(result){
          $('#modalSendSessionLink').modal('hide');
        }
      });   
  }, false);
  var formRequestPaymentDeposit = document.getElementById('formRequestPaymentDeposit');
  formRequestPaymentDeposit.addEventListener('submit', function (event) {
      event.preventDefault();
      event.stopPropagation();
      const params = {event: eventid, rows: JSON.parse(document.getElementById('PaymentDeposit').textContent)};  
      if( test===true )
        params.test = true;
      $.ajax({
        type: "POST",
        url: "../server/manage/emailpaymentdeposit.php",
        cache: false,
        dataType: 'json',
        data: JSON.stringify(params),
        success: function(result){
          $('#modalRequestPaymentDeposit').modal('hide');
        }
      });   
  }, false);
  var formRequestPaymentFull = document.getElementById('formRequestPaymentFull');
  formRequestPaymentFull.addEventListener('submit', function (event) {
      event.preventDefault();
      event.stopPropagation();
      const params = {event: eventid, rows: JSON.parse(document.getElementById('PaymentFull').textContent)};  
      if( test===true )
        params.test = true;
      $.ajax({
        type: "POST",
        url: "../server/manage/emailpaymentfull.php",
        cache: false,
        dataType: 'json',
        data: JSON.stringify(params),
        success: function(result){
          $('#modalRequestPaymentFull').modal('hide');
        }
      });   
  }, false);
}

//////////////////////////////////////////////////////////////
//
//  Event Payments
//
//////////////////////////////////////////////////////////////

function prepareEventPayments() {
  var dtablePayments = createTableEventPayments();
  populateTableEventPayments(dtablePayments);
  //handlerTableEventPayments(dtablePayments);
  //handlerButtonsEventPayments(dtablePayments);
  //handlerFormsEventPayments(dtablePayments);
}

function createTableEventPayments() {
  return $('#tableEventPayments').DataTable( {
    orderCellsHome: true,
    fixedHeader: true,
    paginate: false,
    select : false,
    columns: [
      { title: "Date",  width: "4%", data: "date" },
      { title: "Provider",  width: "2%", data: "provider" },
      { title: "Number",  width: "2%", data: "number" },
      { title: "Value",  width: "2%", data: "value" },
      { title: "Method",  width: "5%", data: "method" }
    ],
    initComplete: function () {
      $('#tableEventPayments thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tableEventPayments thead');
      $('#tableEventPayments thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      var tableEventPayments = this.api();
      tableEventPayments
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('#tableEventPayments thead tr.filters th').eq(
            $(tableEventPayments.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $('input', $('#tableEventPayments thead tr.filters th').eq($(tableEventPayments.column(colIdx).header()).index()))
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              tableEventPayments
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
    }  
  });
}

function populateTableEventPayments(dtableEventPayments) {
  const params = {event: eventid};  
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tablepayments.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      dtableEventPayments.clear();
      if( result.easypay!=undefined )
        $.each( result.easypay.orders, function( key, val ) {
          const rowObject = {};
          rowObject.date = val.date;
          rowObject.provider = "easypay";
          rowObject.number = val.number;
          rowObject.value = val.value;
          rowObject.method = val.method;
          dtableEventPayments.row.add(rowObject).draw();          
        });
      if( result.tpa!=undefined )
        $.each( result.tpa.orders, function( key, val ) {
          const rowObject = {};
          rowObject.date = val.date;
          rowObject.provider = "tpa";
          rowObject.number = val.number;
          rowObject.value = val.value;
          rowObject.method = val.method;
          dtableEventPayments.row.add(rowObject).draw();          
        });
      if( result.cash!=undefined )
        $.each( result.cash.orders, function( key, val ) {
          const rowObject = {};
          rowObject.date = val.date;
          rowObject.provider = "cash";
          rowObject.number = val.number;
          rowObject.value = val.value;
          rowObject.method = val.method;
          dtableEventPayments.row.add(rowObject).draw();          
        });
      dtableEventPayments.draw();
    }
  });
}

//////////////////////////////////////////////////////////////
//
//  Event Emails
//
//////////////////////////////////////////////////////////////

function prepareEventEmails() {
  var dtableEmails = createTableEventEmails();
  populateTableEventEmails(dtableEmails);
  handlerTableEventEmails(dtableEmails);
  handlerButtonsEventEmails(dtableEmails);
  handlerFormsEventEmails(dtableEmails);
}

function createTableEventEmails() {
  var ecolumns = [];
  ecolumns.push({ title: "Created", width: "10%", data: "created" });
  ecolumns.push({ title: "Type", width: "10%", data: "type" });
  ecolumns.push({ title: "Number", width: "10%", data: "number" });
  ecolumns.push({ title: "To", width: "20%", data: "to" });
  ecolumns.push({ title: "Subject", width: "20%", data: "subject" });
  ecolumns.push({ title: "Body", width: "40%", data: "body",
    render: function(data, type, row, meta) {
        if (type === 'display' && data) {
            // Extract <body>...</body> manually
            let bodyMatch = data.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
            let bodyHTML = bodyMatch ? bodyMatch[1] : data;

            // Temporary element to parse HTML and extract visible text
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = bodyHTML;
            // Get plain text (contents of <span> and other inline tags are preserved as text)
            let plainText = tempDiv.textContent || "";
            plainText = plainText.replace(/\s+/g, ' ').trim();

            // Short version for display
            const shortText = plainText.length > 30 
                ? plainText.substring(0, 30) + '…'
                : (plainText.length === 0 ? '[No preview]' : plainText);

            // Return with full text as tooltip
            return `<span title="${plainText.replace(/"/g, '&quot;')}">${shortText}</span>`;
        }

        return data;
    }
  });
  return $('#tableEventEmails').DataTable( {
    orderCellsHome: true,
    fixedHeader: true,
    paginate: false,
    select : true,
    columns: ecolumns,
    initComplete: function () {
      $('#tableEventEmails thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tableEventEmails thead');
      $('#tableEventEmails thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      var tableEmails = this.api();
      tableEmails
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('#tableEventEmails thead tr.filters th').eq(
            $(tableEmails.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $('input', $('#tableEventEmails thead tr.filters th').eq($(tableEmails.column(colIdx).header()).index()))
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              tableEmails
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
    }  
  });
}

function populateTableEventEmails(dtableEmails) {
  const params = {event: eventid};  
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tableemails.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      dtableEmails.clear();
      $.each( result.rows, function( key, val ) {
        dtableEmails.row.add({
            created: val.created,
            type: val.type,
            number: val.number,
            to: JSON.parse(val.metadata).to,
            subject: JSON.parse(val.metadata).subject,
            body: JSON.parse(val.metadata).body
        });
      });

      //
      // ERROR loading templosintra.png if email template (html) has /booking/img/templosintra.png
      //

      dtableEmails.draw();
    }
  });
}

function handlerTableEventEmails(dtableEmails) {
  $('#tableEventEmails tbody').on('click', 'tr', function () {
    $('#modalBookingEmail').modal('show');
    var data = dtableEmails.row( this ).data();
    $('input[name="number"]').val(data.number);
    $('#emailDate').val(data.created);
    $('#emailType').val(data.type);
    $('#emailTo').val(data.to);
    $('#emailSubject').val(data.subject);
    $('#emailBody').val(data.body);
    document.getElementById('emailSubject').innerHTML = data.subject;
    document.getElementById('emailBody').innerHTML = data.body;
  });
}

function handlerButtonsEventEmails(dtableEmails) {
  $('#closeBookingEmail').on('click', function(){
    $('#modalBookingEmail').modal('hide');
    dtableEmails.rows().deselect();
  });

  $('#clearFilter').on('click', function(){
    dtableEmails
        .search( '' )
        .columns().search( '' )
        .draw();
    $('input[name="filter"]').val( '' );
  });

}

function handlerFormsEventEmails(dtableEmails) {
  var formEmailResend = document.getElementById('formEmailResend');
  formEmailResend.addEventListener('submit', function (event) {
    event.preventDefault();
    event.stopPropagation();
    var data;
    if( dtableEmails.rows('.selected').any() )
      data = dtableEmails.row('.selected').data();
    else
      return;

    const params = {event: eventid, number: data.number, created: data.created, type: data.type};  
    if( test===true )
      params.test = true;
    $.ajax({
      type: "POST",
      url: "../server/manage/emailresend.php",
      dataType: 'json',
      data: JSON.stringify(params),
      success: function(result){
        dtableEmails.rows().deselect();
        $('#modalBookingEmail').modal('hide');
      }
    });   
  }, false)
}

//////////////////////////////////////////////////////////////
//
//  Event Logs
//
//////////////////////////////////////////////////////////////

function prepareEventLogs() {
  var dtableEventLogs = createTableEventLogs();
  populateTableEventLogs(dtableEventLogs);
  //handlerTableEventLogs(dtableEventLogs);
  handlerButtonsEventLogs(dtableEventLogs);
  //handlerFormsEventLogs(dtableEventLogs);
}

function createTableEventLogs() {
  return $('#tableEventLogs').DataTable( {
    orderCellsHome: true,
    fixedHeader: true,
    paginate: false,
    select : false,
    columns: bcolumns,
    columnDefs: [
      { targets: '_all', className: 'dt-center' }
    ],
    initComplete: function () {
      $('#tableEventLogs thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tableEventLogs thead');
      $('#tableEventLogs thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      var tableEventLogs = this.api();
      tableEventLogs
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('#tableEventLogs thead tr.filters th').eq(
            $(tableEventLogs.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $('input', $('#tableEventLogs thead tr.filters th').eq($(tableEventLogs.column(colIdx).header()).index()))
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              tableEventLogs
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
    }  
  });
}

function populateTableEventLogs(dtableEventLogs) {
  const params = {event: eventid};
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tablelogs.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      dtableEventLogs.clear();
      $.each( result.rows, function( key, val ) {
          const rowObject = {};
          $.each( bcolumns, function( key2, val2 ) {
            if ( val[val2.data] !== undefined ) {
              rowObject[val2.data] = val[val2.data];
            } else if (JSON.parse(val.metadata)[val2.data] !== undefined) {
              rowObject[val2.data] = JSON.parse(val.metadata)[val2.data];
            } else {
              rowObject[val2.data] = "";
            }
          });
          dtableEventLogs.row.add(rowObject).draw();          
      });
      dtableEventLogs.draw();
    }
  });
}

function handlerButtonsEventLogs(dtableEventLogs) {
  $('#buttonBookingRestore').on('click', function(){
    $('#modalBookingRestore').modal('show');
    var data;
    if( dtableEventLogs.rows('.selected').any() )
      data = dtableEventLogs.row('.selected').data();
    else
      return;
    logcreated = data[0];
    number = data[2];
    name = data[3];
    $('#event').val(eventid);
    $('#number').val(number);
    $('#name').text(name);
    $('#created').val(logcreated);
  });  

  $('#cancelBookingRestore').on('click', function(){
    $('#modalBookingRestore').modal('hide');
    dtableEventLogs.rows().deselect();
  });

  $('#clearFilter').on('click', function(){
    dtableEventLogs
        .search( '' )
        .columns().search( '' )
        .draw();
    $('input[name="filter"]').val( '' );
  });
}

function handlerFormsEventLogs(dtableEventLogs) {
  var formBookingRestore = document.getElementById('formBookingRestore');
  formBookingRestore.addEventListener('submit', function (event) {
    event.preventDefault();
    event.stopPropagation();
    // get input fields

    inputFields = convertFormToJSON(formBookingRestore);
    if( test===true )
      inputFields.test = true;
    $.ajax({
      type: "POST",
      url: "../server/manage/restorebooking.php",
      dataType: 'json',
      data: JSON.stringify(inputFields),
      success: function(result){
        $('#modalBookingRestore').modal('hide');
        const params = {event: eventid, number: number};
        if( test===true )
          params.test = true;
        $.ajax({
          type: "POST",
          url: "../server/manage/tableEventlogs.php",
          dataType: 'json',
          data: JSON.stringify(params),
          success: function(result){
            dtableEventLogs.clear();
            if( result.status===true ) {
              const params = {event: eventid, number: number};
              if( test===true )
                params.test = true;
              $.ajax({
                type: "POST",
                url: "../server/manage/tablebookings.php",
                dataType: 'json',
                data: JSON.stringify(params),
                success: function(result){
                  dtableEventBookings.clear();
                  $.each( result.rows, function( key, val ) {
                      row = [];
                      row.push(val.created);
                      row.push(val.idEvent);
                      row.push(val.number);
                      $.each( bcolumns, function( key2, val2 ) {
                          if( val2.title!="created" && val2.title!="number" && val2.title!="Event" ) {
                              if (JSON.parse(val.metadata)[val2.title] === undefined) {
                                  row.push("");
                              } else {
                                  row.push(JSON.parse(val.metadata)[val2.title]);
                              }
                          }
                      });
                      row.push(val.metadata);
                      dtableEventBookings.row.add(row);
                  });
                  dtableEventBookings.draw();
                }
              });
              $.each( result.rows, function( key, val ) {
                  row = [];
                  row.push(val.created);
                  row.push(val.idEvent);
                  row.push(val.number);
                  $.each( bcolumns, function( key2, val2 ) {
                      if( val2.title!="created" && val2.title!="number" && val2.title!="Event" ) {
                          if (JSON.parse(val.metadata)[val2.title] === undefined) {
                              row.push("");
                          } else {
                              row.push(JSON.parse(val.metadata)[val2.title]);
                          }
                      }
                  });
                  row.push(val.metadata);
                  dtableEventLogs.row.add(row);
              });
              dtableEventLogs.draw();
            }
          }
        });

      }
    });   
  }, false)
}


//////////////////////////////////////////////////////////////
//
//  Event Config
//
//////////////////////////////////////////////////////////////

function prepareEventConfig() {
  // add links
  $('#link_event_booking').text(url_dream + "event/" + eventid + "/index.html");
  $('#link_event_booking').attr("href", url_dream + "event/" + eventid + "/index.html");
  $('#link_event_manage').text(url_dream + "manage/index.html?event=" + eventid);
  $('#link_event_manage').attr("href", url_dream + "manage/index.html?event=" + eventid);
  $('#link_event_booking_test').text(url_dream + "event/" + eventid + "/index.html?test");
  $('#link_event_booking_test').attr("href", url_dream + "event/" + eventid + "/index.html?test");
  $('#link_event_manage_test').text(url_dream + "manage/index.html?event=" + eventid + "&date=" + eventdate + "&test");
  $('#link_event_manage_test').attr("href", url_dream + "manage/index.html?event=" + eventid + "&date=" + eventdate + "&test");
  var dtableconfigremotelinks  = createTableConfigRemoteLinks();
  populateTableConfigRemoteLinks(dtableconfigremotelinks);
  var dtableconfigpublic  = createTableConfigFilesPublic();
  var dtableconfigprivate = createTableConfigFilesPrivate();
  populateTablesConfigFiles(dtableconfigpublic,dtableconfigprivate);
  handlerTablesConfig(dtableconfigpublic,dtableconfigprivate);
  handlerButtonsConfig(dtableconfigpublic,dtableconfigprivate);
  handlerFormsConfig();
}

function createTableConfigRemoteLinks() {
  return $('#tableEventRemoteLinks').DataTable( {
    ordering: false,
    fixedHeader: true,
    paginate: false,
    searching: false,
    info: false,
    select : false,
    columns: [
      { title: "t_Session", width: "10%" },
      { title: "Link", width: "90%" }
    ]
  });
}

function populateTableConfigRemoteLinks(dtableconfigremotelinks) {
  const params = {event: eventid};
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tableremotelinks.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      remotelinks = [];
      $.each( result, function( key, val ) {
        row = [];
        row.push(val.value);
        row.push(val.link);
        dtableconfigremotelinks.row.add(row);
        // add to global variable to share with send email link
        remotelinks.push({"t_Session": val.value, "link": val.link});
      });
      dtableconfigremotelinks.draw();
    }
  });
}

function createTableConfigFilesPublic() {
  return $('#tableEventConfigPublic').DataTable( {
    ordering: false,
    fixedHeader: true,
    paginate: false,
    searching: false,
    info: false,
    select : false,
    columns: [
      { title: "Type", width: "10%" },
      { title: "File", width: "20%" },
      { title: "Title", width: "70%" }
    ],
    columnDefs: [
      { targets: [1], className: 'dt-center' }
    ]
  });
}

function createTableConfigFilesPrivate() {
  return $('#tableEventConfigPrivate').DataTable( {
    ordering: false,
    fixedHeader: true,
    paginate: false,
    searching: false,
    info: false,
    select : false,
    columns: [
      { title: "Type", width: "10%" },
      { title: "File", width: "20%" },
      { title: "Title", width: "70%" }
    ],
    columnDefs: [
      { targets: [1], className: 'dt-center' }
    ]
  });
}

function populateTablesConfigFiles(dtableconfigpublic,dtableconfigprivate) {
  const params = {event: eventid};
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tablefiles.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      $.each( result.public, function( key, val ) {
        row = [];
        row.push(val.extension);
        row.push(val.name);
        row.push(val.title);
        dtableconfigpublic.row.add(row);
      });
      dtableconfigpublic.draw();

      $.each( result.private, function( key, val ) {
        row = [];
        row.push(val.extension);
        row.push(val.name);
        row.push(val.title);
        dtableconfigprivate.row.add(row);
      });
      dtableconfigprivate.draw();
    }
  });
}

function handlerTablesConfig(dtableconfigpublic,dtableconfigprivate) {
  // Click handlers for table of public files
  $('#tableEventConfigPublic tbody').on('click', 'tr', function () {
    //console.log('click');
    var data = dtableconfigpublic.row( this ).data();
    filetype  = data[0];
    filename  = data[1];
    filetitle = data[2];
    if( filetype=="html" ) {
      // HTML
      $.ajax({
        type: "POST",
        url: "views/htmlconfig.html",
        dataType: 'text',
        success: function(result){
          $('#conteudo').html(result);
          //$('#breadcrumbEvents').text(activitytitle);
          //$('#breadcrumbEvents').attr("href", "?activity=" + activityid + "&title=" + activitytitle);
          $('#breadcrumbEvent').text("Evento: " + eventdate);
          $('#breadcrumbEvent').attr("href", "?event=" + eventid + "&title=" + eventtitle + "&date=" + eventdate + "&lastTabPaneEvent=" + lastTabPaneEvent);
          $('#breadcrumbEventFile').text(filename);
          $('#pageHTMLConfig_pTitle').text(filetitle);
          $('#event').val(eventid);
          $('#fileName').val(filename + ".html");

          var formTitleChange = document.getElementById('formTitleChange');
          formTitleChange.addEventListener('submit', function (event) {
              event.preventDefault();
              event.stopPropagation();
              // get input fields

              inputFields = convertFormToJSON(formTitleChange);
              if( test===true )
                inputFields.test = true;
              $.ajax({
                type: "POST",
                url: "../server/manage/changepublicfilemetatitle.php",
                dataType: 'json',
                data: JSON.stringify(inputFields),
                success: function(result){
                  $.ajax({
                    type: "POST",
                    url: "views/eventdetails.html",
                    dataType: 'text',
                    success: function(result){
                      $('#conteudo').html(result);
                      //$('#breadcrumbEvents').text(activitytitle);
                      //$('#breadcrumbEvents').attr("href", "?activity=" + activityid + "&title=" + activitytitle);
                      $('#breadcrumbEvent').text(eventdate);
                      loadEvents();
                    }
                  });
                }
              });   
          }, false)
        }
      });
    } else {
      // JSON
      $.ajax({
        type: "POST",
        url: "views/jsonconfig.html",
        dataType: 'text',
        success: function(result){
          $('#conteudo').html(result);
          //$('#breadcrumbEvents').text(activitytitle);
          //$('#breadcrumbEvents').attr("href", "?activity=" + activityid + "&title=" + activitytitle);
          $('#breadcrumbEvent').text("Evento: " + eventdate);
          $('#breadcrumbEvent').attr("href", "?event=" + eventid + "&title=" + eventtitle + "&date=" + eventdate + "&lastTabPaneEvent=" + lastTabPaneEvent);
          $('#breadcrumbEventFile').text(filename);          
          $('#pageHTMLConfig_pTitle').text(filetitle);
          $('#event').val(eventid);
          $('#fileName').val(filename + ".html");
          $.ajax({
            cache: false,
            url: url_dream + "event/" + eventid + "/" + filename + ".json",       //(getFileName().substring(0, getFileName().lastIndexOf('.')) + ".json"),
            dataType: "json",
            success: function(data) {
              renderJSONTree(data);
              $('#downloadJSON').on('click', function () {
                downloadJSON(data);
              });
              $('#saveEdit').on('click', function () {
                saveEdit(data);
              });
              $('#cancelEdit').on('click', function () {
                cancelEdit();
              });
            }
          });
        }
      });
    }
  });
  // Click handlers for table of private files
  $('#tableEventConfigPrivate tbody').on('click', 'tr', function () {
    //console.log('click');
    var data = dtableconfigprivate.row( this ).data();
    filetype  = data[0];
    filename  = data[1];
    filetitle  = data[2];
    if( filetype=="html" ) {
      // HTML
      $.ajax({
        type: "POST",
        url: "views/htmlconfig.html",
        dataType: 'text',
        success: function(result){
          $('#conteudo').html(result);
          //$('#breadcrumbEvents').text(activitytitle);
          //$('#breadcrumbEvents').attr("href", "?activity=" + activityid + "&title=" + activitytitle);
          $('#breadcrumbEvent').text("Evento: " + eventdate);
          $('#breadcrumbEvent').attr("href", "?event=" + eventid + "&title=" + eventtitle + "&date=" + eventdate + "&lastTabPaneEvent=" + lastTabPaneEvent);
          $('#breadcrumbEventFile').text(filename);
          $('#pageHTMLConfig_pTitle').text(filetitle);
          $('#event').val(eventid);
          $('#fileName').val(filename + ".html");

          var formTitleChange = document.getElementById('formTitleChange');
          formTitleChange.addEventListener('submit', function (event) {
              event.preventDefault();
              event.stopPropagation();
              // get input fields

              inputFields = convertFormToJSON(formTitleChange);
              if( test===true )
                inputFields.test = true;
              $.ajax({
                type: "POST",
                url: "../server/manage/changeprivatefilemetatitle.php",
                dataType: 'json',
                data: JSON.stringify(inputFields),
                success: function(result){
                  $.ajax({
                    type: "POST",
                    url: "views/eventdetails.html",
                    dataType: 'text',
                    success: function(result){
                      $('#conteudo').html(result);
                      //$('#breadcrumbEvents').text(activitytitle);
                      //$('#breadcrumbEvents').attr("href", "?activity=" + activityid + "&title=" + activitytitle);
                      $('#breadcrumbEvent').text(eventdate);
                      loadEvents();
                    }
                  });
                }
              });   
          }, false)
        }
      });
    } else {
      // JSON
      $.ajax({
        type: "POST",
        url: "views/jsonconfig.html",
        dataType: 'text',
        success: function(result){
          $('#conteudo').html(result);
          $('#pageHTMLConfig_pTitle').text(filetitle);
          $('#event').val(eventid);
          $('#fileName').val(filename + ".html");
          //$('#breadcrumbEvents').text(activitytitle);
          //$('#breadcrumbEvents').attr("href", "?activity=" + activityid + "&title=" + activitytitle);
          $('#breadcrumbEvent').text("Evento: " + eventdate);
          $('#breadcrumbEvent').attr("href", "?event=" + eventid + "&title=" + eventtitle + "&date=" + eventdate + "&lastTabPaneEvent=" + lastTabPaneEvent);
          $('#breadcrumbEventFile').text(filename);
          // Request json to PHP script
          $.ajax({
            type: "POST",
            url: "../server/manage/getjson.php",
            dataType: 'json',
            data: JSON.stringify({"eventid": eventid, "filename": filename}),
            success: function(json){
              renderJSONTree(json);
              let jsonchanges = new Object();
              $('#downloadJSON').on('click', function () {
                // 
                //downloadJSON(json);
                // send changes to server
                jsonchanges["eventid"] = eventid;
                jsonchanges["filename"] = filename;
//console.log(jsonchanges);
                $.ajax({
                  type: "POST",
                  url: "../server/manage/savejson.php",
                  dataType: 'json',
                  data: JSON.stringify(jsonchanges),
                  success: function(result){
//console.log("Success");
                  }
                });
              });
              $('#saveEdit').on('click', function () {
                saveEdit(json);
                // saving the change to a local object
                jsonchanges[$('#editorPath').text()] = $('#editorInput').val();
              });
              $('#cancelEdit').on('click', function () {
                cancelEdit();
              });
            }
          });
        }
      });
    }
  });
}

function handlerButtonsConfig(dtableconfigpublic,dtableconfigprivate) {
  $('#buttonCloneEvent').on('click', function(){
    $('#modalCloneEvent').modal('show');
    $('#activityClone').val(activityid);
    $('#eventClone').val(eventid);
  });  
  $('#cancelCloneEvent').on('click', function(){
    $('#modalCloneEvent').modal('hide');
  });  
  $('#buttonDeleteEvent').on('click', function(){
    $('#modalDeleteEvent').modal('show');
    $('#activityId').val(activityid);
    $('#eventId').val(eventid);
  });  
  $('#cancelDeleteEvent').on('click', function(){
    $('#modalDeleteEvent').modal('hide');
  });  
  $('#buttonGenerateEmptyBadges').on('click', function(){
    let numbers = [];
    // 1. Create a form element
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '../server/manage/badges.php';
    form.target = '_blank';

    // 2. Create a hidden input with JSON-encoded attendees
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'event';
    input.value = eventid;
    form.appendChild(input);
    const input2 = document.createElement('input');
    input2.type = 'hidden';
    input2.name = 'numbers';
    input2.value = JSON.stringify(numbers);
    form.appendChild(input2);

    // 3. Add to body and submit
    document.body.appendChild(form);
    form.submit();

    // 4. Clean up
    document.body.removeChild(form);
  });
  $('#clearEventConfigFilter').on('click', function(){
    dtableconfigpublic
        .search( '' )
        .columns().search( '' )
        .draw();
    dtableconfigprivate
        .search( '' )
        .columns().search( '' )
        .draw();
    $('input[name="filter"]').val( '' );
  });
}

function handlerFormsConfig() {
  var formCloneEvent = document.getElementById('formCloneEvent');
  formCloneEvent.addEventListener('submit', function (event) {
      event.preventDefault();
      event.stopPropagation();
      inputFields = convertFormToJSON(formCloneEvent);
      if( test===true )
        inputFields.test = true;
      $.ajax({
        type: "POST",
        url: "../server/manage/cloneevent.php",
        cache: false,
        dataType: 'json',
        data: JSON.stringify(inputFields),
        success: function(result){
          $('#modalCloneEvent').modal('hide');
        }
      });   
  }, false)
  var formDeleteEvent = document.getElementById('formDeleteEvent');
  formDeleteEvent.addEventListener('submit', function (event) {
      event.preventDefault();
      event.stopPropagation();
      const params = {event: eventid};
      if( test===true )
        params.test = true;
      $.ajax({
        type: "POST",
        url: "../server/manage/deleteevent.php",
        cache: false,
        dataType: 'json',
        data: JSON.stringify(params),
        success: function(result){
          $('#modalDeleteEvent').modal('hide');
          const params = new URLSearchParams({ event: eventid, title: eventtitle });
          // Reload the same page with the new query string
          window.location.href = window.location.pathname + '?' + params.toString();        }
      });   
  }, false)
}


//////////////////////////////////////////////////////////////
//
//  Pack details
//
//////////////////////////////////////////////////////////////

function loadPackDetails() {
  $.ajax({
    cache: false,
    type: "get",
    url: "views/packdetails.html",
    async: true,
    success: function(result){
      $('#conteudo').html(result);
      //$('#breadcrumbEvents').text("Atividade: " + activitytitle);
      //$('#breadcrumbEvents').attr("href", "?activity=" + activityid + "&title=" + activitytitle);
      $('#breadcrumbEvent').text("Evento: " + eventdate);
      $('#breadcrumbEvent').attr("href", "?event=" + eventid + "&title=" + eventtitle + "&date=" + eventdate + "&lastTabPaneEvent=" + lastTabPaneEvent);
      $('#breadcrumbPackBookings').text("Pack: " + packnumber);
      $('#breadcrumbPackBookings').attr("href", "?event=" + eventid + "&title=" + eventtitle + "&date=" + eventdate + "&pack=" + packnumber + "&lastTabPaneEvent=" + lastTabPaneEvent);
      preparePackBookings();
      preparePackPayments();
      preparePackEmails();
      preparePackLogs();
    }
  }); 
}

//
//  Pack Bookings
//

function preparePackBookings() {
  const urlhtml = '../event/' + eventid + '/index.html';
  const urljson = '../../event/' + eventid + '/config.json';

  var dtablePackBookings = createTablePackBookings();
  populateTablePackBookings(dtablePackBookings);
  handlerTablePackBookings(dtablePackBookings);
  handlerButtonsPackBookings(dtablePackBookings,urlhtml,urljson);
  handlerFormsPackBookings(dtablePackBookings);
}

function createTablePackBookings() {
  var tfoot = '<tfoot><tr><td></td><td></td><td></td><td class="columnTotal"></td><td class="columnSum"></td><td class="columnSum"></td><td class="columnSum"></td></tr></tfoot>';
  $(`#tablePackBookings`).append(tfoot);
  
  return $('#tablePackBookings').DataTable( {
    orderCellsHome: true,
    fixedHeader: true,
    paginate: false,
    select : false,
    columns: bcolumns,
    columnDefs: [
      { targets: '_all', className: 'dt-center' }
    ],
    footerCallback: function ( row, data, start, end, display ) {
      var api = this.api();

      $( api.column( 3 ).footer() ).html('Total: ');
      //const count = columns.length;
      for (let i = 4; i < 7; i++) {
        total = api
            .column( i, { search: 'applied' } )
            .data()
            .reduce( function (a, b) {
              if ( typeof(a) === "undefined" && a === null) a = 0;
              if ( typeof(b) === "undefined" && b === null) b = 0;
              return parseFloat(a) + parseFloat(b);
            }, 0 );
        $( api.column( i ).footer() ).html( parseFloat(total).toFixed(2) || 0 );
      }
    },
    initComplete: function () {
      $('#tablePackBookings thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tablePackBookings thead');
      $('#tablePackBookings thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      var tablePackBookings = this.api();
      tablePackBookings
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('#tablePackBookings thead tr.filters th').eq(
            $(tablePackBookings.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $('input', $('#tablePackBookings thead tr.filters th').eq($(tablePackBookings.column(colIdx).header()).index()))
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              tablePackBookings
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
      }  
    });
}

function populateTablePackBookings(dtablePackBookings) {
  const params = {event: eventid, packnumber: packnumber};
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tablebookings.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      dtablePackBookings.clear();
      $.each( result.rows, function( key, val ) {
        const rowObject = {};
        $.each( bcolumns, function( key2, val2 ) {
          if ( val[val2.data] !== undefined ) {
            rowObject[val2.data] = val[val2.data];
          } else if (JSON.parse(val.metadata)[val2.data] !== undefined) {
            rowObject[val2.data] = JSON.parse(val.metadata)[val2.data];
          } else {
            rowObject[val2.data] = "";
          }
        });
        dtablePackBookings.row.add(rowObject).draw();          
        packtoken = val.packtoken;  //e' sempre igual como o idpack
      });
      dtablePackBookings.draw();
    }
  });
}

function handlerTablePackBookings(dtablePackBookings) {
  $('#tablePackBookings tbody').on('click', 'tr', function () {
    var data = dtablePackBookings.row( this ).data();
    bookingnumber = data.number;
    loadBookingDetails(data);
  });
}

function handlerButtonsPackBookings (dtablePackBookings,urlhtml,urljson) {
  // Click handlers for buttons
  $('#buttonPackBookingAdd').on('click', function(){
    // 1. Open event.html in new tab
    const newWindow = window.open('event/index.html?title=' + activitytitle + '&config=' + urljson + '&token=' + packtoken, '_blank');
    // 2. Load urlhtml, extract its body
    fetch(urlhtml + '?t=' + Date.now(), { cache: 'no-store' })
      .then(response => response.text())
      .then(fullHtml => {
        const parser = new DOMParser();
        const doc = parser.parseFromString(fullHtml, 'text/html');
        // Remove all <script> tags inside body
        doc.body.querySelectorAll('script').forEach(script => script.remove());
        // Show private fields
        doc.body.querySelectorAll('div[name="private"]').forEach(div => {
          div.classList.remove('d-none');
        });      

        const bodyContent = doc.body.innerHTML;
        // 3. Function to send body content to event.html
        const sendContent = () => {
          newWindow.postMessage({
            type: 'injectBody',
            html: bodyContent
          }, window.location.origin);
        };

        // Send after event.html is loaded or fallback after delay
        newWindow.addEventListener('load', sendContent);
        setTimeout(sendContent, 1000);
      });
  });  

  $('#buttonPaymentCreate').on('click', function(){
    const params = {event: eventid};
    if( test===true )
      params.test = true;
    $.ajax({
      type: "POST",
      url: "../server/manage/getpaymentfields.php",
      dataType: 'json',
      data: JSON.stringify(params),
      success: function(result){
        $.each( result.providers, function( key, val ) {
          var row_provider = '<div class="form-check"><input class="form-check-input" type="radio" name="provider" id="provider.' + val + '" value="' + val + '"><label class="form-check-label" for="provider.' + val + '">' + val + '</label></div>';
          $('#paymentProviders').append(row_provider);
        });
        // populate bookings
        var data = dtablePackBookings.rows().data();
        table_html = $('#tablePackPayment tbody tr').html();
        $('#tablePackPayment tbody').html('');
        $.each( data, function( key, val ) {
          var row_text = '<tr><td>' + val.number + '</td><td>' + val.name + '</td><td>' + parseFloat(val.price).toFixed(2) + '</td><td>' + parseFloat(val.deposit).toFixed(2) + '</td><td>' + parseFloat(val.paid).toFixed(2) + '</td><td>';
          if( true || val.paid<val.price )
              for( i=1 ; i<4 ; i++ ) {
                  table_payment_template = table_html.split("<td>");
                  table_input = table_payment_template[6].split("value="); // after 5th td
//console.log(table_input);
                  table_input_text = table_input[i].split('"');     // counter (1-3)
//console.log(table_input_text);
                  table_input_text_value = table_input_text[1];
//console.log(table_input_text_value);   // data-text
                  if( table_input_text_value=="deposit" && val.paid>=val.deposit ) continue;
                  table_data = table_payment_template[6].split("data-text=");
                  table_data_text = table_data[i].split('"');     // counter (1-3)
                  table_data_text_value = table_data_text[1];     // data-text property of label
//console.log(table_data_text_value);   // data-text
                  table_label = table_data[i].split(">");    // counter (1-3)
                  table_label_text = table_label[1].split("</label");
                  table_label_text_value = table_label_text[0];   // content of label
//console.log(table_label_text_value);
                  row_text += '<div class="form-check"><input class="form-check-input" type="radio" name="t_payment_' + val.number + '" id="t_payment_' + val.number + '.' + table_input_text_value + '" value="' + table_input_text_value + '"><label class="form-check-label" for="t_payment_' + val.number + '.' + table_input_text_value + '" data-text="' + table_data_text_value + '">' + table_label_text_value + '</label></div>';
              }
          row_text += '</td></tr>';
          //$('#tablePackPayment tbody').append('<tr><td>' + val.number + '</td><td>' + val.name + '</td><td><div class="form-check"><input class="form-check-input" type="radio" name="' + val.number + '_payment" id="' + val.number + '_payment.none" value="none"><label class="form-check-label" for="' + val.number + '_payment.none" data-text="Nenhum">Nenhum</label></div><div class="form-check"><input class="form-check-input" type="radio" name="' + val.number + '_payment" id="' + val.number + '_payment.deposit" value="deposit"><label class="form-check-label" for="' + val.number + '_payment.deposit" data-text="Depósito">Depósito</label></div><div class="form-check"><input class="form-check-input" type="radio" name="' + val.number + '_payment" id="' + val.number + '_payment.full" value="full" data-error="Quantia a pagar"><label class="form-check-label" for="' + val.number + '_payment.full" data-text="Completo">Completo</label></div></td></tr>');
          $('#tablePackPayment tbody').append(row_text);

        });
        $('#modalPackPayment').modal('show');
      }
    });
  });

  $('#clearFilter').on('click', function(){
    dtablePackBookings
        .search( '' )
        .columns().search( '' )
        .draw();
    $('input[name="filter"]').val( '' );
  });
}

function handlerFormsPackBookings(dtablePackBookings) {
  var formPackPayment = document.getElementById('formPackPayment');
  formPackPayment.addEventListener('submit', function (event) {
    event.preventDefault();
    event.stopPropagation();
    paymentFields = convertFormToJSON(formPackPayment);
    var inputFields = {};
    inputFields.event = eventid;
    inputFields.packtoken = packtoken;
    inputFields.paymentFields = paymentFields;
    if( test===true )
      inputFields.test = true;
    $.ajax({
      type: "POST",
      url: "../server/manage/payment.php",
      dataType: 'json',
      data: JSON.stringify(inputFields),
      success: function(result){
        $('#modalPackPayment').modal('hide');
      }
    });   
  }, false)
}


//
//  Pack Payments
//

function preparePackPayments() {
  var dtablePackPayments = createTablePackPayments();
  populateTablePackPayments(dtablePackPayments);
  //handlerTablePackPayments(dtablePackPayments);
  //handlerButtonsPackPayments(dtablePackPayments);
}

function createTablePackPayments() {
  return $('#tablePackPayments').DataTable( {
    orderCellsHome: true,
    fixedHeader: true,
    paginate: false,
    select : false,
    columns: [
      { title: "Date",  width: "4%", data: "date" },
      { title: "Provider",  width: "2%", data: "provider" },
      { title: "Number",  width: "2%", data: "number" },
      { title: "Value",  width: "2%", data: "value" },
      { title: "Method",  width: "5%", data: "method" }
    ],
    initComplete: function () {
      $('#tablePackPayments thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tablePackPayments thead');
      $('#tablePackPayments thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      var tablePackPayments = this.api();
      tablePackPayments
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('#tablePackPayments thead tr.filters th').eq(
            $(tablePackPayments.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $('input', $('#tablePackPayments thead tr.filters th').eq($(tablePackPayments.column(colIdx).header()).index()))
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              tablePackPayments
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
    }  
  });
}

function populateTablePackPayments(dtablePackPayments) {
  const params = {event: eventid, packnumber: packnumber};
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tablepayments.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      dtablePackPayments.clear();
      if( result.easypay!=undefined )
        $.each( result.easypay.orders, function( key, val ) {
          const rowObject = {};
          rowObject.date = val.date;
          rowObject.provider = "easypay";
          rowObject.number = val.number;
          rowObject.value = val.value;
          rowObject.method = val.method;
          dtablePackPayments.row.add(rowObject).draw();          
        });
      if( result.tpa!=undefined )
        $.each( result.tpa.orders, function( key, val ) {
          const rowObject = {};
          rowObject.date = val.date;
          rowObject.provider = "tpa";
          rowObject.number = val.number;
          rowObject.value = val.value;
          rowObject.method = val.method;
          dtablePackPayments.row.add(rowObject).draw();          
        });
      if( result.cash!=undefined )
        $.each( result.cash.orders, function( key, val ) {
          const rowObject = {};
          rowObject.date = val.date;
          rowObject.provider = "cash";
          rowObject.number = val.number;
          rowObject.value = val.value;
          rowObject.method = val.method;
          dtablePackPayments.row.add(rowObject).draw();          
        });
      dtablePackPayments.draw();
    }
  });
}

//
//  Pack Emails
//

function preparePackEmails() {
  var dtablePackEmails = createTablePackEmails();
  populateTablePackEmails(dtablePackEmails);
  handlerTablePackEmails(dtablePackEmails);
  handlerButtonsPackEmails(dtablePackEmails);
  handlerFormsPackEmails(dtablePackEmails);
}

function createTablePackEmails() {
  var ecolumns = [];
  ecolumns.push({ title: "Created", width: "10%", data: "created" });
  ecolumns.push({ title: "Type", width: "10%", data: "type" });
  ecolumns.push({ title: "Number", width: "10%", data: "number" });
  ecolumns.push({ title: "To", width: "20%", data: "to" });
  ecolumns.push({ title: "Subject", width: "20%", data: "subject" });
  ecolumns.push({ title: "Body", width: "40%", data: "body",
    render: function(data, type, row, meta) {
        if (type === 'display' && data) {
            // Extract <body>...</body> manually
            let bodyMatch = data.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
            let bodyHTML = bodyMatch ? bodyMatch[1] : data;

            // Temporary element to parse HTML and extract visible text
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = bodyHTML;
            // Get plain text (contents of <span> and other inline tags are preserved as text)
            let plainText = tempDiv.textContent || "";
            plainText = plainText.replace(/\s+/g, ' ').trim();

            // Short version for display
            const shortText = plainText.length > 30 
                ? plainText.substring(0, 30) + '…'
                : (plainText.length === 0 ? '[No preview]' : plainText);

            // Return with full text as tooltip
            return `<span title="${plainText.replace(/"/g, '&quot;')}">${shortText}</span>`;
        }

        return data;
    }
    /*
    render: function(data, type, row, meta) {
        if (type === 'display' && data) {
            const template = document.createElement('template');
            template.innerHTML = data.trim();

            // Extract <body> content if possible
            let bodyContent = template.content.querySelector('body');
            let plainText = "";

            if (bodyContent) {
                plainText = bodyContent.textContent || "";
            } else {
                // Fallback: extract whatever text is available
                plainText = template.content.textContent || "";
            }

            // Normalize whitespace
            plainText = plainText.replace(/\s+/g, ' ').trim();

            // Prepare shortened version
            const shortText = plainText.length > 50 
                ? plainText.substring(0, 50) + '…'
                : (plainText.length === 0 ? '[No preview]' : plainText);

            // Return HTML-safe version with full text in tooltip
            return `<span title="${plainText.replace(/"/g, '&quot;')}">${shortText}</span>`;
        }

        return data;
    }
    */
  });
  return $('#tablePackEmails').DataTable( {
    orderCellsHome: true,
    fixedHeader: true,
    paginate: false,
    select : true,
    columns: ecolumns,
    initComplete: function () {
      $('#tablePackEmails thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tablePackEmails thead');
      $('#tablePackEmails thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      var tablePackEmails = this.api();
      tablePackEmails
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('#tablePackEmails thead tr.filters th').eq(
            $(tablePackEmails.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $('input', $('#tablePackEmails thead tr.filters th').eq($(tablePackEmails.column(colIdx).header()).index()))
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              tablePackEmails
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
    }  
  });
}

function populateTablePackEmails(dtablePackEmails) {
  const params = {event: eventid, packnumber: packnumber};
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tableemails.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      dtablePackEmails.clear();
      $.each( result.rows, function( key, val ) {
        dtablePackEmails.row.add({
            created: val.created,
            type: val.type,
            number: val.number,
            to: JSON.parse(val.metadata).to,
            subject: JSON.parse(val.metadata).subject,
            body: JSON.parse(val.metadata).body
        });
      });
      dtablePackEmails.draw();
    }
  });
}

function handlerTablePackEmails(dtablePackEmails) {
  $('#tablePackEmails tbody').on('click', 'tr', function () {
    $('#modalBookingEmail').modal('show');
    var data = dtablePackEmails.row( this ).data();
    $('input[name="number"]').val(data.number);
    $('#emailDate').val(data.created);
    $('#emailType').val(data.type);
    $('#emailTo').val(data.to);
    $('#emailSubject').val(data.subject);
    $('#emailBody').val(data.body);
    document.getElementById('emailSubject').innerHTML = data.subject;
    document.getElementById('emailBody').innerHTML = data.body;
  });
}

function handlerButtonsPackEmails(dtablePackEmails) {
  $('#closeBookingEmail').on('click', function(){
    $('#modalBookingEmail').modal('hide');
    dtablePackEmails.rows().deselect();
  });

  $('#clearFilter').on('click', function(){
    dtablePackEmails
        .search( '' )
        .columns().search( '' )
        .draw();
    $('input[name="filter"]').val( '' );
  });

}

function handlerFormsPackEmails(dtablePackEmails) {
  var formEmailResend = document.getElementById('formEmailResend');
  formEmailResend.addEventListener('submit', function (event) {
    event.preventDefault();
    event.stopPropagation();
    var data;
    if( dtablePackEmails.rows('.selected').any() )
      data = dtablePackEmails.row('.selected').data();
    else
      return;

    const params = {event: eventid, number: data.number, created: data.created, type: data.type};
    if( test===true )
      params.test = true;
    $.ajax({
      type: "POST",
      url: "../server/manage/emailresend.php",
      dataType: 'json',
      data: JSON.stringify(params),
      success: function(result){
        dtablePackEmails.rows().deselect();
        $('#modalBookingEmail').modal('hide');
      }
    });   
  }, false)
}

//
//  Pack Logs
//

function preparePackLogs() {
  var dtablePackLogs = createTablePackLogs();
  populateTablePackLogs(dtablePackLogs);
  //handlerTablePackLogs(dtablePackLogs);
  handlerButtonsPackLogs(dtablePackLogs);
  handlerFormsPackLogs(dtablePackLogs);
}

function createTablePackLogs() {
  return $('#tablePackLogs').DataTable( {
    orderCellsHome: true,
    fixedHeader: true,
    paginate: false,
    select : true,
    columns: bcolumns,
    initComplete: function () {
      $('#tablePackLogs thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tablePackLogs thead');
      $('#tablePackLogs thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      var tablePackLogs = this.api();
      tablePackLogs
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('#tablePackLogs thead tr.filters th').eq(
            $(tablePackLogs.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $('input', $('#tablePackLogs thead tr.filters th').eq($(tablePackLogs.column(colIdx).header()).index()))
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              tablePackLogs
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
    }  
  });
}

function populateTablePackLogs(dtablePackLogs) {
  const params = {event: eventid, packnumber: packnumber};
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tablelogs.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      dtablePackLogs.clear();
      $.each( result.rows, function( key, val ) {
          const rowObject = {};
          $.each( bcolumns, function( key2, val2 ) {
            if ( val[val2.data] !== undefined ) {
              rowObject[val2.data] = val[val2.data];
            } else if (JSON.parse(val.metadata)[val2.data] !== undefined) {
              rowObject[val2.data] = JSON.parse(val.metadata)[val2.data];
            } else {
              rowObject[val2.data] = "";
            }
          });
          dtablePackLogs.row.add(rowObject).draw();          
      });
      dtablePackLogs.draw();
    }
  });
}

function handlerButtonsPackLogs(dtablePackLogs) {
  $('#buttonBookingRestore').on('click', function(){
    $('#modalBookingRestore').modal('show');
    var data;
    if( dtablePackLogs.rows('.selected').any() )
      data = dtablePackLogs.row('.selected').data();
    else
      return;
    logcreated = data[0];
    number = data[2];
    name = data[3];
    $('#event').val(eventid);
    $('#number').val(number);
    $('#name').text(name);
    $('#created').val(logcreated);
  });  

  $('#cancelBookingRestore').on('click', function(){
    $('#modalBookingRestore').modal('hide');
    dtablePackLogs.rows().deselect();
  });

  $('#clearFilter').on('click', function(){
    dtablePackLogs
        .search( '' )
        .columns().search( '' )
        .draw();
    $('input[name="filter"]').val( '' );
  });
}

function handlerFormsPackLogs(dtablePackLogs) {
  var formBookingRestore = document.getElementById('formBookingRestore');
  formBookingRestore.addEventListener('submit', function (event) {
    event.preventDefault();
    event.stopPropagation();
    // get input fields

    inputFields = convertFormToJSON(formBookingRestore);
    if( test===true )
      inputFields.test = true;
    $.ajax({
      type: "POST",
      url: "../server/manage/restorebooking.php",
      dataType: 'json',
      data: JSON.stringify(inputFields),
      success: function(result){
        $('#modalBookingRestore').modal('hide');
        const params = {event: eventid, packnumber: packnumber};
        if( test===true )
          params.test = true;
        $.ajax({
          type: "POST",
          url: "../server/manage/tablepacklogs.php",
          dataType: 'json',
          data: JSON.stringify(params),
          success: function(result){
            dtablePackLogs.clear();
            if( result.status===true ) {
              const params = {event: eventid, packnumber: packnumber};
              if( test===true )
                params.test = true;
              $.ajax({
                type: "POST",
                url: "../server/manage/tablebookings.php",
                dataType: 'json',
                data: JSON.stringify(params),
                success: function(result){
                  dtablePackBookings.clear();
                  $.each( result.rows, function( key, val ) {
                      row = [];
                      row.push(val.created);
                      row.push(val.idpack);
                      row.push(val.number);
                      $.each( bcolumns, function( key2, val2 ) {
                          if( val2.title!="created" && val2.title!="number" && val2.title!="pack" ) {
                              if (JSON.parse(val.metadata)[val2.title] === undefined) {
                                  row.push("");
                              } else {
                                  row.push(JSON.parse(val.metadata)[val2.title]);
                              }
                          }
                      });
                      row.push(val.metadata);
                      dtablePackBookings.row.add(row);
                  });
                  dtablePackBookings.draw();
                }
              });
              $.each( result.rows, function( key, val ) {
                  row = [];
                  row.push(val.created);
                  row.push(val.idpack);
                  row.push(val.number);
                  $.each( bcolumns, function( key2, val2 ) {
                      if( val2.title!="created" && val2.title!="number" && val2.title!="pack" ) {
                          if (JSON.parse(val.metadata)[val2.title] === undefined) {
                              row.push("");
                          } else {
                              row.push(JSON.parse(val.metadata)[val2.title]);
                          }
                      }
                  });
                  row.push(val.metadata);
                  dtablePackLogs.row.add(row);
              });
              dtablePackLogs.draw();
            }
          }
        });

      }
    });   
  }, false)
}

//////////////////////////////////////////////////////////////
//
//  Booking
//
//////////////////////////////////////////////////////////////

function loadBookingDetails(data) {
  $.ajax({
    type: "get",
    url: "views/bookingdetails.html",
    async: true,
    success: function(result){
      $('#conteudo').html(result);
      //$('#breadcrumbEvents').text("Atividade: " + activitytitle);
      //$('#breadcrumbEvents').attr("href", "?activity=" + activityid + "&title=" + activitytitle);
      $('#breadcrumbEvent').text("Evento: " + eventdate);
      $('#breadcrumbEvent').attr("href", "?event=" + eventid + "&title=" + eventtitle + "&date=" + eventdate + "&lastTabPaneEvent=" + lastTabPaneEvent);
      $('#breadcrumbPackBookings').text("Pack: " + packnumber);
      $('#breadcrumbPackBookings').attr("href", "?event=" + eventid + "&title=" + eventtitle + "&date=" + eventdate + "&pack=" + packnumber + "&lastTabPaneEvent=" + lastTabPaneEvent);
      $('#breadcrumbBookingDetails').text("Inscrição: " + bookingnumber);
      $('#breadcrumbBookingDetails').attr("href", "?event=" + eventid + "&title=" + eventtitle + "&date=" + eventdate + "&pack=" + packnumber + "&booking=" + bookingnumber + "&lastTabPaneEvent=" + lastTabPaneEvent);

      prepareBookingDetails(data);
      prepareBookingPayments(data);
      prepareBookingEmails(data);
      prepareBookingLogs(data);
    }
  }); 
}

//
//  Booking Details
//

function prepareBookingDetails(data) {
  const urlhtml = '../event/' + eventid + '/index.html';
  const urljson = '../../event/' + eventid + '/config.json';
  var dtableBookingDetails = createTableBookingDetails();
  populateTableBookingDetails(dtableBookingDetails,data);
  handlerTableBookingDetails(dtableBookingDetails,urlhtml,urljson);
  //handlerButtonsBookingDetails(dtableBookingDetails);
}

function createTableBookingDetails() {
  return $('#tableBookingDetails').DataTable( {
    orderCellsHome: true,
    fixedHeader: true,
    paginate: false,
    select : true,
    columns: bcolumns,
    columnDefs: [
      { targets: '_all', className: 'dt-center' }
    ],
    initComplete: function () {
      $('#tableBookingDetails thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tableBookingDetails thead');
      $('#tableBookingDetails thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      var tableBookingDetails = this.api();
      tableBookingDetails
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('#tableBookingDetails thead tr.filters th').eq(
            $(tableBookingDetails.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $('input', $('#tableBookingDetails thead tr.filters th').eq($(tableBookingDetails.column(colIdx).header()).index()))
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              tableBookingDetails
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
      }  
    });
}

function populateTableBookingDetails(dtableBookingDetails,data) {
  dtableBookingDetails.clear();
  dtableBookingDetails.row.add(data);
  dtableBookingDetails.draw();
}

function handlerTableBookingDetails(dtableBookingDetails,urlhtml,urljson) {
  // Click handlers for buttons
  $('#buttonBookingChange').on('click', function(){
    var data;
    data = dtableBookingDetails.row(0).data();
    bookingnumber = data.number;
    const params = {event: eventid};
    if( test===true )
      params.test = true;
    $.ajax({
      type: "POST",
      url: "../server/manage/getbookingfields.php",
      dataType: 'json',
      data: JSON.stringify(params),
      success: function(result){
        fields = result;
        // 1. Open event.html in new tab
        const newWindow = window.open('event/index.html?title=' + eventtitle + '&config=' + urljson + '&booking=' + bookingnumber, '_blank');
        // 2. Load urlhtml, extract its body
        fetch(urlhtml + '?t=' + Date.now(), { cache: 'no-store' })
          .then(response => response.text())
          .then(fullHtml => {
            const parser = new DOMParser();
            const doc = parser.parseFromString(fullHtml, 'text/html');
            // Remove all <script> tags inside body
            doc.body.querySelectorAll('script').forEach(script => script.remove());
            // Show private fields
            doc.body.querySelectorAll('div[name="private"]').forEach(div => {
              div.classList.remove('d-none');
            });
            // Hide submit button and show submit change button
            doc.body.querySelectorAll('button[name="buttonSubmit"]').forEach(div => {
              div.classList.add('d-none');
            });
            doc.body.querySelectorAll('button[name="buttonChange"]').forEach(div => {
              div.classList.remove('d-none');
            });
            // Target your form by ID or any selector
            const form = doc.body.querySelector('#formBooking');
            // Select direct child divs of the form (top-level divs)
            const topLevelDivs = form.querySelectorAll(':scope > div');
            topLevelDivs.forEach(div => {
              div.classList.remove('collapse');
            });

            // Fill the values
            for( let i=0; i<bcolumns.length; i++ ) {
              if( fields[bcolumns[i].data] === undefined ) {
                continue;
              } else if( fields[bcolumns[i].data].input !== undefined && fields[bcolumns[i].data].values !== undefined ) {
                // radio input
                if( data[bcolumns[i].data] !== undefined && data[bcolumns[i].data] != "" ) {
                  //const form = doc.getElementById('formBooking');
                  const input = form.querySelector('#'+bcolumns[i].data+'\\.'+data[bcolumns[i].data]);
                  if (input) {
                    input.checked = true;
                    input.setAttribute('checked', 'checked');
                  }
                }
                // checkbox input
                // select input
              } else {
                // text field
                //const form = doc.getElementById('formBooking');
                const input = form.querySelector('#'+bcolumns[i].data);
                if (input)
                  input.defaultValue = data[bcolumns[i].data];
              }
            }

            const bodyContent = doc.body.innerHTML;
//console.log(bodyContent);
            // 3. Function to send body content to event.html
            const sendContent = () => {
              newWindow.postMessage({
                type: 'injectBody',
                html: bodyContent
              }, window.location.origin);
            };

            // Send after event.html is loaded or fallback after delay
            newWindow.addEventListener('load', sendContent);
            setTimeout(sendContent, 1000);
          });

      }
    });
   });  

  $('#buttonBookingDelete').on('click', function(){
    $('#modalBookingDelete').modal('show');
    var data;
    if( dtableBookingDetails.rows('.selected').any() )
      data = dtableBookingDetails.row('.selected').data();
    else
      return;
    number = data[2];
    lang = data[3];
    $('#bookingDeleteNumber').val(number);
    $('#bookingDeleteName').val(name);
    var formBookingDelete = document.getElementById('formBookingDelete');
    formBookingDelete.addEventListener('submit', function (event) {
      event.preventDefault();
      event.stopPropagation();

      // get input fields
      // inputFields = convertFormToJSON(formBookingChange);
  
      number = $('#bookingDeleteNumber').val();
  //console.log(number);
      // create new activity
      const params = {event: eventid, number: number, lang: lang};
      if( test===true )
        params.test = true;
      $.ajax({
        type: "POST",
        url: "../server/manage/changebooking.php",
        dataType: 'json',
        data: JSON.stringify(params),
        success: function(result){
          $('#modalBookingDelete').modal('hide');
          if( result.status===true ) {
            const params = {event: eventid, packnumber: packnumber};
            if( test===true )
              params.test = true;
            $.ajax({
              type: "POST",
              url: "../server/manage/tablebookings.php",
              dataType: 'json',
              data: JSON.stringify(params),
              success: function(result){
                dtableBookingDetails.clear();
                $.each( result.rows, function( key, val ) {
                    row = [];
                    row.push(val.created);
                    row.push(val.idpack);
                    row.push(val.number);
                    $.each( bcolumns, function( key2, val2 ) {
                        if( val2.title!="created" && val2.title!="number" && val2.title!="pack" ) {
                            if (JSON.parse(val.metadata)[val2.title] === undefined) {
                                row.push("");
                            } else {
                                row.push(JSON.parse(val.metadata)[val2.title]);
                            }
                        }
                    });
                    row.push(val.metadata);
                    dtableBookingDetails.row.add(row);
                });
                dtableBookingDetails.draw();
                dtablePackLogs.clear();
                $.each( result.rows, function( key, val ) {
                    row = [];
                    row.push(val.created);
                    row.push(val.idpack);
                    row.push(val.number);
                    $.each( bcolumns, function( key2, val2 ) {
                        if( val2.title!="created" && val2.title!="number" && val2.title!="pack" ) {
                            if (JSON.parse(val.metadata)[val2.title] === undefined) {
                                row.push("");
                            } else {
                                row.push(JSON.parse(val.metadata)[val2.title]);
                            }
                        }
                    });
                    row.push(val.metadata);
                    dtablePackLogs.row.add(row);
                });
                dtablePackLogs.draw();
              }
            });
          }
        }
      });   
    }, false)
  });  

  $('#cancelBookingDelete').on('click', function(){
    $('#modalBookingDelete').modal('hide');
    dtableBookingDetails.rows().deselect();
  });  
}

function getBookingDetails() {
  const params = {event: eventid, packnumber: packnumber, number: bookingnumber};
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tablebookings.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      const rowObject = {};
      $.each( bcolumns, function( key2, val2 ) {
        if ( result[val2.data] !== undefined ) {
          rowObject[val2.data] = result[val2.data];
        } else if (JSON.parse(result.metadata)[val2.data] !== undefined) {
          rowObject[val2.data] = JSON.parse(result.metadata)[val2.data];
        } else {
          rowObject[val2.data] = "";
        }
      });
      loadBookingDetails(rowObject);
    }
  });
}

//
//  Booking Payments
//

function prepareBookingPayments(data) {
  var dtableBookingPayments = createTableBookingPayments();
  populateTableBookingPayments(dtableBookingPayments,data);
  //handlerTableBookingDetails(dtableBookingPayments);
  //handlerButtonsBookingDetails(dtableBookingPayments);
}

function createTableBookingPayments() {
  return $('#tableBookingPayments').DataTable( {
    orderCellsHome: true,
    fixedHeader: true,
    paginate: false,
    select : false,
    columns: [
      { title: "Date",  width: "4%", data: "date" },
      { title: "Provider",  width: "2%", data: "provider" },
      { title: "Number",  width: "2%", data: "number" },
      { title: "Value",  width: "2%", data: "value" },
      { title: "Method",  width: "5%", data: "method" }
    ],
    initComplete: function () {
      $('#tableBookingPayments thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tableBookingPayments thead');
      $('#tableBookingPayments thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      var tableBookingPayments = this.api();
      tableBookingPayments
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('#tableBookingPayments thead tr.filters th').eq(
            $(tableBookingPayments.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $('input', $('#tableBookingPayments thead tr.filters th').eq($(tableBookingPayments.column(colIdx).header()).index()))
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              tableBookingPayments
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
    }  
  });
}

function populateTableBookingPayments(dtableBookingPayments) {
  const params = {event: eventid, packnumber: packnumber, number: bookingnumber};
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tablepayments.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      dtableBookingPayments.clear();
      if( result.easypay!=undefined )
        $.each( result.easypay.orders, function( key, val ) {
          const rowObject = {};
          rowObject.date = val.date;
          rowObject.provider = "easypay";
          rowObject.number = val.number;
          rowObject.value = val.value;
          rowObject.method = val.method;
          dtableBookingPayments.row.add(rowObject).draw();          
        });
      if( result.tpa!=undefined )
        $.each( result.tpa.orders, function( key, val ) {
          const rowObject = {};
          rowObject.date = val.date;
          rowObject.provider = "tpa";
          rowObject.number = val.number;
          rowObject.value = val.value;
          rowObject.method = val.method;
          dtableBookingPayments.row.add(rowObject).draw();          
        });
      if( result.cash!=undefined )
        $.each( result.cash.orders, function( key, val ) {
          const rowObject = {};
          rowObject.date = val.date;
          rowObject.provider = "cash";
          rowObject.number = val.number;
          rowObject.value = val.value;
          rowObject.method = val.method;
          dtableBookingPayments.row.add(rowObject).draw();          
        });
      dtableBookingPayments.draw();
    }
  });
}


//
//  Booking Emails
//

function prepareBookingEmails(data) {
  var dtableBookingEmails = createTableBookingEmails();
  populateTableBookingEmails(dtableBookingEmails,data);
  handlerTableBookingEmails(dtableBookingEmails);
  handlerButtonsBookingEmails(dtableBookingEmails);
}

function createTableBookingEmails() {
  var ecolumns = [];
  ecolumns.push({ title: "Created", width: "10%", data: "created" });
  ecolumns.push({ title: "Type", width: "10%", data: "type" });
  ecolumns.push({ title: "Number", width: "10%", data: "number" });
  ecolumns.push({ title: "To", width: "20%", data: "to" });
  ecolumns.push({ title: "Subject", width: "20%", data: "subject" });
  ecolumns.push({ title: "Body", width: "40%", data: "body",
    render: function(data, type, row, meta) {
        if (type === 'display' && data) {
            // Extract <body>...</body> manually
            let bodyMatch = data.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
            let bodyHTML = bodyMatch ? bodyMatch[1] : data;

            // Temporary element to parse HTML and extract visible text
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = bodyHTML;
            // Get plain text (contents of <span> and other inline tags are preserved as text)
            let plainText = tempDiv.textContent || "";
            plainText = plainText.replace(/\s+/g, ' ').trim();

            // Short version for display
            const shortText = plainText.length > 30 
                ? plainText.substring(0, 30) + '…'
                : (plainText.length === 0 ? '[No preview]' : plainText);

            // Return with full text as tooltip
            return `<span title="${plainText.replace(/"/g, '&quot;')}">${shortText}</span>`;
        }

        return data;
    }
  });
  return $('#tableBookingEmails').DataTable( {
    orderCellsHome: true,
    fixedHeader: true,
    paginate: false,
    select : true,
    columns: ecolumns,
    initComplete: function () {
      $('#tableBookingEmails thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tableBookingEmails thead');
      $('#tableBookingEmails thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      var tableBookingEmails = this.api();
      tableBookingEmails
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('#tableBookingEmails thead tr.filters th').eq(
            $(tableBookingEmails.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $('input', $('#tableBookingEmails thead tr.filters th').eq($(tableBookingEmails.column(colIdx).header()).index()))
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              tableBookingEmails
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
    }  
  });
}

function populateTableBookingEmails(dtableBookingEmails) {
  const params = {event: eventid, number: bookingnumber};
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tableemails.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      dtableBookingEmails.clear();
      $.each( result.rows, function( key, val ) {
        dtableBookingEmails.row.add({
            created: val.created,
            type: val.type,
            number: val.number,
            to: JSON.parse(val.metadata).to,
            subject: JSON.parse(val.metadata).subject,
            body: JSON.parse(val.metadata).body
        });
      });
      dtableBookingEmails.draw();
    }
  });
}

function handlerTableBookingEmails(dtableBookingEmails) {
  $('#tableBookingEmails tbody').on('click', 'tr', function () {
    $('#modalBookingEmail').modal('show');
    var data = dtableBookingEmails.row( this ).data();
    $('input[name="number"]').val(data.number);
    $('#emailDate').val(data.created);
    $('#emailType').val(data.type);
    $('#emailTo').val(data.to);
    $('#emailSubject').val(data.subject);
    $('#emailBody').val(data.body);
    document.getElementById('emailSubject').innerHTML = data.subject;
    document.getElementById('emailBody').innerHTML = data.body;
  });
}

function handlerButtonsBookingEmails(dtableBookingEmails) {
  $('#closeBookingEmail').on('click', function(){
    $('#modalBookingEmail').modal('hide');
    dtableBookingEmails.rows().deselect();
  });

  $('#clearFilter').on('click', function(){
    dtableBookingEmails
        .search( '' )
        .columns().search( '' )
        .draw();
    $('input[name="filter"]').val( '' );
  });

}

function handlerFormsBookingEmails(dtableBookingEmails) {
  var formEmailResend = document.getElementById('formEmailResend');
  formEmailResend.addEventListener('submit', function (event) {
    event.preventDefault();
    event.stopPropagation();
    var data;
    if( dtableBookingEmails.rows('.selected').any() )
      data = dtableBookingEmails.row('.selected').data();
    else
      return;

    const params = {event: eventid, number: data.number, created: data.created, type: data.type};
    if( test===true )
      params.test = true;
    $.ajax({
      type: "POST",
      url: "../server/manage/emailresend.php",
      dataType: 'json',
      data: JSON.stringify(params),
      success: function(result){
        dtableBookingEmails.rows().deselect();
        $('#modalBookingEmail').modal('hide');
      }
    });   
  }, false)
}

//
//  Booking Logs
//

function prepareBookingLogs(data) {
  var dtableBookingLogs = createTableBookingLogs();
  populateTableBookingLogs(dtableBookingLogs,data);
  //handlerTableBookingLogs(dtableBookingLogs);
  handlerButtonsBookingLogs(dtableBookingLogs);
}

function createTableBookingLogs() {
  return $('#tableBookingLogs').DataTable( {
    orderCellsHome: true,
    fixedHeader: true,
    paginate: false,
    select : true,
    columns: bcolumns,
    initComplete: function () {
      $('#tableBookingLogs thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tableBookingLogs thead');
      $('#tableBookingLogs thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      var tableBookingLogs = this.api();
      tableBookingLogs
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('#tableBookingLogs thead tr.filters th').eq(
            $(tableBookingLogs.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $('input', $('#tableBookingLogs thead tr.filters th').eq($(tableBookingLogs.column(colIdx).header()).index()))
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              tableBookingLogs
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
    }  
  });
}

function populateTableBookingLogs(dtableBookingLogs) {
  const params = {event: eventid, number: bookingnumber};
  if( test===true )
    params.test = true;
  $.ajax({
    type: "POST",
    url: "../server/manage/tablelogs.php",
    dataType: 'json',
    data: JSON.stringify(params),
    success: function(result){
      dtableBookingLogs.clear();
      $.each( result.rows, function( key, val ) {
          const rowObject = {};
          $.each( bcolumns, function( key2, val2 ) {
            if ( val[val2.data] !== undefined ) {
              rowObject[val2.data] = val[val2.data];
            } else if (JSON.parse(val.metadata)[val2.data] !== undefined) {
              rowObject[val2.data] = JSON.parse(val.metadata)[val2.data];
            } else {
              rowObject[val2.data] = "";
            }
          });
          dtableBookingLogs.row.add(rowObject).draw();          
      });
      dtableBookingLogs.draw();
    }
  });
}

function handlerButtonsBookingLogs(dtableBookingLogs) {
  $('#buttonBookingRestore').on('click', function(){
    $('#modalBookingRestore').modal('show');
    var data;
    if( dtableBookingLogs.rows('.selected').any() )
      data = dtableBookingLogs.row('.selected').data();
    else
      return;
    logcreated = data[0];
    number = data[2];
    name = data[3];
    $('#event').val(eventid);
    $('#number').val(number);
    $('#name').text(name);
    $('#created').val(logcreated);
  });  

  $('#cancelBookingRestore').on('click', function(){
    $('#modalBookingRestore').modal('hide');
    dtableBookingLogs.rows().deselect();
  });

  $('#clearFilter').on('click', function(){
    dtableBookingLogs
        .search( '' )
        .columns().search( '' )
        .draw();
    $('input[name="filter"]').val( '' );
  });
}

function handlerFormsBookingLogs(dtableBookingLogs) {
  var formBookingRestore = document.getElementById('formBookingRestore');
  formBookingRestore.addEventListener('submit', function (event) {
    event.preventDefault();
    event.stopPropagation();
    // get input fields

    inputFields = convertFormToJSON(formBookingRestore);
    if( test===true )
      inputFields.test = true;
    $.ajax({
      type: "POST",
      url: "../server/manage/restorebooking.php",
      dataType: 'json',
      data: JSON.stringify(inputFields),
      success: function(result){
        $('#modalBookingRestore').modal('hide');
        const params = {event: eventid, Bookingnumber: Bookingnumber};
        if( test===true )
          params.test = true;
        $.ajax({
          type: "POST",
          url: "../server/manage/tableBookinglogs.php",
          dataType: 'json',
          data: JSON.stringify(params),
          success: function(result){
            dtableBookingLogs.clear();
            if( result.status===true ) {
              const params = {event: eventid, number: number};
              if( test===true )
                params.test = true;
              $.ajax({
                type: "POST",
                url: "../server/manage/tablebookings.php",
                dataType: 'json',
                data: JSON.stringify(params),
                success: function(result){
                  dtableBookingBookings.clear();
                  $.each( result.rows, function( key, val ) {
                      row = [];
                      row.push(val.created);
                      row.push(val.idBooking);
                      row.push(val.number);
                      $.each( bcolumns, function( key2, val2 ) {
                          if( val2.title!="created" && val2.title!="number" && val2.title!="Booking" ) {
                              if (JSON.parse(val.metadata)[val2.title] === undefined) {
                                  row.push("");
                              } else {
                                  row.push(JSON.parse(val.metadata)[val2.title]);
                              }
                          }
                      });
                      row.push(val.metadata);
                      dtableBookingBookings.row.add(row);
                  });
                  dtableBookingBookings.draw();
                }
              });
              $.each( result.rows, function( key, val ) {
                  row = [];
                  row.push(val.created);
                  row.push(val.idBooking);
                  row.push(val.number);
                  $.each( bcolumns, function( key2, val2 ) {
                      if( val2.title!="created" && val2.title!="number" && val2.title!="Booking" ) {
                          if (JSON.parse(val.metadata)[val2.title] === undefined) {
                              row.push("");
                          } else {
                              row.push(JSON.parse(val.metadata)[val2.title]);
                          }
                      }
                  });
                  row.push(val.metadata);
                  dtableBookingLogs.row.add(row);
              });
              dtableBookingLogs.draw();
            }
          }
        });

      }
    });   
  }, false)
}


//////////////////////////////////////////////////////////////
//
// Helper functions
//
//////////////////////////////////////////////////////////////

function activateTabPaneById(paneId) {
  const button = document.querySelector(`#pills-tab .nav-link[data-bs-target="#${paneId}"]`);
  if (button) {
    const tab = new bootstrap.Tab(button); // Requires Bootstrap's JS
    tab.show();
  }
}

function convertFormToJSON(form) {
    return $(form)
        .serializeArray()
        .reduce(function (json, { name, value }) {
            json[name] = value;
            return json;
        }, {});
}  

function createTreeNode(key, value, parentObj, parentKey, path) {
  const node = document.createElement('div');
  node.classList.add('tree-node');

  const currentPath = path ? path + '.' + key : key;

  if (typeof value === 'object' && value !== null) {
    const isArrayIndex = /^\[\d+\]$/.test(key);
    const keyClass = isArrayIndex ? 'array-index' : 'key';
    const toggle = document.createElement('span');
    toggle.innerHTML = `<span class='${keyClass}'>+ ${key}</span>`;
    toggle.classList.add('toggle');
    node.appendChild(toggle);

    /*
    // Add or delete items
    const actions = document.createElement('span');
    actions.className = 'node-actions';
    const addBtn = document.createElement('button');
    addBtn.textContent = '+';
    addBtn.className = 'btn btn-sm btn-success me-1';
    addBtn.onclick = () => {
      const newKey = prompt('Enter key:');
      if (newKey) {
        value[newKey] = "new value";
        renderJSONTree(metadata);
      }
    };
    const deleteBtn = document.createElement('button');
    deleteBtn.textContent = '×';
    deleteBtn.className = 'btn btn-sm btn-danger';
    deleteBtn.onclick = () => {
      if (confirm(`Delete '${key}'?`)) {
        delete parentObj[parentKey];
        renderJSONTree(metadata);
      }
    };
    actions.appendChild(addBtn);
    actions.appendChild(deleteBtn);
    node.appendChild(actions);
    */

    const childrenContainer = document.createElement('div');
    childrenContainer.style.display = 'none';

    if (Array.isArray(value)) {
      value.forEach((item, index) => {
        childrenContainer.appendChild(createTreeNode(`[${index}]`, item, value, index, currentPath));
      });
    } else {
      for (const prop in value) {
        childrenContainer.appendChild(createTreeNode(prop, value[prop], value, prop, currentPath));
      }
    }

    toggle.addEventListener('click', () => {
      const isVisible = childrenContainer.style.display === 'block';
      toggle.innerHTML = `<span class='${keyClass}'>${(isVisible ? '+ ' : '- ') + key}</span>`;
      childrenContainer.style.display = isVisible ? 'none' : 'block';
    });

    node.appendChild(childrenContainer);
  } else {
    const isArrayIndex = /^\[\d+\]$/.test(key);
    const keyClass = isArrayIndex ? 'array-index' : 'key';
    const valueSpan = document.createElement('span');
    valueSpan.innerHTML = `<span class='${keyClass}'>${key}</span>: <span class='value'>${value}</span>`;
    valueSpan.style.cursor = 'pointer';
    valueSpan.onclick = () => openEditor(key, value, parentObj, parentKey, node, currentPath);
    node.appendChild(valueSpan);
  }

  return node;
}

function openEditor(key, value, parentObj, parentKey, nodeElement, path) {
  document.querySelectorAll('.selected-node').forEach(el => el.classList.remove('selected-node'));
  nodeElement.classList.add('selected-node');

  document.getElementById('editorKey').textContent = 'Key: ' + key;
  document.getElementById('editorPath').textContent = path;
  document.getElementById('editorInput').value = value;
  document.getElementById('editorPanel').style.display = 'block';

  currentEdit = { parentObj, parentKey, nodeElement };
}

function saveEdit(metadata) {
  const newValue = document.getElementById('editorInput').value;
  const parsed = parseValue(newValue);

  if (parsed !== undefined) {
    currentEdit.parentObj[currentEdit.parentKey] = parsed;
    renderJSONTree(metadata);
    closeEditor();
  } else {
    alert('Invalid input');
  }
}

function cancelEdit() {
  closeEditor();
}

function closeEditor() {
  document.getElementById('editorPanel').style.display = 'none';
  if (currentEdit && currentEdit.nodeElement) {
    currentEdit.nodeElement.classList.remove('selected-node');
  }
  currentEdit = null;
}

function parseValue(value) {
  try {
    return JSON.parse(value);
  } catch {
    if (typeof value === 'string') return value;
    return undefined;
  }
}

function renderJSONTree(json) {
  const treeContainer = document.getElementById('jsonTree');
  treeContainer.innerHTML = '';
  for (const key in json) {
    treeContainer.appendChild(createTreeNode(key, json[key], json, key, ''));
  }
}

function downloadJSON(metadata) {
  const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(metadata, null, 2));
  const downloadAnchor = document.createElement('a');
  downloadAnchor.setAttribute("href", dataStr);
  downloadAnchor.setAttribute("download", "data.json");
  document.body.appendChild(downloadAnchor);
  downloadAnchor.click();
  downloadAnchor.remove();
}

function openModifiedHtmlFromPath(fileUrl, oldScriptSrc, newScriptSrc) {
  fetch(fileUrl)
    .then(response => response.text())
    .then(originalHtml => {
      const parser = new DOMParser();
      const doc = parser.parseFromString(originalHtml, 'text/html');

      const scripts = doc.querySelectorAll('script[src]');
      scripts.forEach(script => {
        if (script.getAttribute('src') === oldScriptSrc) {
          script.setAttribute('src', newScriptSrc);
        }
      });

      const modifiedHtml = '<!DOCTYPE html>\n' + doc.documentElement.outerHTML;
      const blob = new Blob([modifiedHtml], { type: 'text/html' });
      const url = URL.createObjectURL(blob);

      window.open(url, '_blank');
    })
    .catch(err => {
      console.error('Failed to load HTML file:', err);
      alert('Unable to load the file. Ensure it’s hosted via a local server.');
    });
}

