<section class="shift-table-container">
  <h1>Manage Shifts</h1>
  <table id="shift-table">
  <thead>
    <tr>
      <th>ID</th>
      <th>Date</th>
      <th>Start Time</th>
      <th>End Time</th>
      <th>Extra Time</th>
      <th>Extra</th>
      <th>Film</th>
      <th>Responsible</th>
      <th>Actions</th>
      <th>Register For Shift</th>
    </tr>
  </thead>
    <tbody>
      <!-- rows will be loaded with javascript -->
    </tbody>
  </table>
</section>

<script>
  var currentAdminID = <?= json_encode($_SESSION['userID']) ?>;

  document.addEventListener('DOMContentLoaded', function () {
    var tbody = document.querySelector('#shift-table tbody');

    Promise.all([
      fetch('Functions/Shifts/getRegisteredShifts.php'),
      fetch('Functions/Shifts/getResponsibleShiftData.php'),
      fetch('Functions/Shifts/getFilmShiftData.php'),
      fetch('Functions/Shifts/getExtraShiftData.php'),
      fetch('Functions/Shifts/getShifts.php')
    ]).then(function (responses) {
      return Promise.all(responses.map(function (res) { return res.json(); }));
    }).then(function (data) {
      console.log(data);
      var regData = data[0];
      var responsibleData = data[1];
      var filmData = data[2];
      var extraData = data[3];
      var shifts = data[4];

      var registeredShiftIDs = [];
      
      if (regData.status === 'success') {
        for (var i = 0; i < regData.registeredShifts.length; i++) {
          registeredShiftIDs.push(String(regData.registeredShifts[i]));
        }
      }

      function createSelect(className, options, selectedValue, includeEmpty) {
        var select = document.createElement('select');
        select.className = className;
        select.disabled = true;

        if (includeEmpty) {
          var emptyOpt = document.createElement('option');
          emptyOpt.value = '';
          emptyOpt.textContent = '-- None --';

          if (!selectedValue) {
            emptyOpt.selected = true;
          }
          select.appendChild(emptyOpt);
        }

        for (var j = 0; j < options.length; j++) {
          var opt = document.createElement('option');
          opt.value = options[j].value;
          opt.textContent = options[j].label;

          if (String(options[j].value) === String(selectedValue)) {
            opt.selected = true;
          }
          select.appendChild(opt);
        }

        return select;
      }

      for (var k = 0; k < shifts.length; k++) {
        var shift = shifts[k];
        var row = document.createElement('tr');
        row.dataset.id = shift.pk_shift;

        var isSelf = (parseInt(shift.fk_responsible) === parseInt(currentAdminID));
        var isRegistered = shift.fk_responsible !== null && parseInt(shift.fk_responsible) > 0;

        if (!shift.fk_responsible || shift.fk_responsible == 0) {
          row.classList.add('shift-no-responsible');
        }

        row.innerHTML = ''
          + '<td>' + shift.pk_shift + '</td>'
          + '<td><input type="date" class="shiftDate" value="' + (shift.date || '') + '" disabled></td>'
          + '<td><input type="time" class="fromTime" value="' + (shift.fromTime || '') + '" disabled></td>'
          + '<td><input type="time" class="toTime" value="' + (shift.toTime || '') + '" disabled></td>'
          + '<td><input type="time" class="extraTime" value="' + (shift.extraTime || '') + '" disabled></td>'
          + '<td class="extraContainer"></td>'
          + '<td class="filmContainer"></td>'
          + '<td class="responsibleContainer"></td>'
          + '<td>'
          + (!isSelf ? '<button class="btn-edit">Edit</button> <button class="btn-update" style="display:none;">Save</button> <button class="btn-delete">Delete</button>'
                      : '<img src="./Assets/Images/Icons/edit_prohibited.svg" alt="Edit prohibited">')
          + '</td>'
          + '<td>'
          + (!isRegistered ? '<button class="btn-register btn">Register</button>'
                          : '<img src="./Assets/Images/Icons/edit_prohibited.svg" alt="Edit prohibited">')
          + '</td>';

        var responsibleOptions = responsibleData.map(function (user) {
          return { value: user.pk_userID, label: user.email };
        });

        var filmOptions = filmData.allFilms.map(function (film) {
          return { value: film.pk_filmID, label: film.title };  
        });

        var extraOptions = extraData.map(function (extra) {
          return { value: extra.pk_extra, label: extra.name };
        });

        row.querySelector('.responsibleContainer').appendChild(
          createSelect('fkResponsible', responsibleOptions, shift.fk_responsible, true)
        );

        row.querySelector('.filmContainer').appendChild(
          createSelect('fkFilm', filmOptions, shift.fk_film, false)
        );

        row.querySelector('.extraContainer').appendChild(
          createSelect('fkExtra', extraOptions, shift.fk_extra, true)
        );

        tbody.appendChild(row);
      }

      tbody.addEventListener('click', function (e) {
        var target = e.target;
        var row = target.closest('tr');
        if (!row) return;
        var id = row.dataset.id;

        if (target.classList.contains('btn-edit')) {
          var inputs = row.querySelectorAll('input, select');

          for (var i = 0; i < inputs.length; i++) {
            inputs[i].disabled = false;
          }

          target.style.display = 'none';
          row.querySelector('.btn-update').style.display = 'inline-block';
        }

        if (target.classList.contains('btn-update')) {
          var updatedData = {
            id: id,
            date: row.querySelector('.shiftDate').value,
            fromTime: row.querySelector('.fromTime').value,
            toTime: row.querySelector('.toTime').value,
            extraTime: row.querySelector('.extraTime').value,
            fk_extra: row.querySelector('.fkExtra').value,
            fk_film: row.querySelector('.fkFilm').value,
            fk_responsible: row.querySelector('.fkResponsible').value
          };

          var formBody = '';

          for (var key in updatedData) {
            if (formBody !== '') formBody += '&';
            formBody += key + '=' + updatedData[key];
            console.log(formBody);
          }

          fetch('Functions/Shifts/updateShift.php', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: formBody
          })
          .then(function (res) { return res.json(); })
          .then(function (data) {
            if (data.status === 'success') {
              showMessage('success', 'Shift updated.');
              var inputs = row.querySelectorAll('input, select');

              for (var j = 0; j < inputs.length; j++) {
                inputs[j].disabled = true;
              }

              target.style.display = 'none';
              row.querySelector('.btn-edit').style.display = 'inline-block';
            } else {
              console.log(data.message);
              showMessage('error', 'Update failed: ' + data.message);
            }
          });
        }

        if (target.classList.contains('btn-delete')) {
          if (confirm('Are you sure you want to delete this shift?')) {
            const formData = new FormData();
            formData.append('id', id);

            fetch('Functions/Shifts/deleteShift.php', {
              method: 'POST',
              body: formData
            }).then(res => res.json())
              .then(data => {
                if (data.status === 'success') {
                  row.remove();
                } else {
                  showMessage('error', 'Could not delete shift: ' + data.message);
                }
              });
          }
        }

        if (target.classList.contains('btn-register')) {
          fetch('Functions/Shifts/registerForShift.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ pk_shift: id })
          }).then(function (res) { return res.json(); }).then(function (data) {
            if (data.status === 'success') {
              var img = document.createElement('img');
              img.src = './Assets/Images/Icons/edit_prohibited.svg';
              img.alt = 'Edit prohibited';
              target.parentNode.replaceChild(img, target);
            } else {
              showMessage('Could not register: ' + data.message);
            }
          });
        }
      });
    });
  });
</script>