<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">
        <?php
$basePath   = '../../../' . TENANT_URL . '/output/wsfiles/' . $cd['clientnumber'] . '/WS' . $_REQUEST['ws'];
$extensions = ['pdf', 'doc', 'docx'];

$hasFile = false;
foreach ($extensions as $ext) {
    if (file_exists($basePath . '.' . $ext)) {
        $hasFile = true;
        break;
    }
}
?>

<button class="nav-link <?= $hasFile ? '' : '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="<?= $hasFile ? 'Deliver documents' : 'No delivery document available' ?>">
    <i class="fad fa-truck"></i> Delivery
</button>

      </li>
      <li class="ms-auto">
                <div id="wsDownload" class="mt-3 mb-n3">
                    <?php if (file_exists('../../../' . TENANT_URL . '/output/wsfiles/' . $cd['clientnumber'] . '/WS' . $n['id'] . '.pdf')) { ?><a
                        class="btn btn-info btn-sm"
                        href="output/wsfiles/<?= $n['clientnumber'] ?>/WS<?= $n['id'] ?>.pdf?<?= rand() ?>"
                        target="_blank" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
                        data-mdb-placement="bottom" data-mdb-trigger="hover" data-mdb-placement="bottom" totitle="hover"
                        title="View stored WS documentation"><i class="fad fa-file-pdf"></i>
                        WS</a><?php } else {
                                } ?>
                </div>

                <div id="fullDownload" class="mt-3 mb-n3">
                    <?php if (file_exists('../../../' . TENANT_URL . '/output/wsfiles/' . $cd['clientnumber'] . '/WS' . $_REQUEST['ws'] . '_full.zip')) { ?><a
                        class="btn btn-info btn-sm"
                        href="output/wsfiles/<?= $cd['clientnumber'] ?>/WS<?= $_REQUEST['ws'] ?>_full.zip?<?= rand() ?>"
                        target="_blank" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
                        data-mdb-placement="bottom" data-mdb-trigger="hover" data-mdb-placement="bottom"
                        data-mdb-trigger="hover" data-mdb-placement="bottom" title="View stored WS documentation"><i
                            class="fad fa-file-pdf"></i> Full Pack</a><?php } else {
                                                                                                            } ?>
                </div>
            </li>
    </ul>

 

    <!-- 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 class="mb-3">
                  <label class="form-label">Revision</label>
                  <div>
                    <button type="button" class="btn btn-info btn-sm" onclick="editWsRevisionNumber()" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" title="Change WS revision number">
                      Revision <span id="wsRevNumber"><?= (int)$n['rev'] ?></span>
                    </button>
                  </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
                $basePathFs   = '../../../' . TENANT_URL . '/output/wsfiles/' . $cd['clientnumber'] . '/WS' . $_REQUEST['ws'];
                $basePathUrl  = 'output/wsfiles/' . $cd['clientnumber'] . '/WS' . $_REQUEST['ws'];
                $extensions   = ['pdf', 'doc', 'docx'];
                
                $foundExt = null;
                
                foreach ($extensions as $ext) {
                    if (file_exists($basePathFs . '.' . $ext)) {
                        $foundExt = $ext;
                        break;
                    }
                }
                ?>
                
                <div id="attach" class="mt-4">
                <?php if ($foundExt): ?>
                
                    <div class="lead mb-2">Existing File:</div>
                
                    <?php
                    // Icon by type
                    if ($foundExt === 'pdf') {
                        $icon = 'fa-file-pdf';
                    } elseif ($foundExt === 'doc' || $foundExt === 'docx') {
                        $icon = 'fa-file-word';
                    } else {
                        $icon = 'fa-file';
                    }
                   ?>
                
                    <div class="d-flex justify-content-between">
                        <a class="btn btn-secondary btn-sm"
                           href="<?= $basePathUrl . '.' . $foundExt ?>?<?= rand() ?>"
                           target="_blank">
                            <i class="fad <?= $icon ?>"></i> Download
                        </a>
                
                        <a class="btn btn-danger btn-sm"
                           href="<?= $basePathUrl . '.' . $foundExt ?>?<?= rand() ?>"
                           target="_blank">
                            <i class="fad fa-trash"></i>
                        </a>
                    </div>
                
                <?php else: ?>
                
                    <span class="text-danger">NO FILE ATTACHED</span>
                
                <?php endif; ?>
                </div>

              </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" onclick="toggleVisibility('parts')">
                            <i class="fad fa-plus"></i> Add parts
                        </button>
                    </div>
                    <div class="card-body">
                        <!-- Section to add new items -->
                        <div id="parts" class="mb-4" style="max-height:200px; overflow-y:auto; display:none">
                            <h5 class="d-flex align-items-center gap-3 flex-wrap">
                                <small>Add new item to the Written Scheme</small>
                                <div class="input-group input-group-sm ws-parts-search-group" style="width:260px; max-width:100%;">
                                    <span class="input-group-text"><i class="fad fa-search"></i></span>
                                    <input type="search" class="form-control ws-parts-search" id="wsPartsAddSearch" data-ws-filter-target="inactive" placeholder="Search add items" aria-label="Search add items">
                                </div>
                                <button class="btn btn-info btn-sm ms-auto" onclick="toggleVisibility('parts')">Hide</button>
                            </h5>
                            <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']) ?></td>
                                        <td><?= htmlspecialchars($itd['serialnumber']) ?></td>
                                        <td><?= htmlspecialchars($itd['plantnumber']) ?></td>
                                        <td>
                                            <a href="index.php?t=includes/master&p=asset.php&view=edit_attached&data=<?= $itd['clientnumber'] ?>|<?= $itd['locnumber'] ?>|<?= $itd['itemnumber'] ?>"
                                                class="btn btn-info btn-sm"
                                                title="View <?= htmlspecialchars($itd['desc']) ?>">
                                                <i class="fad fa-eye"></i>
                                            </a>
                                        </td>
                                        <td>
                                            <button id="A<?= $itd['itemnumber'] ?>" class="btn btn-success btn-sm"
                                                onclick="addConfirm('<?= $itd['itemnumber'] ?>','A<?= $itd['itemnumber'] ?>')"
                                                title="Add <?= htmlspecialchars($itd['desc']) ?>">
                                                <i class="fad fa-plus-circle"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Current items table -->
                        <h5 class="mt-4 d-flex align-items-center gap-3 flex-wrap">
                            <small>Current items covered by this Written Scheme</small>
                            <div class="input-group input-group-sm ws-parts-search-group" style="width:260px; max-width:100%;">
                                <span class="input-group-text"><i class="fad fa-search"></i></span>
                                <input type="search" class="form-control ws-parts-search" id="wsPartsCurrentSearch" data-ws-filter-target="active" placeholder="Search current items" aria-label="Search current items">
                            </div>
                        </h5>
                        <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']) ?></td>
                                        <td><?= htmlspecialchars($itd['serialnumber']) ?></td>
                                        <td><?= htmlspecialchars($itd['plantnumber']) ?></td>
                                        <td>
                                            <a href="index.php?t=includes/master&p=asset.php&view=edit_attached&data=<?= $itd['clientnumber'] ?>|<?= $itd['locnumber'] ?>|<?= $itd['itemnumber'] ?>"
                                                class="btn btn-info btn-sm"
                                                title="View <?= htmlspecialchars($itd['desc']) ?>">
                                                <i class="fad fa-eye"></i>
                                            </a>
                                        </td>
                                        <td>
                                            <button id="R<?= $itd['itemnumber'] ?>" class="btn btn-danger btn-sm"
                                                onclick="delConfirm('<?= $itd['itemnumber'] ?>','R<?= $itd['itemnumber'] ?>')"
                                                title="Remove <?= htmlspecialchars($itd['desc']) ?>">
                                                <i class="fad fa-minus-circle"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </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-success btn-sm" onclick="toggleVisibility('newItem')"> <i
                                class="fad fa-plus"></i> Add Revision</button>
                    </div>
                    <div class="card-body">
                        <!-- New item form -->
                        <div id="newItem" class="row mb-3" style="display: none;">
                            <div class="col-12 col-md-4">
                                <div class="mb-2 date-picker" data-date-type="open" data-mdb-toggle-button="false">
                                    <input class="form-control" data-mdb-confirmDateOnSelect
                                        data-mdb-toggle="datepicker" type="text" name="nDate" id="nDate" value=""
                                        placeholder="Date" />
                                </div>
                                <div>
                                    <?php
                                    if ($_SESSION['usertype'] == 'surveyor') {
                                        $surv = $_SESSION['userid'];
                                    } else {
                                        $surv = '';
                                    }
                                    echo listSurveyor($surv, 'nSurveyor', 'select');
                                    ?>
                                </div>
                            </div>
                            <div class="col-12 col-md-8 mt-2">
                                <textarea id="nDesc" class="form-control" name="nDesc" rows="5"
                                    placeholder="Enter description"></textarea>
                            </div>
                            <div class="col-12 mt-2">
                                <button class="btn btn-success btn-sm text-light" onclick="addRevision()">
                                    <i class="fad fa-plus"></i> Register Entry
                                </button>
                            </div>
                        </div>

                        <!-- Revisions table -->
                        <table id="revTable" class="table table-striped table-sm">
                            <thead>
                                <tr>
                                    <th>Date of revision</th>
                                    <th>Record of any modification made to the pressure system or part</th>
                                    <th>Surveyor</th>
                                    <th>Action</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 id="delContainer" class="card">
                    <div class="card-header">Delivery</div>
                    <div class="card-body d-flex flex-column align-items-center justify-content-center">
                        <div id="delConf" class="text-center">
                            <?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();
                            $isOne = mysqli_num_rows($wsi);
                            $items = "";
                            $delitems = "";

                            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/" . $itd['clientnumber'] . "/" . $itdata['repnumber'] . "_" . $idata['itemnumber'] . ".pdf,";
                            }
                            ?>

                            <?php if ($isOne == 1) { ?>
                            <button class="btn btn-secondary me-2" onclick="genEWS('single')">
                                <i class="fad fa-file-pdf"></i> Generate Single
                            </button>
                            <button class="btn btn-secondary" onclick="genEWS('full')">
                                <i class="fad fa-file-pdf"></i> Generate Full
                            </button>
                            <?php } else { ?>
                            <button class="btn btn-secondary" onclick="genWS('full')">Generate Documents</button>
                            <?php } ?>

                            <div class="col-12 mt-4">
                                <div class="form-check">
                                    <input type="checkbox" class="form-check-input" id="attachReps" checked>
                                    <label class="form-check-label" for="attachReps">Attach Reports</label>
                                </div>
                            </div>
                        </div>

                        <div id="loadingBlock" class="col-md-12 text-center" style="display:none">
                            <h1>
                                <i class="fad fa-ring fa-spin fa-3x fa-fw"
                                    style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>
                                Generating Documents<br><small>Please wait</small>

                            </h1>
                        </div>

                        <div id="deliveryMode" class="text-center" style="display:none"></div>

                        <div id="delMail" class="text-center" 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';
                            ?>
                            <div id="optionBox" class="col-12 text-center">
                                <button class="btn btn-secondary toggleMode me-3" data-mode="mail">Send to
                                    client</button>
                                <button class="btn btn-secondary toggleMode" data-mode="deliveryMode">Reset
                                    delivery</button>
                            </div>

                            <div id="mailBox" style="display:none">
                                <?php include('../master/mailer.php'); ?>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>


<script>
var modalElement = document.getElementById('myTabContent');

function filterWSPartTable(input) {
  const tableId = input.getAttribute('data-ws-filter-target');
  const table = tableId ? document.getElementById(tableId) : null;
  if (!table) return;

  const query = input.value.trim().toLowerCase();
  table.querySelectorAll('tbody tr').forEach(row => {
    if (row.dataset.wsPartMoved === '1') {
      row.style.display = 'none';
      return;
    }
    const text = Array.from(row.children).slice(0, 3).map(cell => cell.textContent.toLowerCase()).join(' ');
    row.style.display = text.indexOf(query) === -1 ? 'none' : '';
  });
}

function filterWSPartTables() {
  document.querySelectorAll('.ws-parts-search').forEach(filterWSPartTable);
}

document.querySelectorAll('.ws-parts-search').forEach(input => {
  if (input.__wsPartsSearchBound) return;
  input.__wsPartsSearchBound = true;
  input.addEventListener('input', () => filterWSPartTable(input));
});

var datepickerElements = modalElement.querySelectorAll(".date-picker");
datepickerElements.forEach((datepickerEl) => {
    const options = {
        confirmDateOnSelect: true,
        format: "dd-mm-yyyy",
    };

    new mdb.Datepicker(datepickerEl, options);
});
// ---- 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', '<?= $_REQUEST['tenant']?>');

  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 editWsRevisionNumber() {
  const current = document.getElementById('wsRevNumber') ? document.getElementById('wsRevNumber').textContent.trim() : '0';
  const dest = `
    <p class="mb-3">Change the current revision number for this Written Scheme. This updates the scheme header number only; it does not add or remove entries from the revision history table.</p>
    <div class="mb-2">
      <label class="form-label" for="wsRevInput">Revision number</label>
      <input type="number" min="0" step="1" class="form-control" id="wsRevInput" value="${current}">
    </div>
  `;
  loadModalContent(dest, "confirmBox", "modal-md", 1060, "true", "Change Revision Number", "cancelConfirm", () => saveWsRevisionNumber());
}

function saveWsRevisionNumber() {
  const input = document.getElementById('wsRevInput');
  const revision = input ? parseInt(input.value, 10) : NaN;
  if (!Number.isInteger(revision) || revision < 0) {
    showResponse('warning', 'Please enter a valid revision number');
    return;
  }

  fetch(ROOT_URL + '/includes/master/ws_functions.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      mode: 'saveRev',
      id: '<?= $n['id']?>',
      rev: String(revision),
      tenant: TENANT_URL
    })
  }).then(r=>r.text()).then(ret=>{
    const dta = ret.split('|');
    if (dta[0] !== 'success') {
      showResponse('danger', ret);
      return;
    }
    document.getElementById('wsRevNumber').textContent = dta[1];
    killModal('confirmBox');
    showResponse('success', 'The revision number has been updated');
  });
}

function reviewConfirm() {

    var dest ="<p>You are adding a blank confirmation of review without alteration</p>";
    loadModalContent(dest, "confirmBox", "modal-lg", 1060, "true", "Add Review", "cancelConfirm", () => 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() {
    var dest ="<p>Are you sure you wish to add this exclusion to the Written Scheme?</p>";
    loadModalContent(dest, "confirmBox", "modal-lg", 1060, "true", "Add Exclusion", "cancelConfirm", () => 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) {
    var dest ="<p>re you sure you wish to remove this exclusion from the Written Scheme?</p>";
    loadModalContent(dest, "confirmBox", "modal-lg", 1060, "true", "Remove Exclusion", "cancelConfirm", () => 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) {
        var dest ="<p>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></p>";
    loadModalContent(dest, "confirmBox", "modal-lg", 1060, "true", "Add Item", "cancelConfirm", () => 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, revisionLock: (typeof wsRevisionLockValue === 'function' ? wsRevisionLockValue() : '0'), tenant:TENANT_URL })
  }).then(r=>r.text()).then(ret=>{
    const dta = ret.split('|');
    if (dta[0] !== 'success') {
      showResponse('danger', ret);
      return;
    }
    showResponse('success', 'The item has been successfully added to the WS');
    killModal('confirmBox');
    if (dta[1]) document.querySelector('#revTable tbody').innerHTML = dta[1];
    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;
    const cell4 = tr1.children[3].innerHTML;
    let cell5 = tr1.children[4].innerHTML;
    cell5 = cell5.replace('addConfirm', 'delConfirm')
                 .split(`A${i}`).join(`R${i}`)
                 .replace('fa-plus-circle', 'fa-minus-circle')
                 .replace('btn-outline-success', 'btn-outline-danger')
                 .replace('btn-success', 'btn-danger');
    document.querySelector('#active tbody').insertAdjacentHTML('beforeend', `<tr><td>${cell1}</td><td>${cell2}</td><td>${cell3}</td><td>${cell4}</td><td>${cell5}</td></tr>`);
    tr1.dataset.wsPartMoved = '1';
    tr1.style.display = 'none';
    filterWSPartTables();
    document.getElementById('prompt').style.display = 'block';
  });
}

function delConfirm(i, l) {
              var dest ="<p>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></p>";
    loadModalContent(dest, "confirmBox", "modal-lg", 1060, "true", "Remove Item", "cancelConfirm", () => 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, revisionLock: (typeof wsRevisionLockValue === 'function' ? wsRevisionLockValue() : '0'), tenant:TENANT_URL })
  }).then(r=>r.text()).then(ret=>{
    const dta = ret.split('|');
    if (dta[0] !== 'success') {
      showResponse('danger', ret);
      return;
    }
    showResponse('success', 'The item has been successfully removed from the WS');
    killModal('confirmBox');
    if (dta[1]) document.querySelector('#revTable tbody').innerHTML = dta[1];
    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;
    const cell4 = tr2.children[3].innerHTML;
    let cell5 = tr2.children[4].innerHTML;
    cell5 = cell5.replace('delConfirm', 'addConfirm')
                 .split(`R${i}`).join(`A${i}`)
                 .replace('fa-minus-circle', 'fa-plus-circle')
                 .replace('btn-outline-danger', 'btn-outline-success')
                 .replace('btn-danger', 'btn-success');
    document.querySelector('#inactive tbody').insertAdjacentHTML('beforeend', `<tr><td>${cell1}</td><td>${cell2}</td><td>${cell3}</td><td>${cell4}</td><td>${cell5}</td></tr>`);
    tr2.dataset.wsPartMoved = '1';
    tr2.style.display = 'none';
    filterWSPartTables();
    document.getElementById('prompt').style.display = 'block';
  });
}

function remrevConfirm(i) {
            var dest ="<p>Are you sure you wish to remove this revision entry from the Written Scheme?<br><small>This cannot be undone</small></p>";
    loadModalContent(dest, "confirmBox", "modal-lg", 1060, "true", "Remove revision entry", "cancelConfirm", () => 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('Rr' + i);
    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');
    });
  });
})();

$('.toggleMode').on('click', function() {
    var target = $(this).data('mode');


    if (target === "mail") {
        $('#mailBox').css('display', 'block');
        $('#optionBox').css('display', 'none');
        $('#delConf').css('display', 'none');
    }

    if (target === "deliveryMode") {
        $('#mailBox').css('display', 'none');
        $('#delConf').css('display', 'block');
        $('#optionBox').css('display', 'none');
    }
})
</script>
