<?php 
if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../'.$_REQUEST['tenant'].'/config.php'); $tg=1;}
if(file_exists('/config.php')){require_once('/config.php'); $tg=2;}
$d=explode("|",$_REQUEST['data']);

// Parent item fields, including subloc and duedate
$stmt = $GLOBALS['con']->prepare("SELECT `plantnumber`,`serialnumber`,`manf`,`dateofmanf`,`model`,`swl`,`subloc`,`duedate` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $d[2]);
$stmt->execute();
$cc=$stmt->get_result();
$stmt->close();
$td=mysqli_fetch_assoc($cc);

// Distinct sublocs for this client
$sublocs=[];
if (!empty($d[0])) {
    $clientnumber = (int)$d[0];
    $stmt2 = $GLOBALS['con']->prepare("SELECT DISTINCT subloc FROM itemdetails WHERE clientnumber=? AND subloc IS NOT NULL  ORDER BY subloc");
    $stmt2->bind_param('i', $clientnumber);
    $stmt2->execute();
    $res = $stmt2->get_result();
    while ($r = $res->fetch_assoc()) { $sublocs[] = $r['subloc']; }
    $stmt2->close();
}
if(empty($td['duedate'])){$dueDateCurrent='<span class="badge badge-warning">No Date Stored</span>'; $dueDateCheck="disabled";}
else{$dueDateCurrent='<span class="badge badge-info">'.date('d-m-y',$td['duedate']).'</span>'; $dueDateCheck="checked";}
?>

<div class="row mt-n4">
  <div class="col-md-12 text-center p-1 alert-warning text-dark">
    <span>You must complete the <strong class="text-dark">plant number</strong> or <strong class="text-dark">serial number</strong> to store the record. If you leave any other field blank, they will be cloned from the parent.</span>
  </div>
<div class="col-12 mb-3 mt-2 text-center">
  <strong>Cloning:</strong>  <?= $d[3]?> - <?=$td['plantnumber']?> / <?=$td['serialnumber']?></div>
  <div class="col-12 mt-2 d-flex align-items-center flex-wrap gap-3">
    <div>
      <label for="clones" class="lead me-2 align-middle">Set Number of required <?= $d[3]?>'s</label>
      <input type="number" id="clones" class="form-control d-inline-block w-auto align-middle " placeholder="Choose" onkeyup="genClones()">
    </div>

    <div class="form-check form-switch ms-2">
      <input class="form-check-input" type="checkbox" id="useOriginalDateSwitch" <?=$dueDateCheck?>>
      <label class="form-check-label" for="useOriginalDateSwitch">Use parents inspection due date: <?= $dueDateCurrent?></label>
    </div>
  </div>
</div>
<hr>

<form id="cloneForm">
  <div id="clonebox" class="col-md-12">
    <table class="table table-striped" id="cloneList">
      <thead>
        <tr>
          <th width="20px"></th>
          <th>
            Plant Number
            <button type="button" class="badge badge-info ms-2"  onclick="autoFillPlantNumbers()">Auto-fill</button>
          </th>
          <th>Serial</th>
          <th>Manufacturer</th>
          <th>Manufacture Date</th>
          <th>Model</th>
          <th>Sublocation</th> <!-- New header -->
          <th>SWL</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <input id="parent" name="parent" type="hidden" value="<?= (int)$d[2]?>">
    <input id="rowCount" name="rowCount" type="hidden" value="">
  </div>

  <div class="col-md-12 mt-4 text-center hidden"><button id="frmSub" type="submit" class="btn btn-info">Proceed</button></div>
</form>
<?php
$origSubloc = isset($td['subloc']) ? trim((string)$td['subloc']) : '';
if ($origSubloc === '0') $origSubloc = ''; // treat DB '0' as empty

// Build options from DISTINCT sublocs for this client
$sublocOptions = '<option value="">Define New</option>';
$seen = [];
$matched = false;

foreach ($sublocs as $s) {
    $s = trim((string)$s);
    if ($s === '' || $s === '0') continue;          // drop blanks and literal "0"
    if (isset($seen[$s])) continue;
    $seen[$s] = true;
    $sel = ($origSubloc !== '' && strcasecmp($s, $origSubloc) === 0) ? ' selected' : '';
    if ($sel) $matched = true;
    $sublocOptions .= '<option value="'.htmlspecialchars($s, ENT_QUOTES).'"'.$sel.'>'
                    .  htmlspecialchars($s, ENT_QUOTES).'</option>';
}

// If original subloc not in DISTINCT list, prepend it as selected
if ($origSubloc !== '' && !$matched) {
    $v = htmlspecialchars($origSubloc, ENT_QUOTES);
    $sublocOptions = '<option value="'.$v.'" selected>'.$v.'</option>'.$sublocOptions;
}
?>
<script>
var ORIG_SUBLOC = <?= json_encode($td['subloc'] ?? '') ?>;
var ORIG_duedate_UNIX = <?= (int)($td['duedate'] ?? 0) ?>;
var SUBLOCS = <?= json_encode($sublocs, JSON_UNESCAPED_UNICODE) ?>;

function escapeHtml(str) {
  if (str == null) return '';
  return String(str)
    .replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')
    .replace(/"/g,'&quot;').replace(/'/g,'&#039;').replace(/\n/g,'&#10;');
}

function buildSublocSelect(name, selected) {
  var seen = Object.create(null);
  var opts = ['<option value=""></option>'];
  if (selected && !seen[selected]) {
    opts.push('<option value="'+escapeHtml(selected)+'" selected>'+escapeHtml(selected)+'</option>');
    seen[selected] = true;
  }
  for (var i = 0; i < SUBLOCS.length; i++) {
    var s = SUBLOCS[i];
    if (!seen[s]) {
      opts.push('<option value="'+escapeHtml(s)+'">'+escapeHtml(s)+'</option>');
      seen[s] = true;
    }
  }
  return '<select name="'+name+'" class="form-select">'+opts.join('')+'</select>';
}

function genClones() {
  var count = parseInt(document.getElementById('clones').value || '0', 10);
  if (isNaN(count) || count < 0) count = 0;
  document.getElementById('rowCount').value = count;

  var useOriginalDate = !!document.getElementById('useOriginalDateSwitch')?.checked;
    var origUnix = <?= (int)($td['duedate'] ?? 0) ?>;
    var dateVal = (useOriginalDate && origUnix) ? origUnix : ''; // '' => NULL server-side
  var html = '';

  for (var i = 1; i <= count; i++) {
     html += '<tr id="'+i+'">';
    html +=   '<td width="20px">'+i+'</td>';
    html +=   '<td><input name="plantnumber'+i+'" class="form-control"></td>';
    html +=   '<td><input name="serialnumber'+i+'" class="form-control"></td>';
    html +=   '<td><input name="manf'+i+'" class="form-control" placeholder="Manufacturer" value="<?= htmlspecialchars($td['manf'] ?? '', ENT_QUOTES) ?>"></td>';
    html +=   '<td><input name="dateofmanf'+i+'" class="form-control" placeholder="Date of manufacture" value="<?= htmlspecialchars($td['dateofmanf'] ?? '', ENT_QUOTES) ?>"></td>';
    html +=   '<td><input name="model'+i+'" class="form-control" placeholder="Model" value="<?= htmlspecialchars($td['model'] ?? '', ENT_QUOTES) ?>"></td>';
   html += '<td data-label="Sublocation">' + getSublocSelect('subloc' + i) + '</td>';
    html +=   '<td>';
    html +=     '<input name="swl'+i+'" class="form-control" placeholder="SWL" value="<?= htmlspecialchars($td['swl'] ?? '', ENT_QUOTES) ?>">';
   html +=   '<input type="hidden" data-role="duedate" name="duedate'+i+'" value="'+dateVal+'">';
    html +=   '</td>';

    html += '</tr>';
  }
  document.querySelector('#cloneList tbody').innerHTML = html;
}


// Update existing hidden duedate fields when toggled
var ORIG_DUEDATE_UNIX = <?= (isset($td['duedate']) && (int)$td['duedate'] > 0) ? (int)$td['duedate'] : 'null' ?>;

// set hidden currdate fields based on toggle
function updateDuedateFields() {
  var useOrig = document.getElementById('useOriginalDateSwitch').checked;
  var val = (useOrig && ORIG_DUEDATE_UNIX) ? ORIG_DUEDATE_UNIX : '';
  document.querySelectorAll('#cloneList tbody input[data-role="duedate"]').forEach(function(inp){
    inp.value = val; // '' => store NULL server-side (use NULLIF)
  });
}
document.getElementById('useOriginalDateSwitch').addEventListener('change', updateDuedateFields);


updateDuedateFields(); // ensure rows reflect current toggle

document.getElementById('cloneForm').addEventListener('submit', function(event) {
  event.preventDefault();
  var formData = new FormData(document.getElementById('cloneForm'));
  formData.append('tenant', TENANT_URL);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', ROOT_URL + '/includes/master/clone_functions.php', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

  xhr.onload = function() {
    if (xhr.status === 200) {
      var result = xhr.responseText.trim();
      document.getElementById('popupBox').classList.remove('show');
      showResponse('success', 'Your clones have been created successfully');
      document.location.href = 'index.php?t=includes/master&p=client.php&clientnumber=<?= (int)$d[0]?>&clientname=<?= urlencode($d[4])?>&view=asset';
    }
  };
  xhr.send(new URLSearchParams(formData).toString());
});

function submitForm() { document.getElementById('frmSub').click(); }


function autoFillPlantNumbers() {
  const inputs = document.querySelectorAll('#cloneList tbody input[name^="plantnumber"]');
  if (!inputs.length) return;

  let seedIndex = -1, seedVal = '';
  for (let i = 0; i < inputs.length; i++) {
    const v = inputs[i].value.trim();
    if (v !== '') { seedIndex = i; seedVal = v; break; }
  }
  if (seedIndex === -1) {
    const dest = `
      <p>Enter starting plant number (e.g. P001):</p>
      <input type="text" id="plantSeed" class="form-control" placeholder="P001" />
    `;
    loadModalContent(
      dest, "seedBox", "modal-sm", 1060, "false", "Specify Plant Number Seed", "cancelConfirm",
      () => {
        const val = document.getElementById('plantSeed').value.trim();
        if (!val) { showResponse('warning', 'Enter a starting plant number'); return false; }
        killModal('seedBox');
        autoFillFromSeed(inputs, val, 0);
      }
    );
    return;
  }
  autoFillFromSeed(inputs, seedVal, seedIndex);
}

function autoFillFromSeed(inputs, seedVal, seedIndex) {
  const m = seedVal.match(/^(\D*)(\d+)$/);
  let prefix, start, width;
  if (m) { prefix = m[1]; start = parseInt(m[2],10); width = m[2].length; }
  else   { prefix = seedVal; start = 1; width = 0; }
  for (let i = 0; i < inputs.length; i++) {
    const n = start + (i - seedIndex);
    inputs[i].value = prefix + (width ? String(n).padStart(width,'0') : String(n));
  }
}


var saElement = document.querySelector('#popupBox .modal-footer');
if (saElement) {
  saElement.innerHTML = '<div class="col-md-12 text-center"><a onclick="submitForm()" class="btn btn-info">Clone items</a></div>';
}
function getSublocSelect(name){
  return '<select name="'+name+'" class="form-select" onchange="handleSublocChange(this)"><?= $sublocOptions ?></select>';
}

function handleSublocChange(sel){
  if (sel.value === '') { // "Define new"
    const td = sel.parentNode;
    const name = sel.name;

    const input = document.createElement('input');
    input.type = 'text';
    input.name = name;               // keep same name for POST
    input.className = 'form-control';
    input.placeholder = 'Enter sublocation';

    const revert = document.createElement('button');
    revert.type = 'button';
    revert.className = 'btn btn-sm btn-outline-secondary mt-1';
    revert.textContent = 'Choose from list';
    revert.addEventListener('click', function(){
      td.innerHTML = getSublocSelect(name);
    });

    td.innerHTML = '';
    td.appendChild(input);
    td.appendChild(revert);
  }
}
</script>
