<div id="modeSwitch" class="row">
  <div id="prompt" class="col-12" style="display:<?= $alertDelivery?>">
    <p class="alert alert-danger text-center">A revision has been detected - Reissue documents</p>
  </div>

  <div class="col-12">
    <!-- Tabs navigation -->
    <ul class="nav nav-tabs mb-3" id="wsTabs" role="tablist">
      <li class="nav-item" role="presentation">
        <button class="nav-link active" id="details-tab" data-mdb-toggle="tab"
          data-mdb-target="#details-content" type="button" role="tab"
          aria-controls="details-content" aria-selected="true"
          data-mdb-tooltip-init title="Written Scheme Details">
          <i class="fad fa-file-alt"></i> Details
        </button>
      </li>

      <li class="nav-item" role="presentation">
        <button class="nav-link" id="parts-tab" data-mdb-toggle="tab"
          data-mdb-target="#parts-content" type="button" role="tab"
          aria-controls="parts-content" aria-selected="false"
          data-mdb-tooltip-init title="Parts Of the system">
          <i class="fad fa-cogs"></i> Parts
        </button>
      </li>

      <li class="nav-item" role="presentation">
        <button class="nav-link" id="revisions-tab" data-mdb-toggle="tab"
          data-mdb-target="#revisions-content" type="button" role="tab"
          aria-controls="revisions-content" aria-selected="false"
          data-mdb-tooltip-init title="Revisions to the system">
          <i class="fad fa-sync-alt"></i> Revisions
        </button>
      </li>

      <li class="nav-item" role="presentation">
        <button class="nav-link <?php if (!file_exists('../../../'.TENANT_URL . '/output/wsfiles/' . $cd['clientnumber'] . '/WS' . $_REQUEST['ws'] . '.pdf')) { echo 'disabled'; } ?>"
          id="delivery-tab" data-mdb-toggle="tab" data-mdb-target="#delivery-content"
          type="button" role="tab" aria-controls="delivery-content" aria-selected="false"
          data-mdb-tooltip-init title="Deliver documents">
          <i class="fad fa-truck"></i> Delivery
        </button>
      </li>
    </ul>

    <!-- Downloads -->
    <div class="d-flex gap-2 mb-3" id="wsDownloads">
      <span id="wsDownload">
        <?php if (file_exists('../../../'.TENANT_URL . '/output/wsfiles/' . $n['clientnumber'] . '/WS' . $_REQUEST['ws'] . '_ws.zip')) { ?>
          <a class="btn btn-info btn-sm"
            href="output/wsfiles/<?= $n['clientnumber'] ?>/WS<?= $_REQUEST['ws'] ?>_ws.zip?<?= rand() ?>"
            target="_blank" data-mdb-tooltip-init title="View stored WS documentation">
            <i class="fad fa-file-pdf"></i> WS
          </a>
        <?php } ?>
      </span>

      <span id="fullDownload">
        <?php if (file_exists('../../../'.TENANT_URL . '/output/wsfiles/' . $n['clientnumber'] . '/WS' . $_REQUEST['ws'] . '_full.zip')) { ?>
          <a class="btn btn-info btn-sm"
            href="output/wsfiles/<?= $n['clientnumber'] ?>/WS<?= $_REQUEST['ws'] ?>_full.zip?<?= rand() ?>"
            target="_blank" data-mdb-tooltip-init title="View stored WS documentation">
            <i class="fad fa-file-pdf"></i> Full Pack
          </a>
        <?php } ?>
      </span>
    </div>

    <!-- Tab content -->
    <div class="tab-content" id="myTabContent">
      <!-- Details -->
      <div class="tab-pane fade show active" id="details-content" role="tabpanel" aria-labelledby="details-tab">
        <div class="card" style="display: block;">
          <div class="card-header">File</div>
          <div class="card-body">
            <div class="row">
              <div class="col-12 col-md-6">
                <div class="mb-3 row align-items-center">
                  <label for="scheme_number_alt" class="col-3 col-form-label">WS number</label>
                  <div class="col-7">
                    <input type="text" class="form-control" id="scheme_number_alt" name="scheme_number_alt" value="<?= htmlspecialchars($n['scheme_number_alt'], ENT_QUOTES, 'UTF-8') ?>">
                  </div>
                  <div class="col-2">
                    <button class="btn btn-info btn-sm" id="but_save">Save</button>
                  </div>
                </div>

                <div class="mb-3">
                  <label for="surveyor" class="form-label">Certified by</label>
                  <div>
                    <?= listSurveyor($n['surveyor'], 'surveyor', 'select') ?>
                  </div>
                </div>
              </div>

              <div class="col-12 col-md-6">
                <div class="mb-3">
                  <label for="file" class="form-label">Upload File</label>
                  <div class="input-group">
                    <input type="file" class="form-control" id="file" aria-label="Upload">
                    <button class="btn btn-success btn-sm" id="but_upload">Upload</button>
                  </div>
                  <div class="form-text">Choose a file to upload.</div>
                </div>

                <?php if(file_exists('../../../'.TENANT_URL.'/output/wsfiles/'.$cd['clientnumber'].'/WS'.$_REQUEST['ws'].'.pdf')) { ?>
                  <div id="attach" class="mt-4">
                    <div class="lead mb-2">Existing File:</div>
                    <div class="d-flex justify-content-between">
                      <a class="btn btn-secondary btn-sm" href="output/wsfiles/<?= $cd['clientnumber'] ?>/WS<?= $_REQUEST['ws'] ?>.pdf?<?=rand()?>" target="_blank">
                        <i class="fad fa-file-pdf"></i> Download
                      </a>
                      <a class="btn btn-danger btn-sm" href="output/wsfiles/<?= $cd['clientnumber'] ?>/WS<?= $_REQUEST['ws'] ?>.pdf?<?=rand()?>" target="_blank">
                        <i class="fad fa-trash"></i>
                      </a>
                    </div>
                  </div>
                <?php } else { ?>
                  <div id="attach" class="mt-4">
                    <span class="text-danger">NO FILE ATTACHED</span>
                  </div>
                <?php } ?>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Parts -->
      <div class="tab-pane fade" id="parts-content" role="tabpanel" aria-labelledby="parts-tab">
        <div class="card">
          <div class="card-header d-flex justify-content-between align-items-center">
            <span>Parts</span>
            <button class="btn btn-success btn-sm" type="button" data-mdb-toggle="collapse" data-mdb-target="#parts" aria-expanded="false" aria-controls="parts">
              <i class="fad fa-plus"></i>
            </button>
          </div>
          <div id="parts" class="collapse" style="max-height:200px; overflow-y:auto;">
            <div class="card-body">
              <h2><small>Add new item to the Written Scheme</small></h2>
              <table id="inactive" class="table table-sm table-striped">
                <thead>
                  <tr>
                    <th>Item</th>
                    <th>Serial</th>
                    <th>Plant Number</th>
                    <th></th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  <?php while ($itd = mysqli_fetch_array($ic)) {
                    if (in_array($itd['itemnumber'], $ilist) || in_array($itd['itemnumber'], $lilist)) { continue; } ?>
                    <tr>
                      <td><?= htmlspecialchars($itd['desc'], ENT_QUOTES, 'UTF-8') ?></td>
                      <td><?= htmlspecialchars($itd['serialnumber'], ENT_QUOTES, 'UTF-8') ?></td>
                      <td><?= htmlspecialchars($itd['plantnumber'], ENT_QUOTES, 'UTF-8') ?></td>
                      <td>
                        <a href="index.php?t=includes/master&p=asset.php&view=edit_attached&data=<?= htmlspecialchars($itd['clientnumber']) ?>|<?= htmlspecialchars($itd['locnumber']) ?>|<?= htmlspecialchars($itd['itemnumber']) ?>"
                          class="btn btn-info btn-sm" data-mdb-tooltip-init title="View <?= htmlspecialchars($itd['desc'], ENT_QUOTES, 'UTF-8') ?>">
                          <i class="fad fa-eye"></i>
                        </a>
                      </td>
                      <td>
                        <a id="A<?= htmlspecialchars($itd['itemnumber'], ENT_QUOTES, 'UTF-8') ?>" href="javascript:void(0)" class="btn btn-success btn-sm"
                          onclick="addConfirm('<?= htmlspecialchars($itd['itemnumber'], ENT_QUOTES, 'UTF-8') ?>', 'A<?= htmlspecialchars($itd['itemnumber'], ENT_QUOTES, 'UTF-8') ?>')"
                          data-mdb-tooltip-init title="Add <?= htmlspecialchars($itd['desc'], ENT_QUOTES, 'UTF-8') ?>">
                          <i class="fad fa-plus-circle"></i>
                        </a>
                      </td>
                    </tr>
                  <?php } ?>
                </tbody>
              </table>

              <h2><small>Current items covered by this Written Scheme</small></h2>
              <div id="list" style="max-height:200px; overflow-y:auto;">
                <table id="active" class="table table-sm table-striped">
                  <thead>
                    <tr>
                      <th>Item</th>
                      <th>Serial</th>
                      <th>Plant Number</th>
                      <th></th>
                      <th></th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php foreach ($itable as $aws) {
                      $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`itemnumber`,`desc`,`serialnumber`,`plantnumber`,`locnumber` FROM `itemdetails` WHERE `itemnumber`=?");
                      $stmt->bind_param('i', $aws['itemnumber']);
                      $stmt->execute();
                      $icx = $stmt->get_result();
                      $stmt->close();
                      $itd = mysqli_fetch_array($icx); ?>
                      <tr>
                        <td><?= htmlspecialchars($itd['desc'], ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= htmlspecialchars($itd['serialnumber'], ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= htmlspecialchars($itd['plantnumber'], ENT_QUOTES, 'UTF-8') ?></td>
                        <td>
                          <a href="index.php?t=includes/master&p=asset.php&view=edit_attached&data=<?= htmlspecialchars($itd['clientnumber']) ?>|<?= htmlspecialchars($itd['locnumber']) ?>|<?= htmlspecialchars($itd['itemnumber']) ?>"
                            class="btn btn-info btn-sm" data-mdb-tooltip-init title="View <?= htmlspecialchars($itd['desc'], ENT_QUOTES, 'UTF-8') ?>">
                            <i class="fad fa-eye"></i>
                          </a>
                        </td>
                        <td>
                          <a id="R<?= htmlspecialchars($itd['itemnumber'], ENT_QUOTES, 'UTF-8') ?>" href="javascript:void(0)" class="btn btn-danger btn-sm"
                            onclick="delConfirm('<?= htmlspecialchars($itd['itemnumber'], ENT_QUOTES, 'UTF-8') ?>', 'R<?= htmlspecialchars($itd['itemnumber'], ENT_QUOTES, 'UTF-8') ?>')"
                            data-mdb-tooltip-init title="Remove <?= htmlspecialchars($itd['desc'], ENT_QUOTES, 'UTF-8') ?>">
                            <i class="fad fa-minus-circle"></i>
                          </a>
                        </td>
                      </tr>
                    <?php } ?>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Revisions -->
      <div class="tab-pane fade" id="revisions-content" role="tabpanel" aria-labelledby="revisions-tab">
        <div class="card">
          <div class="card-header d-flex justify-content-between align-items-center">
            <span>Revisions</span>
            <button id="newButton" class="btn btn-secondary btn-sm" onclick="newItem()">Manual Entry</button>
          </div>
          <div class="card-body">
            <div id="newItem" class="row mb-2" style="display: none;">
              <div class="col-md-4">
                <div class="mb-2">
                  <input id="nDate" class="form-control" name="nDate" placeholder="Date" type="date">
                </div>
                <div>
                  <?php
                    if ($_SESSION['usertype'] == 'surveyor') { $surv = $_SESSION['userid']; } else { $surv = ''; }
                    echo listSurveyor($surv, 'nSurveyor', 'select');
                  ?>
                </div>
              </div>

              <div class="col-md-8">
                <textarea id="nDesc" class="form-control" name="nDesc" rows="5" placeholder="Description"></textarea>
              </div>

              <div class="col-12 mt-2">
                <button class="btn btn-success btn-sm" onclick="addRevision()">
                  <i class="fad fa-plus"></i> Register Entry
                </button>
              </div>
            </div>

            <table id="revTable" class="table table-striped table-sm">
              <thead>
                <tr>
                  <th>Date of Revision</th>
                  <th>Record of Modification</th>
                  <th>Surveyor</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                <?= getPssrReviews($_REQUEST['ws']) ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- Delivery -->
      <div class="tab-pane fade" id="delivery-content" role="tabpanel" aria-labelledby="delivery-tab">
        <div class="card">
          <div class="card-header">Delivery</div>
          <div class="card-body">
            <div id="delConf" class="text-center mb-4">
              <?php
                $stmt = $GLOBALS['con']->prepare("SELECT * FROM `wsitems` WHERE `wsnumber`=? AND `type`='1'") or die(mysqli_error($GLOBALS['con']));
                $stmt->bind_param('i', $n['id']);
                $stmt->execute();
                $wsi = $stmt->get_result();
                $stmt->close();
                while ($idata = mysqli_fetch_array($wsi)) {
                  $stmt2 = $GLOBALS['con']->prepare("SELECT `repnumber` FROM `reportitems` WHERE `itemnumber`='" . $idata['itemnumber'] . "' ORDER BY abs(repitem) DESC LIMIT 1");
                  $stmt2->execute();
                  $wsit = $stmt2->get_result();
                  $stmt2->close();
                  $itdata = mysqli_fetch_array($wsit);
                  $items .= $itdata['repnumber'] . "_" . $idata['itemnumber'] . "|";
                  $delitems .= "../output/reports/" . $cd['clientnumber'] . "/" . $itdata['repnumber'] . "_" . $idata['itemnumber'] . ".pdf,";
                }
              ?>
              <a class="btn btn-secondary" href="javascript:void(0)" onclick="genEWS('single')">Send Written Scheme</a>
              <a class="btn btn-info" href="javascript:void(0)" onclick="genEWS('full')">Send Written Scheme &amp; Reports</a>
            </div>

            <div id="loadingBlock" class="text-center" style="display: none;">
              <h1>
                <i class="fad fa-spinner fa-spin fa-3x"></i>
                <br>Generating Documents<br>
                <small>Please wait</small>
              </h1>
            </div>

            <div id="deliveryMode" style="display: none;"></div>
            <div id="delMail" style="display: none;">
              <?php
                $_REQUEST['mode'] = "popup";
                $_REQUEST['data'] = $itd['clientnumber'] . '|' . $cd['clientname'] . '|' . $cd['email'] . '|Your Written Scheme|Please find enclosed your written scheme documentation|output/wsfiles/' . $itd['clientnumber'] . '|WS' . $_REQUEST['ws'] . '.pdf';
                include('mailer.php');
              ?>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
// ---- MDB UMD init for dynamically injected content ----
(function initWSUI(){
  // Tabs
  document.querySelectorAll('button[data-mdb-toggle="tab"]').forEach(el => {
    if (!mdb.Tab.getInstance(el)) new mdb.Tab(el);
  });
  // Tooltips

  // Collapses
  document.querySelectorAll('.collapse').forEach(el => {
    if (!mdb.Collapse.getInstance(el)) new mdb.Collapse(el, { toggle:false });
  });
})();

// ---- Actions ----
document.getElementById('but_save').addEventListener('click', function() {
  const w = document.getElementById('scheme_number_alt').value;
  fetch(ROOT_URL+'/includes/master/ws_functions.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      mode: 'saveAlt',
      id: '<?= $n['id']?>',
      scheme_number_alt: w,
      tenant: TENANT_URL
    })
  }).then(r=>r.text()).then(()=>{
    document.getElementById('scheme_number_alt').classList.add('is-valid');
  });
});

document.getElementById('surveyor').addEventListener('change', function() {
  const w = this.value;
  fetch(ROOT_URL+'/includes/master/ws_functions.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      mode: 'saveSurv',
      id: '<?= $n['id']?>',
      surveyor: w,
      tenant: TENANT_URL
    })
  }).then(r=>r.text()).then(()=>{
    document.getElementById('surveyor').classList.add('is-valid');
  });
});

document.getElementById('but_upload').addEventListener('click', function() {
  const fd = new FormData();
  const files = document.getElementById('file').files[0];
  if (!files) { showResponse('warning','Select a file first'); return; }
  fd.append('file', files);
  fd.append('clientnumber', '<?= $cd['clientnumber']?>');
  fd.append('wsno', '<?= $_REQUEST['ws']?>');
  fd.append('tenant', TENANT_URL);

  fetch(ROOT_URL + '/functions/wsupload.php', { method: 'POST', body: fd })
    .then(r=>r.text()).then(response => {
      if (response.trim() === 's') {
        document.getElementById('attach').innerHTML = `
          <div class="lead mb-2">Existing File:</div>
          <div class="d-flex justify-content-between">
            <a class="btn btn-secondary btn-sm" href="output/wsfiles/<?= $cd['clientnumber']?>/WS<?= $_REQUEST['ws']?>.pdf?${Date.now()}" target="_blank">
              <i class="fad fa-file-pdf"></i> Download
            </a>
            <a class="btn btn-danger btn-sm" href="output/wsfiles/<?= $cd['clientnumber']?>/WS<?= $_REQUEST['ws']?>.pdf?${Date.now()}" target="_blank">
              <i class="fad fa-trash"></i>
            </a>
          </div>`;
        document.getElementById('file').value = '';
      } else {
        parent.showResponse('danger', 'File not uploaded');
      }
    });
});

// ---- Revisions ----
function addRevision() {
  const d = document.getElementById('nDate').value;
  const s = document.getElementById('nSurveyor').value;
  const r = document.getElementById('nDesc').value;
  const w = "<?= $_REQUEST['ws']?>";

  fetch(ROOT_URL + '/includes/master/ws_functions.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({ mode:'addRevision', date:d, surveyor:s, desc:r, wsnumber:w, tenant:TENANT_URL })
  })
  .then(r=>r.text())
  .then(ret => {
    const dta = ret.split('|');
    if (dta[0] === "success") {
      document.getElementById('prompt').style.display = 'block';
      document.querySelector('#revTable tbody').innerHTML = dta[1];
      closeNew();
      showResponse('success', 'Manual revision added successfully');
    }
  });
}

// Use your modal loader, not jQuery
function autofill(f, s, t) {
  const url = `${ROOT_URL}/includes/master/form_options.php?form=${encodeURIComponent(f)}&source=${encodeURIComponent(s)}&type=${encodeURIComponent(t)}&tenant=${TENANT_URL}`;
  loadModalContent(url, 'popupBox', 'modal-lg', 900, 'true', 'Autofill Options', 'close');
}

function newItem() {
  document.getElementById('newItem').style.display = 'block';
  document.getElementById('newButton').setAttribute('onclick', 'closeNew()');
}
function closeNew() {
  document.getElementById('nDate').value = '';
  document.getElementById('nSurveyor').value = '';
  document.getElementById('nDesc').value = '';
  document.getElementById('newItem').style.display = 'none';
  document.getElementById('newButton').setAttribute('onclick', 'newItem()');
}

function cloneWse(i) {
  const d = document.querySelector(`#${i} .wsDesc`).textContent;
  const s = document.querySelector(`#${i} .wsSWL`).textContent;
  document.getElementById('wseDesc').value = d;
  document.getElementById('wseSwl').value = s;
}

// ---- Delivery ----
function genEWS(i) {
  document.getElementById('delConf').style.display = 'none';
  document.getElementById('loadingBlock').style.display = 'block';

  fetch(ROOT_URL + '/functions/generators/genEWsPDF.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({ clientnumber:'<?= $n['clientnumber']?>', wsnumber:'<?= $_REQUEST['ws']?>', tenant:TENANT_URL })
  })
  .then(r=>r.text())
  .then(result => {
    fetch(ROOT_URL + '/functions/generators/genECover.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ items:'<?= $items?>', wsnumber:'<?= $_REQUEST['ws']?>', clientnumber:'<?= $n['clientnumber']?>', tenant:TENANT_URL })
    })
    .then(()=> {
      fetch(ROOT_URL + '/functions/generators/genEZIP.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({ mode:i, clientnumber:'<?= $n['clientnumber']?>', wsnumber:'<?= $_REQUEST['ws']?>', items:'<?= $items?>' })
      })
      .then(r=>r.text())
      .then(zipPath => {
        document.getElementById('attachment_1').value = zipPath;
        document.getElementById('source_1').value = 'output/wsfiles/<?= $n['clientnumber']?>';
        if (i === "single") {
          document.getElementById('wsDownload').innerHTML = `
            <a class="btn btn-info btn-sm" href="output/wsfiles/<?= $n['clientnumber']?>/WS<?= $_REQUEST['ws']?>_ws.zip?${Date.now()}" target="_blank" data-mdb-tooltip-init title="View stored WS documentation">
              <i class="fad fa-file-pdf"></i> WS
            </a>`;
        }
        if (i === "full") {
          document.getElementById('deliveryMode').textContent = 'reps';
          document.getElementById('fullDownload').innerHTML = `
            <a class="btn btn-info btn-sm" href="output/wsfiles/<?= $n['clientnumber']?>/WS<?= $_REQUEST['ws']?>_full.zip?${Date.now()}" target="_blank" data-mdb-tooltip-init title="View stored WS documentation">
              <i class="fad fa-file-pdf"></i> Full Pack
            </a>`;
        }
        mdb.Tooltip.init(document.querySelectorAll('[data-mdb-tooltip-init]'));
      });

      if (result.trim() === "success") {
        document.getElementById('loadingBlock').style.display = 'none';
        document.getElementById('delMail').style.display = 'block';

        fetch(ROOT_URL + '/includes/master/ws_functions.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: new URLSearchParams({ mode:'setWSIDel', wsnumber:'<?= $n['id']?>', clientnumber:'<?= $n['clientnumber']?>' })
        });
      }
    });
  });
}

// ---- Confirm helpers (no jQuery) ----
function reviewConfirm() {
  confirmBox("Add Item", "You are adding a blank confirmation of review without alteration", "addReview()");
}
function addReview() {
  fetch(ROOT_URL + '/includes/master/ws_functions.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      mode:'addReview',
      wsnumber:'<?= $n['id']?>',
      clientnumber:'<?= $n['clientnumber']?>',
      surveyor: document.getElementById('surveyor').value
    })
  }).then(r=>r.text()).then(()=>{
    showResponse('success', 'The review has been successfully added to the WS');
    killModal('confirmBox');
    document.getElementById('prompt').style.display = 'block';
  });
}

function addEConfirm() {
  confirmBox("Add Item", "Are you sure you wish to add this exclusion to the Written Scheme?", "addEPart()");
}
function addEPart() {
  const val = Math.floor(1000 + Math.random() * 9000);
  fetch(ROOT_URL + '/includes/master/ws_functions.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      mode:'addWSIE',
      wsnumber:'<?= $n['id']?>',
      clientnumber:'<?= $n['clientnumber']?>',
      desc: document.getElementById('wseDesc').value,
      swl: document.getElementById('wseSwl').value,
      tenant:TENANT_URL
    })
  }).then(r=>r.text()).then(()=>{
    showResponse('success', 'The exclusion has been successfully added to the WS');
    killModal('confirmBox');
    const newRow = `
      <tr id="R${val}">
        <td class="wsDesc">${document.getElementById('wseDesc').value}</td>
        <td class="wsSWL">${document.getElementById('wseSwl').value}</td>
        <td>
          <a href="javascript:void(0)" class="btn btn-secondary btn-sm" onclick="cloneWse('R${val}')" data-mdb-tooltip-init title="Clone Exclusion">
            <i class="far fa-clone"></i>
          </a>
        </td>
      </tr>`;
    document.querySelector('#exList tbody').insertAdjacentHTML('beforeend', newRow);
    mdb.Tooltip.init(document.querySelectorAll('[data-mdb-tooltip-init]'));
  });
}

function delEConfirm(i, l) {
  confirmBox("Remove Exclusion", "Are you sure you wish to remove this exclusion from the Written Scheme?", `delEPart('${i}', '${l}')`);
}
function delEPart(i, l) {
  killModal('confirmBox');
  fetch(ROOT_URL + '/includes/master/ws_functions.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({ mode:'removeWSIE', id:i, clientnumber:'<?= $n['clientnumber']?>', tenant:TENANT_URL })
  }).then(r=>r.text()).then(()=>{
    showResponse('success', 'The exclusion has been successfully removed from the WS');
    const tr1 = document.getElementById(l).closest("tr");
    tr1.style.display = 'none';
  });
}

function addConfirm(i, l) {
  confirmBox("Add Item", "Are you sure you wish to add this item to the Written Scheme?<br><small>This will constitute a revision and documents should be re-submitted to the client</small>", `addPart('${i}', '${l}')`);
}
function addPart(i, l) {
  fetch(ROOT_URL + '/includes/master/ws_functions.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({ mode:'addWSI', wsnumber:'<?= $n['id']?>', clientnumber:'<?= $n['clientnumber']?>', itemnumber:i, tenant:TENANT_URL })
  }).then(r=>r.text()).then(()=>{
    showResponse('success', 'The item has been successfully added to the WS');
    killModal('confirmBox');
    const tr1 = document.getElementById(l).closest("tr");
    const cell1 = tr1.children[0].innerHTML;
    const cell2 = tr1.children[1].innerHTML;
    const cell3 = tr1.children[2].innerHTML;
    let cell4 = tr1.children[3].innerHTML;
    cell4 = cell4.replace('addConfirm', 'delConfirm')
                 .replace('fa-plus-circle', 'fa-minus-circle')
                 .replace('btn-outline-success', 'btn-outline-danger');
    document.querySelector('#active tbody').insertAdjacentHTML('beforeend', `<tr><td>${cell1}</td><td>${cell2}</td><td>${cell3}</td><td>${cell4}</td></tr>`);
    tr1.style.display = 'none';
    document.getElementById('prompt').style.display = 'block';
  });
}

function delConfirm(i, l) {
  confirmBox("Remove Item", "Are you sure you wish to remove this item from the Written Scheme?<br><small>This will constitute a revision and documents should be re-submitted to the client</small>", `delPart('${i}', '${l}')`);
}
function delPart(i, l) {
  fetch(ROOT_URL + '/includes/master/ws_functions.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({ mode:'removeWSI', wsnumber:'<?= $n['id']?>', clientnumber:'<?= $n['clientnumber']?>', itemnumber:i, tenant:TENANT_URL })
  }).then(r=>r.text()).then(()=>{
    showResponse('success', 'The item has been successfully removed from the WS');
    killModal('confirmBox');
    const tr2 = document.getElementById(l).closest("tr");
    const cell1 = tr2.children[0].innerHTML;
    const cell2 = tr2.children[1].innerHTML;
    const cell3 = tr2.children[2].innerHTML;
    let cell4 = tr2.children[3].innerHTML;
    cell4 = cell4.replace('delConfirm', 'addConfirm')
                 .replace('fa-minus-circle', 'fa-plus-circle')
                 .replace('btn-outline-danger', 'btn-outline-success');
    document.querySelector('#inactive tbody').insertAdjacentHTML('beforeend', `<tr><td>${cell1}</td><td>${cell2}</td><td>${cell3}</td><td>${cell4}</td></tr>`);
    tr2.style.display = 'none';
    document.getElementById('prompt').style.display = 'block';
  });
}

function remrevConfirm(i) {
  confirmBox("Remove revision entry", "Are you sure you wish to remove this revision entry from the Written Scheme?<br><small>This cannot be undone</small>", `remRev('${i}')`);
}
function remRev(i) {
  fetch(ROOT_URL + '/includes/master/ws_functions.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({ mode:'remRev', wsnumber:'<?= $n['id']?>', clientnumber:'<?= $n['clientnumber']?>', entry:i, tenant:TENANT_URL })
  }).then(r=>r.text()).then(()=>{
    showResponse('success', 'The entry has been successfully removed from the WS');
    killModal('confirmBox');
    const tr2 = document.getElementById(i).closest("tr");
    tr2.style.display = 'none';
  });
}

function relWs() {
  fetch(`${ROOT_URL}/includes/master/ws_data.php?clientnumber=<?= $n['clientnumber']?>`)
    .then(r=>r.text())
    .then(html => { document.getElementById('wsData').innerHTML = html; });
}

(function wireTabs(){
  const buttons = Array.from(document.querySelectorAll('button.nav-link[data-mdb-toggle="tab"]'));
  const panes   = Array.from(document.querySelectorAll('.tab-content .tab-pane'));
  if (!buttons.length || !panes.length) return;

  // Ensure one pane is active
  if (!panes.some(p => p.classList.contains('active'))) {
    const firstPane = document.querySelector('#details-content');
    if (firstPane) {
      panes.forEach(p => p.classList.remove('show','active'));
      firstPane.classList.add('active','show');
    }
    const firstBtn = document.getElementById('details-tab');
    if (firstBtn) {
      buttons.forEach(b => { b.classList.remove('active'); b.setAttribute('aria-selected','false'); });
      firstBtn.classList.add('active');
      firstBtn.setAttribute('aria-selected','true');
    }
  }

  // Bind click once
  buttons.forEach(btn => {
    if (btn.__wsBound) return;
    btn.__wsBound = true;

    btn.addEventListener('click', (e) => {
      if (btn.classList.contains('disabled')) { e.preventDefault(); return; }
      e.preventDefault();

      // Try MDB if present
      try {
        if (window.mdb && mdb.Tab && mdb.Tab.getOrCreateInstance) {
          mdb.Tab.getOrCreateInstance(btn).show();
          return;
        }
      } catch(_) {}

      // Fallback manual toggle
      const targetSel = btn.getAttribute('data-mdb-target');
      const target = targetSel && document.querySelector(targetSel);
      if (!target) return;

      buttons.forEach(b => { b.classList.remove('active'); b.setAttribute('aria-selected','false'); });
      panes.forEach(p => p.classList.remove('show','active'));

      btn.classList.add('active');
      btn.setAttribute('aria-selected','true');
      target.classList.add('active');
      void target.offsetWidth; // reflow
      target.classList.add('show');
    });
  });
})();
</script>
