<?php
// config includes
if (isset($_REQUEST['tenant']) && file_exists('../../../'.$_REQUEST['tenant'].'/config.php')) {
    require_once('../../../'.$_REQUEST['tenant'].'/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

// required params: type, form, source
$type  = $_REQUEST['type']  ?? 'phrases';
$form  = $_REQUEST['form']  ?? '';
$source= $_REQUEST['source']?? '';
$group = preg_replace('/[^A-Za-z0-9_\-]/', '', (string)($_REQUEST['group'] ?? ''));
$groupFilterReady = false;
$groupHasAssignedPhrases = false;
$effectiveGroup = $group;
if ($group !== '' && isset($GLOBALS['con']) && $GLOBALS['con'] instanceof mysqli) {
    $groupTable = mysqli_query($GLOBALS['con'], "SHOW TABLES LIKE 'dd_phrase_groups'");
    $groupColumn = mysqli_query($GLOBALS['con'], "SHOW COLUMNS FROM `dd_phrases` LIKE 'group_id'");
    $groupFilterReady = $groupTable && mysqli_num_rows($groupTable) > 0 && $groupColumn && mysqli_num_rows($groupColumn) > 0;

    if ($groupFilterReady) {
        $stmt = $GLOBALS['con']->prepare("
            SELECT COUNT(p.`id`)
            FROM `dd_phrase_groups` g
            INNER JOIN `dd_phrases` p ON p.`group_id` = g.`id`
            WHERE g.`group_name` = ?
              AND g.`status` = 1
        ");
        if ($stmt) {
            $stmt->bind_param('s', $group);
            $stmt->execute();
            $stmt->bind_result($assignedPhraseCount);
            $stmt->fetch();
            $stmt->close();

            $groupHasAssignedPhrases = (int)$assignedPhraseCount > 0;
        }

        if (!$groupHasAssignedPhrases) {
            $effectiveGroup = '';
        }
    }
}
?>
<div id="exportTitle" style="display:none">Phrases - <?= date('d-m-Y')?></div>

<div class="container-fluid py-2">
  <?php if ($group !== '' && $groupFilterReady && $groupHasAssignedPhrases) { ?>
  <div class="alert alert-info py-2 mb-3 autotext-phrase-banner">
    Showing standard phrases for <strong><?= htmlspecialchars($group, ENT_QUOTES, 'UTF-8') ?></strong>.
  </div>
  <?php } elseif ($group !== '' && $groupFilterReady) { ?>
  <div class="alert alert-warning py-2 mb-3 autotext-phrase-banner">
    No phrases are assigned to <strong><?= htmlspecialchars($group, ENT_QUOTES, 'UTF-8') ?></strong>, so the full phrase list is shown.
  </div>
  <?php } elseif ($group !== '') { ?>
  <div class="alert alert-warning py-2 mb-3 autotext-phrase-banner">
    Phrase group filtering is not fully configured, so the full phrase list is shown.
  </div>
  <?php } ?>

  <div class="<?= $group !== '' ? 'autotext-table-host' : '' ?>">
    <table id="phrasesTable" class="table table-striped table-sm table-bordered table-hover w-100">
      <thead>
        <tr>
          <th>ID</th>
          <th>Phrase</th>
          <th class="text-center">Action</th>
        </tr>
      </thead>
    </table>
  </div>
</div>

<style>
  .autotext-phrase-banner {
    clear: both;
    display: block;
    position: relative;
    z-index: 1;
    margin-bottom: 1.25rem !important;
  }

  .autotext-table-host {
    clear: both;
    padding-top: .5rem;
  }

  #phrasesTable_wrapper {
    clear: both;
  }

  #phrasesTable_wrapper .autotext-dt-controls,
  #phrasesTable_wrapper .autotext-dt-footer {
    clear: both;
    width: 100%;
  }

  #phrasesTable_wrapper .dataTables_length,
  #phrasesTable_wrapper .dataTables_filter,
  #phrasesTable_wrapper .dt-length,
  #phrasesTable_wrapper .dt-search {
    float: none !important;
    margin: 0 !important;
  }

  #phrasesTable_wrapper .dataTables_filter,
  #phrasesTable_wrapper .dt-search {
    margin-left: auto !important;
    text-align: right;
  }

  @media (max-width: 767.98px) {
    #phrasesTable_wrapper .dataTables_filter,
    #phrasesTable_wrapper .dt-search {
      margin-left: 0 !important;
      text-align: left;
      width: 100%;
    }
  }
</style>

<script>
(function(){
  const type   = <?= json_encode($type) ?>;
  const formId = <?= json_encode($form) ?>;
  const source = <?= json_encode($source) ?>;
  const group  = <?= json_encode($effectiveGroup) ?>;

  // Initialise DataTable (vanilla DataTables)
  const table = new DataTable('#phrasesTable', {
    serverSide: true,
    processing: true,
    searching: true,
    lengthMenu: [10, 25, 50, 100],
    order: [[0, 'asc']],
    dom: '<"autotext-dt-controls d-flex flex-wrap justify-content-between align-items-center gap-2 mb-2"lf>rt<"autotext-dt-footer d-flex flex-wrap justify-content-between align-items-center gap-2 mt-2"ip>',
    ajax: {
      url: ROOT_URL + '/includes/formgen/form_options_data.php',
      type: 'POST',
      data: function(d){
        d.tenant = TENANT_URL;
        d.type   = type;
        d.group  = group;
      }
    },
    columns: [
      {
        data: function(row){
          // First column: phrasecode or code
          return row.phrasecode ?? row.code ?? '';
        }
      },
      {
        data: function(row){
          // Second column: phrase text or description
          return row.phrase ?? row.description ?? '';
        }
      },
      {
        data: null,
        className: 'text-center',
        orderable: false,
        render: function(row){
          // For phrases/results/examtype we send encoded phrase
          // For plant we send encoded code (to match legacy behavior)
          const payload = (type === 'plant') ? (row.codeEncoded || '') : (row.phraseEncoded || '');
          return `
            <a href="javascript:void(0)"
               class="btn btn-success text-light btn-lg"
               data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
               title="Copy to field"
               onclick="updateField('${payload}')">
              <i class="fad fa-copy"></i>
            </a>`;
        }
      }
    ]
  });

  // Preserve existing behavior
  window.updateField = function(encodedString) {
    const formElement = document.querySelector('#' + formId);
    if (!formElement) { return; }
    const sourceElement = formElement.querySelector('textarea[name="' + source + '"]');
    if (!sourceElement) { return; }

    let decodedContent = decodeURIComponent(encodedString).replace(/\+/g, ' ');
    decodedContent = decodedContent.replace(/\\n+/g, '\n').trim();

    let currentValue = sourceElement.value.trim();
    let newValue = currentValue + (currentValue ? '\n' : '') + decodedContent;
    sourceElement.value = newValue;

    const event = new Event('keyup');
    sourceElement.dispatchEvent(event);

    const popupBox = document.getElementById('popupBox');
    const modalInstance = mdb.Modal.getInstance(popupBox);
    if (modalInstance) { modalInstance.hide(); }
  };
})();
</script>
