<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="myTab" role="tablist">
            <li class="nav-item" role="presentation">
                <a class="nav-link active" id="details-tab" data-mdb-toggle="tab" href="#details-content" role="tab"
                   aria-controls="details-content" aria-selected="true" data-mdb-tooltip="Written Scheme Details">
                    <i class="fad fa-file-alt"></i> Details
                </a>
            </li>
            <li class="nav-item" role="presentation">
                <a class="nav-link" id="parts-tab" data-mdb-toggle="tab" href="#parts-content" role="tab"
                   aria-controls="parts-content" aria-selected="false" data-mdb-tooltip="Parts Of the system">
                    <i class="fad fa-cogs"></i> Parts
                </a>
            </li>
            <li class="nav-item" role="presentation">
                <a class="nav-link" id="revisions-tab" data-mdb-toggle="tab" href="#revisions-content" role="tab"
                   aria-controls="revisions-content" aria-selected="false" data-mdb-tooltip="Revisions to the system">
                    <i class="fad fa-sync-alt"></i> Revisions
                </a>
            </li>
            <li class="nav-item" role="presentation">
                <a 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" href="#delivery-content" role="tab"
                   aria-controls="delivery-content" aria-selected="false" data-mdb-tooltip="Deliver documents">
                    <i class="fad fa-truck"></i> Delivery
                </a>
            </li>
            <li><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="<?=TENANT_URL?>/output/wsfiles/<?= $n['clientnumber'] ?>/WS<?= $_REQUEST['ws'] ?>_ws.zip?<?= rand() ?>" target="_blank"
                       data-mdb-tooltip="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="<?=TENANT_URL?>/output/wsfiles/WS<?= $_REQUEST['ws'] ?>_full.zip?<?= rand() ?>" target="_blank"
                       data-mdb-tooltip="View stored WS documentation"><i class="fad fa-file-pdf"></i> Full Pack</a>
                    <?php } ?>
                </span>
            </li>
        </ul>

        <!-- Tab content -->
        <div class="tab-content" id="myTabContent">
            <!-- Original File -->
            <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">
                                <!-- WS number input field with save button -->
                                <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>

                                <!-- Surveyor selection -->
                                <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">
                                <!-- File upload section -->
                                <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>

                                <!-- Existing file section -->
                                <?php if(file_exists('../../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="<?=TENANT_URL?>/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="<?=TENANT_URL?>/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-toggle="tooltip" data-mdb-placement="left" 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-toggle="tooltip" data-mdb-placement="left" 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-toggle="tooltip" data-mdb-placement="left" 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-toggle="tooltip" data-mdb-placement="left" 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">
                        <!-- New Item Form -->
                        <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>

                        <!-- Revisions Table -->
                        <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
                            // Prepare SQL query to fetch items and corresponding report numbers
                            $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,";
                            }
                            ?>

                            <!-- Delivery buttons -->
                            <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>
document.addEventListener('DOMContentLoaded', function() {

    // Save button click event
    document.getElementById('but_save').addEventListener('click', function() {
        const w = document.getElementById('scheme_number_alt').value;
        fetch('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
                })
            })
            .then(response => response.text())
            .then(() => {
                document.getElementById('scheme_number_alt').classList.add('is-valid');
            });
    });

    // Surveyor change event
    document.getElementById('surveyor').addEventListener('change', function() {
        const w = document.getElementById('surveyor').value;
        fetch('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
                })
            })
            .then(response => response.text())
            .then(() => {
                document.getElementById('surveyor').classList.add('is-valid');
            });
    });

    // Upload button click event
    document.getElementById('but_upload').addEventListener('click', function() {
        const fd = new FormData();
        const files = document.getElementById('file').files[0];
        fd.append('file', files);
        fd.append('clientnumber', '<?= $cd['clientnumber']?>');
        fd.append('wsno', '<?= $_REQUEST['ws']?>');

        fetch(ROOT_URL + 'functions/wsupload.php', {
                method: 'POST',
                body: fd
            })
            .then(response => response.text())
            .then(response => {
                if (response.trim() === 's') {
                    document.getElementById('attach').innerHTML = `
        <div class="col-2 lead">Existing File:</div>
        <div class="col-9">
          <a class="btn btn-secondary btn-block" href="output/wsfiles/<?= $cd['clientnumber']?>/<?= $_REQUEST['ws']?>_ws.pdf" target="_blank">
            <i class="fad fa-file-pdf"></i> Download
          </a>
        </div>
        <div class="col-1">
          <a class="btn btn-danger btn-block" href="output/wsfiles/<?= $cd['clientnumber']?>/<?= $_REQUEST['ws']?>_ws.pdf" target="_blank">
            <i class="fad fa-trash"></i>
          </a>
        </div>
      `;
                    document.getElementById('file').value = '';
                    document.querySelector('.file-path').value = '';
                    document.getElementById('btnDel').removeAttribute('disabled');
                } else {
                    parent.showResponse('danger', 'File not uploaded');
                }
            });
    });
});

// Function to add revision
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
            })
        })
        .then(response => response.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');
            } else {
                // Debug ret if necessary
            }
        });
}

// Function to autofill data
function autofill(f, s, t) {
    $('#popupBox').modal('show');
    $('#popupBox .modal-body').load('includes/master/form_options.php?form=' + f + '&source=' + s + '&type=' + t);
}

// Function to open new item form
function newItem() {
    document.getElementById('newItem').style.display = 'block';
    document.getElementById('newButton').setAttribute('onclick', 'closeNew()');
}

// Function to close new item form
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 to clone exclusion
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;
}

// Function to generate EWS
function genEWS(i) {
    document.getElementById('delConf').style.display = 'none';
    document.getElementById('loadingBlock').style.display = 'block';

    fetch(ROOT_URL + '/functions/genEWsPDF.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                clientnumber: '<?= $n['clientnumber']?>',
                wsnumber: '<?= $_REQUEST['ws']?>'
            })
        })
        .then(response => response.text())
        .then(result => {
            fetch(ROOT_URL + '/functions/genECover.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams({
                        items: '<?= $items?>',
                        wsnumber: '<?= $_REQUEST['ws']?>',
                        clientnumber: '<?= $n['clientnumber']?>'
                    })
                })
                .then(() => {
                    fetch(ROOT_URL + '/functions/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(response => response.text())
                        .then(result => {
                            document.getElementById('attachment_1').value = result;
                            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?<?= rand()?>" target="_blank" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" 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?<?= rand()?>" target="_blank" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="View stored WS documentation">
            <i class="fad fa-file-pdf"></i> Full Pack
          </a>
        `;
                            }
                        });

                    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']?>'
                            })
                        });
                    }
                });
        });
}

// Function to confirm review
function reviewConfirm() {
    confirmBox("Add Item", "You are adding a blank confirmation of review without alteration", "addReview()");
}

// Function to add review
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(response => response.text())
        .then(() => {
            showResponse('success', 'The review has been successfully added to the WS');
            $('#confirmBox').modal('hide');
            document.getElementById('prompt').style.display = 'block';
        });
}

// Function to confirm exclusion addition
function addEConfirm() {
    confirmBox("Add Item", "Are you sure you wish to add this exclusion to the Written Scheme?", "addEPart()");
}

// Function to add exclusion
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
            })
        })
        .then(response => response.text())
        .then(() => {
            showResponse('success', 'The exclusion has been successfully added to the WS');
            $('#confirmBox').modal('hide');
            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-toggle="tooltip" data-placement="left" title="Clone Exclusion">
          <i class="far fa-clone"></i>
        </a>
      </td>
    </tr>
  `;
            document.querySelector('#exList tbody').insertAdjacentHTML('beforeend', newRow);
        });
}

// Function to confirm exclusion removal
function delEConfirm(i, l) {
    confirmBox("Remove Exclusion", "Are you sure you wish to remove this exclusion from the Written Scheme?", `delEPart('${i}', '${l}')`);
}

// Function to remove exclusion
function delEPart(i, l) {
    $('#confirmBox').modal('hide');
    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']?>'
            })
        })
        .then(response => response.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 to confirm part addition
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 to add part
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
            })
        })
        .then(response => response.text())
        .then(() => {
            showResponse('success', 'The item has been successfully added to the WS');
            $('#confirmBox').modal('hide');
            const tr1 = document.getElementById(l).closest("tr");
            const row = tr1.innerHTML;
            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');
            cell4 = cell4.replace('fa-plus-circle', 'fa-minus-circle');
            cell4 = cell4.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 to confirm part removal
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 to remove part
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
            })
        })
        .then(response => response.text())
        .then(() => {
            showResponse('success', 'The item has been successfully removed from the WS');
            $('#confirmBox').modal('hide');
            const tr2 = document.getElementById(l).closest("tr");
            const row = tr2.innerHTML;
            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');
            cell4 = cell4.replace('fa-minus-circle', 'fa-plus-circle');
            cell4 = cell4.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 to confirm revision removal
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 to remove revision
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
            })
        })
        .then(response => response.text())
        .then(() => {
            showResponse('success', 'The entry has been successfully removed from the WS');
            $('#confirmBox').modal('hide');
            const tr2 = document.getElementById(i).closest("tr");
            tr2.style.display = 'none';
        });
}

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