<?php /* $_DEBUG disponibile da init.custom.php */ ?>
<script>var _DEBUG = <?= $_DEBUG ? 'true' : 'false' ?>;</script>
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">

<div class="titolo">SmartLeak Scanner - Inserimento Dati Quantitativi</div>
<div class="spessore"></div>
 <table class="table tablegrid3" style="margin-left: auto; margin-right: auto; width: 90%;" id="frm1">
    <thead>
      <tr>
        <th>Fattore</th>
        <th>Dato di input</th>
        <th>Unità / Scala</th> 
      </tr>
    </thead>
    <tbody>
    <?php
      //— prendo la configurazione dei fattori —
      $mydb->setCharset($charset="utf8mb4");
      $sql = "SELECT id, label, input_type, unit, help_text FROM business_case_factors WHERE is_active = 1 AND `table` = 'quantitative' ORDER BY sort_order";
      $stmt = $mydb->DoSelect($sql);
      foreach ($stmt as $row):
    ?>
    <?php

    // — logica step dinamico —
    $isPercent = strstr($row['unit'], '%');
    $isEuro = strstr($row['unit'], '€');
    $step  = $isPercent ? '1'    : '0.01';
    $min   = $isPercent ? '0'    : '0';
    $max   = $isPercent ? '100'  : '';   // opzionale

    $unita = $row['unit'];
    if ($isPercent) {
        $unita = '%';
    }
    if ($isEuro) {
        $unita = '€';
    }

    // Recupera il valore salvato in sessione, se esiste
    $savedValue = isset($_SESSION['survey'][$id_utente]['factor'][$row['id']]) 
        ? $_SESSION['survey'][$id_utente]['factor'][$row['id']] 
        : '';
  
    if($savedValue == -1) $savedValue = '';
    ?>
      <tr>
        <td>
            <?= htmlspecialchars($row['label'], ENT_QUOTES, 'UTF-8') ?> (<?= htmlspecialchars($row['unit'], ENT_QUOTES, 'UTF-8') ?>)
        <span class="ms-1 text-info"
            tabindex="0"
            data-bs-toggle="popover"
            data-bs-trigger="focus"
            data-bs-content="<?= htmlspecialchars($row['help_text']) ?>">
        <i class="bi bi-question-circle"></i>
      </span>
        </td>

        <td>
          <?php if ($row['input_type'] === 'number'): ?>
            <input type="number" 
                   step="<?= $step ?>"
                   min="<?= $min ?>"
                   <?= $max ? "max=\"$max\"" : '' ?>
                   name="factor[<?= $row['id'] ?>]"
                   value="<?= htmlspecialchars($savedValue) ?>"
                   class="form-control" required data-unit="<?= htmlspecialchars($unita, ENT_QUOTES, 'UTF-8') ?>">
           <?php endif; ?>
        </td>

        <td><?= $unita ?></td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>

  <div class="spessore"></div>
  <span class="testosm"><i>FTE: Full-Time Equivalent o “risorsa a tempo pieno”</i></span>
  <div class="spessore"></div>  
  <div class="spessore"></div> 

  <div class="titolo">SmartLeak Scanner - Inserimento Dati Qualitativi</div>
<div class="spessore"></div>
 <table class="table tablegrid3" style="margin-left: auto; margin-right: auto; width: 90%;" id="frm1">
    <thead>
      <tr>
        <th>Fattore</th>
        <th>Dato di input</th>
        <th>Unità / Scala</th> 
      </tr>
    </thead>
    <tbody>
    <?php
      //— prendo la configurazione dei fattori —
      $mydb->setCharset($charset="utf8mb4");
      $sql = "SELECT id, label, input_type, unit, help_text FROM business_case_factors WHERE is_active = 1 AND `table` = 'qualitative' ORDER BY sort_order";
      $stmt = $mydb->DoSelect($sql);
      foreach ($stmt as $row):
    ?>
    <?php

    // — logica step dinamico —
    $isPercent = strstr($row['unit'], '%');
    $isEuro = strstr($row['unit'], '€');
    $step  = $isPercent ? '1'    : '0.01';
    $min   = $isPercent ? '0'    : '0';
    $max   = $isPercent ? '100'  : '';   // opzionale

    $unita = str_replace("?","/",$row['unit']);
    if ($isPercent) {
        $unita = '%';
    }
    if ($isEuro) {
        $unita = '€';
    }
 

    // Recupera il valore salvato in sessione, se esiste
    $savedValue = isset($_SESSION['survey'][$id_utente]['factor'][$row['id']]) 
        ? $_SESSION['survey'][$id_utente]['factor'][$row['id']] 
        : '';
  
    ?>
      <tr>
        <td>
            <?= htmlspecialchars($row['label'], ENT_QUOTES, 'UTF-8') ?>
        <span class="ms-1 text-info"
            tabindex="0"
            data-bs-toggle="popover"
            data-bs-trigger="focus"
            data-bs-content="<?= htmlspecialchars($row['help_text']) ?>">
        <i class="bi bi-question-circle"></i>
      </span>
        </td>

        <td>
          <?php if ($row['input_type'] === 'number'): ?>
            <input type="number" 
                   step="<?= $step ?>"
                   min="<?= $min ?>"
                   <?= $max ? "max=\"$max\"" : '' ?>
                   name="factor[<?= $row['id'] ?>]"
                   value="<?= htmlspecialchars($savedValue) ?>"
                   class="form-control" required data-unit="<?= htmlspecialchars($unita, ENT_QUOTES, 'UTF-8') ?>">
          <?php else: /* select 1-5 */ ?>
            <select name="factor[<?= $row['id'] ?>]" class="form-select">
              <option value="-1" <?= $savedValue == -1 ? 'selected' : '' ?> >-seleziona-</option>
              <?php for ($i=1; $i<=5; $i++): ?>
                <option value="<?= $i ?>" <?= $savedValue == $i ? 'selected' : '' ?> ><?= str_repeat('+', $i) ?></option>
              <?php endfor; ?>
            </select>
          <?php endif; ?>
        </td>

        <td><?= $unita ?></td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  
  <div class="mt-3 d-flex gap-2">
    <button type="button" class="btn btn-primary" onclick="saveAndGenerateAnalysis('finalyze')" id="btnSave">Salva & Genera Analisi</button>
    <button type="button" class="btn btn-outline-secondary" onclick="bcResetForm()" id="btnReset">Reset</button>
  </div>
<div class="clearboth"></div>
<div id="waiting" style="display:none;">
    <img src="main/contents/immagini/loading3.gif" alt="Loading..." >
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function formToQueryString(form) {
    const params = [];
    for (let el of form.elements) {
        if (!el.name || el.disabled) continue;
        if ((el.type === 'checkbox' || el.type === 'radio') && !el.checked) continue;
        params.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value));
    }
    return params.join('&');
}
function formToJson(form) {
    var obj = {};
    var formData = new FormData(form);
    formData.forEach(function(value, key){
        obj[key] = value;
    });
    return obj;
}
    function saveAndGenerateAnalysis(mode='update') {

      if(mode=='finalyze'){
        hidelayer('btnSave');
        showlayer('waiting');
      }
        // Prepara i dati del form
        const form = document.querySelector('#frm1');
        var json = formToJson(form);
        json.id_utente = form.id_utente.value;
        json.id_item = form.id_item.value;
        json.mode = mode;
        console.log("JSON: " + JSON.stringify(json));
        ajaxSrvJs("saveAndGenerateAnalysis", json, saveAndGenerateAnalysisDone, null);
    }

    function saveAndGenerateAnalysisDone(response) {
      // Nascondi il caricamento
      hidelayer('waiting');
      // Normalizza response a oggetto
      let res = response;
      console.log("Response: " + response);
      try {
        if (typeof response === 'string') {
          res = JSON.parse(response);
        }
      } catch (e) {
        console.warn('Response non JSON, usando valore grezzo');
      }
      // Se è finalyze, passa allo step successivo
      if (res && res.mode === 'finalyze') {
        waitpage();
        //document.frm1.step.value = parseInt(document.frm1.step.value) + 1; non serve
        document.frm1.submit();
      }
    }

    document.addEventListener('DOMContentLoaded', function() {
        // Inizializza i popover
        const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]');
        popoverTriggerList.forEach(el => new bootstrap.Popover(el));

      // Auto-save: invia i dati ad ogni modifica con mode=update (debounce)
      const form = document.querySelector('#frm1');
      let saveTimer = null;
      const triggerAutoSave = () => {
        if (saveTimer) clearTimeout(saveTimer);
        saveTimer = setTimeout(() => {
          saveAndGenerateAnalysis('update');
        }, 500);
      };

      // Ascolta cambi su input/select su tutta la pagina (alcuni campi possono essere fuori da #frm1)
      document.querySelectorAll('input[name^="factor["], select[name^="factor["]').forEach(el => {
        if (el.tagName === 'INPUT') {
          el.addEventListener('blur', () => { formatEuroInput(el); triggerAutoSave(); });
          el.addEventListener('change', () => { formatEuroInput(el); triggerAutoSave(); });
        } else {
          el.addEventListener('change', triggerAutoSave);
        }
      });

      // DEBUG: pulsante autofill rapido (solo admin)
      if(typeof _DEBUG !== 'undefined' && _DEBUG) addAutofillDebugButton();
      // All'avvio: formatta i numeri Euro già presenti (da sessione) su tutta la pagina
      document.querySelectorAll('input[name^="factor["]').forEach(el => { formatEuroInput(el); });
    });

    // ====== Formattazione numeri in Euro ======
    function formatEuroInput(inputEl) {
      try {
        const unit = (inputEl.dataset && inputEl.dataset.unit) ? inputEl.dataset.unit : '';
        if (unit !== '€') return;
        const v = String(inputEl.value || '').trim();
        if (v === '') return;
        // Normalize: remove spaces, thousands '.', replace ',' to '.'
        let raw = v.replace(/\s+/g, '');
        raw = raw.replace(/\./g, '');
        raw = raw.replace(/,/g, '.');
        const num = parseFloat(raw);
        if (isNaN(num)) return;
        inputEl.value = new Intl.NumberFormat('it-IT', { minimumFractionDigits: 0, maximumFractionDigits: 6 }).format(num);
      } catch(e) {}
    }

    // ====== Reset Form ======
    function bcResetForm() {
      // Svuota gli input e resetta le select ai valori di default
      document.querySelectorAll('input[name^="factor["], select[name^="factor["]').forEach(el => {
        if (el.tagName === 'INPUT') {
          el.value = '';
        } else if (el.tagName === 'SELECT') {
          // Imposta al valore medio (3) se è la scala +
          if (el.options && el.options.length >= 5) {
            el.value = '-1';
          } else {
            el.selectedIndex = -1;
          }
        }
      });
      // Re-formatta se necessario e salva stato aggiornato
      document.querySelectorAll('input[name^="factor["]').forEach(el => { formatEuroInput(el); });
      // Esegue un salvataggio di stato aggiornato
      saveAndGenerateAnalysis('update');
    }

    // Le funzioni di debug autofill sono definite sotto, condizionate a $_DEBUG
</script>

<?php if($_DEBUG): ?>
<?php /* === SmartLeak Scanner: funzioni di debug autofill (solo admin) === */ ?>
<script>
    function bcAutofillByLabel(mapping) {
      const form = document.querySelector('#frm1');
      if (!form) return;
      const rows = Array.from(form.querySelectorAll('tbody tr'));
      rows.forEach(tr => {
        const tdLabel = tr.querySelector('td');
        if (!tdLabel) return;
        const labelText = tdLabel.innerText.toLowerCase();
        for (const key in mapping) {
          if (labelText.indexOf(key.toLowerCase()) !== -1) {
            const val = mapping[key];
            const numberInput = tr.querySelector('input[type="number"][name^="factor["]');
            if (numberInput) {
              numberInput.value = val;
              numberInput.dispatchEvent(new Event('input', { bubbles: true }));
              numberInput.dispatchEvent(new Event('change', { bubbles: true }));
              break;
            }
            const selectInput = tr.querySelector('select[name^="factor["]');
            if (selectInput) {
              const intVal = parseInt(val, 10);
              if (!isNaN(intVal) && intVal >= 1 && intVal <= 5) {
                selectInput.value = String(intVal);
                selectInput.dispatchEvent(new Event('change', { bubbles: true }));
              }
              break;
            }
          }
        }
      });
    }

    function bcAutofillQuantitativi() {
      const map = {
        'turn-over': 4, 'assenteismo': 5.5, 'burn-out': 1, 'disengagement': 15,
        'variazione di fatturato': 2.5, 'variazione di produttività': 4,
        'retention': 40, 'talent attraction': 45,
        'costo straordinario per fte': 1500, 'costi di recruiting': 500000,
        'costi di energia': 2, 'costi di training neo assunti': 150000,
        'welfare aziendale per fte': 850, 'accudire i figli': 10000,
        'spostamenti': 3500, 'emissioni co2': 54000
      };
      bcAutofillByLabel(map);
    }

    function bcAutofillQualitativi() {
      const map = {
        'servizio clienti': 4, 'qualità del servizio': 3, 'brand reputation': 3,
        'errori al lavoro': 15, 'carichi di lavoro - fatica': 25, 'stress e ansia': 50,
        'creatività & innovazione': 3, 'soddisfazione al lavoro': 25,
        'emozioni positive': 57, 'frequenza esercizi fisici': 44,
        'problemi legati al sonno': 55, 'qualità delle candidature': 3,
        'gender pay gap': 2, 'problem solving': 4, 'competenze': 4,
        'tempo per formazione: upskilling e reskilling': 3,
        'qualità comunicazione interna ed esterna': 3,
        'motivazione': 3, 'felicità ed energia': 3, 'volontariato': 3
      };
      bcAutofillByLabel(map);
    }

    function addAutofillDebugButton() {
      if (document.getElementById('btn-bc-autofill')) return;
      const btn = document.createElement('div');
      btn.id = 'btn-bc-autofill';
      btn.style.position = 'fixed';
      btn.style.right = '16px';
      btn.style.bottom = '16px';
      btn.style.zIndex = '9999';
      btn.innerHTML = '<div class="btn-group dropup">\
        <button type="button" class="btn btn-sm btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">Autofill (debug)</button>\
        <ul class="dropdown-menu dropdown-menu-end">\
          <li><a class="dropdown-item" href="#" id="autofill-quant">Compila valori quantitativi</a></li>\
          <li><a class="dropdown-item" href="#" id="autofill-qual">Compila valori qualitativi (1–5)</a></li>\
          <li><hr class="dropdown-divider"></li>\
          <li><a class="dropdown-item" href="#" id="autofill-both">Compila entrambi</a></li>\
        </ul>\
      </div>';
      document.body.appendChild(btn);
      document.getElementById('autofill-quant').addEventListener('click', function(e){ e.preventDefault(); bcAutofillQuantitativi(); });
      document.getElementById('autofill-qual').addEventListener('click', function(e){ e.preventDefault(); bcAutofillQualitativi(); });
      document.getElementById('autofill-both').addEventListener('click', function(e){ e.preventDefault(); bcAutofillQuantitativi(); bcAutofillQualitativi(); });
    }
</script>
<?php endif; /* $_DEBUG */ ?>