<?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 clone-item-header">
  <div class="col-md-12 text-center p-1 alert-warning text-dark clone-item-warning">
    <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 clone-item-controls">
    <div class="clone-count-control">
      <label for="clones" class="lead me-2 align-middle">Set Number of required <?= $d[3]?>'s</label>
      <input type="text" id="clones" class="form-control d-inline-block w-auto align-middle" placeholder="Add number" onkeyup="genClones()">
      <button type="button" class="btn btn-info btn-sm clone-mobile-autofill mt-2" onclick="autoFillPlantNumbers()">
        <i class="fad fa-magic"></i> Auto-fill Plant Numbers
      </button>
    </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>
<style>
#clonebox {
  overflow-x: hidden;
}
#cloneList {
  table-layout: fixed;
  width: 100%;
}
#cloneList th,
#cloneList td {
  vertical-align: middle;
}
#cloneList .form-control,
#cloneList .form-select {
  min-width: 0;
  width: 100%;
}
.clone-mobile-autofill {
  display: none;
}
@media (min-width: 768px) and (max-width: 1199.98px) {
  .clone-item-controls {
    align-items: flex-end !important;
  }
  .clone-count-control {
    flex: 1 1 320px;
  }
  .clone-count-control input {
    width: 220px !important;
  }
  .clone-mobile-autofill {
    display: inline-flex;
    margin-left: .5rem;
  }
  #cloneList,
  #cloneList tbody,
  #cloneList tr,
  #cloneList td {
    display: block;
    width: 100%;
  }
  #cloneList thead {
    display: none;
  }
  #cloneList {
    border-collapse: separate;
    border-spacing: 0;
  }
  #cloneList tbody tr {
    background: #fff;
    border: 1px solid rgba(0, 0, 0, .12);
    border-radius: 6px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, .05);
    display: grid;
    gap: .6rem .75rem;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    margin-bottom: .75rem;
    padding: .75rem;
  }
  #cloneList tbody td {
    border: 0;
    padding: 0;
  }
  #cloneList tbody td::before {
    color: #6c757d;
    content: attr(data-label);
    display: block;
    font-size: .72rem;
    font-weight: 700;
    line-height: 1.15;
    margin-bottom: .22rem;
    text-transform: uppercase;
  }
  #cloneList tbody td.clone-row-number {
    align-items: center;
    display: flex;
    font-weight: 700;
    grid-column: 1 / -1;
    justify-content: space-between;
  }
  #cloneList tbody td.clone-row-number::before {
    content: "Clone row";
    margin: 0;
  }
  #cloneList .form-control,
  #cloneList .form-select {
    font-size: .92rem;
    min-height: 34px;
    padding: .35rem .5rem;
  }
}
@media (max-width: 767.98px) {
  .clone-item-header {
    margin-left: 0;
    margin-right: 0;
  }
  .clone-item-warning {
    font-size: .95rem;
    line-height: 1.4;
    padding: .65rem !important;
  }
  .clone-item-controls {
    align-items: stretch !important;
    gap: .75rem !important;
  }
  .clone-count-control,
  .clone-count-control input {
    width: 100% !important;
  }
  .clone-mobile-autofill {
    display: inline-flex;
    justify-content: center;
    width: 100%;
  }
  .clone-count-control label {
    display: block;
    font-size: .9rem;
    font-weight: 600;
    line-height: 1.25;
    margin-bottom: .35rem;
  }
  #cloneList,
  #cloneList tbody,
  #cloneList tr,
  #cloneList td {
    display: block;
    width: 100%;
  }
  #cloneList thead {
    display: none;
  }
  #cloneList {
    border-collapse: separate;
    border-spacing: 0;
  }
  #cloneList tbody tr {
    background: #fff;
    border: 1px solid rgba(0, 0, 0, .12);
    border-radius: 6px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, .05);
    display: grid;
    gap: .55rem .65rem;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    margin-bottom: .75rem;
    padding: .65rem;
  }
  #cloneList tbody td {
    border: 0;
    padding: 0;
  }
  #cloneList tbody td::before {
    color: #6c757d;
    content: attr(data-label);
    display: block;
    font-size: .72rem;
    font-weight: 700;
    line-height: 1.15;
    margin-bottom: .22rem;
    text-transform: uppercase;
  }
  #cloneList tbody td.clone-row-number {
    align-items: center;
    display: flex;
    font-weight: 700;
    grid-column: 1 / -1;
    justify-content: space-between;
  }
  #cloneList tbody td.clone-row-number::before {
    content: "Clone row";
    margin: 0;
  }
  #cloneList tbody td.clone-field-wide {
    grid-column: 1 / -1;
  }
  #cloneList .form-control,
  #cloneList .form-select {
    font-size: .92rem;
    min-height: 34px;
    padding: .35rem .5rem;
  }
}
</style>
<?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" class="clone-row-number" data-label="Clone row">'+i+'</td>';
    html +=   '<td data-label="Plant Number"><input name="plantnumber'+i+'" class="form-control"></td>';
    html +=   '<td data-label="Serial"><input name="serialnumber'+i+'" class="form-control"></td>';
    html +=   '<td data-label="Manufacturer"><input name="manf'+i+'" class="form-control" placeholder="Manufacturer" value="<?= htmlspecialchars($td['manf'] ?? '', ENT_QUOTES) ?>"></td>';
    html +=   '<td data-label="Manufacture Date"><input type="text" name="dateofmanf'+i+'" class="form-control" placeholder="Manufacture date" value="<?= htmlspecialchars($td['dateofmanf'] ?? '', ENT_QUOTES) ?>"></td>';
    html +=   '<td data-label="Model"><input name="model'+i+'" class="form-control" placeholder="Model" value="<?= htmlspecialchars($td['model'] ?? '', ENT_QUOTES) ?>"></td>';
   html += '<td data-label="Sublocation" class="clone-field-wide">' + getSublocSelect('subloc' + i) + '</td>';
    html +=   '<td data-label="SWL" class="clone-field-wide">';
    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('cloneBox').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('#cloneBox .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>
