<div class="row ">
    <div class="note note-secondary">
        Select your supplier, specify a client and then select a location and all assets therein will be assigned.
    </div>
</div>

<div class="row">
    <div class="col-12 col-md-4 mb-4">
        <a href="javascript:void(0)" class="card hoverable">
            <div class="card-body">
                <div class="media">
                    <span class="card-img-100 d-inline-flex justify-content-center align-items-center rounded-circle grey lighten-3 me-4">
                        <i class="fad fa-user-vneck fa-2x green-text"></i>
                    </span>
                    <div class="media-body">
                        <h5 class="dark-grey-text mb-3">SELECT SURVEYOR</h5>
                        <p class="font-weight-light text-muted mb-0">
                            <select id="surveyorSelector" data-mdb-select-init class="form-control form-control-sm" data-placeholder="Select Surveyor" onchange="getAssigned()">
                                <option value="NULL">Select Surveyor</option>
                                <?php $stmt = $GLOBALS['con']->prepare("SELECT `id`,`surname`,`forename` FROM `surveyor`  WHERE `statuslive`='1'")or die(mysqli_error($GLOBALS['con']));
                                    $stmt->execute();$rc=$stmt->get_result();$stmt->close();	
                                    while($cd=mysqli_fetch_array($rc)){	
                                        $stmt = $GLOBALS['con']->prepare("SELECT DISTINCT `client_id` FROM `surveyor_assignments` WHERE `surveyor`=? ")or die(mysqli_error($GLOBALS['con']));
                                        $stmt->bind_param('i',$cd['id']);$stmt->execute();$ic=$stmt->get_result();$stmt->close();
                                        $count=mysqli_num_rows($ic);
                                        if(isset($_REQUEST['id']) && $cd['id']==$_REQUEST['id']){$sel="selected";}
                                        else{$sel='';}
                                        $retb.='<option value="'.$cd['id'].'" '.$sel.'>'.$cd['forename']." ".$cd['surname'].' ('.$count.')</option>';//.PHP_EOL;
                                    }
                                    echo ($retb.$error);
                                    ?>
                            </select>
                        </p>
                    </div>
                </div>
            </div>
        </a>
    </div>

    <div class="col-12 col-md-4 mb-4">
        <a href="javascript:void(0)" class="card hoverable">
            <div class="card-body">
                <div class="media">
                    <span class="card-img-100 d-inline-flex justify-content-center align-items-center rounded-circle grey lighten-3 me-4">
                        <i class="fad fa-calendar-alt fa-2x text-info"></i>
                    </span>
                    <div class="media-body">
                        <h5 class="dark-grey-text mb-3">SELECT CLIENT</h5>
                        <p class="font-weight-light text-muted mb-0">
                        <div id="cF">

                        </div>
                        </p>
                    </div>
                </div>
            </div>
        </a>
    </div>


    <div class="col-12 col-md-4 mb-4">
        <a href="javascript:void(0)" class="card hoverable">
            <div class="card-body">
                <div class="media">
                    <span class="card-img-100 d-inline-flex justify-content-center align-items-center rounded-circle grey lighten-3 me-4">
                        <i class="fad fa-building fa-2x purple-text"></i>
                    </span>
                    <div class="media-body">
                        <h5 class="dark-grey-text mb-3">SELECT LOCATION</h5>
                        <p class="font-weight-light text-muted mb-0">
                        <div id="sF">

                        </div>
                        </p>
                    </div>
                </div>
            </div>
        </a>
    </div>

</div>
<div class="row">
    <div id="assetList" class="col-12"></div>
</div>


<div class="row">

    <div id="assigend" class="col-12 d-flex p-3 align-items-start flex-wrap"></div>
</div>
<script>
<?php if (isset($_REQUEST['id'])) { ?>
// Wait for the DOM to be fully loaded
document.addEventListener('DOMContentLoaded', function() {
    // Check if MDB select element is initialized
    var surveyorSelector = document.getElementById('surveyorSelector');

    if (surveyorSelector) {
        // Get the value of the selected surveyor (id from the database)
        var surveyor = surveyorSelector.value;

        // Programmatically set the selected option and trigger change event
        surveyorSelector.value = surveyor;
        var changeEvent = new Event('change', {
            bubbles: true
        });
        surveyorSelector.dispatchEvent(changeEvent);


    }
});
<?php } ?>


function getClientList() {
    var surveyor = document.getElementById('surveyorSelector').value;
    document.getElementById('sF').innerHTML = '';
    var xhr = new XMLHttpRequest();
    xhr.open('POST', ROOT_URL + '/includes/surveyor/surveyor_functions.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        if (xhr.status === 200) {
            document.getElementById('cF').innerHTML = xhr.responseText;
            var mySelect = new mdb.Select(document.getElementById('clientSelector'), {
                filter: true
            });


        }
    };
    xhr.send('FUNCTION=clientAssigned&tenant=' + TENANT_URL + '&surveyor=' + encodeURIComponent(surveyor));
}

function getLocationList() {
    var client = document.getElementById('clientSelector').value;
    var surveyor = document.getElementById('surveyorSelector').value;
    var location = document.getElementById('locationSelector').value;

    // Build the GET parameters as a query string
    var params = 'tenant=' + encodeURIComponent(TENANT_URL) +
        '&clientnumber=' + encodeURIComponent(client) +
        '&surveyor=' + encodeURIComponent(surveyor) +
        '&locnumber=' + encodeURIComponent(location);

    // Use the master function to load the content and execute any scripts
    loadContentAndExecuteScripts(ROOT_URL + '/includes/surveyor/surveyor_assetSelect.php', 'assetList', params);
}


function getList() {

    var client = document.getElementById('clientSelector').value;

    var params = 'FUNCTION=getList&tenant=' + encodeURIComponent(TENANT_URL) + '&mode=list&comp=' + encodeURIComponent(client);

    loadContentAndExecuteScripts(ROOT_URL + '/includes/surveyor/surveyor_functions.php', 'sF', params, function() {
        document.getElementById('assetList').innerHTML = '';
        var locationSelector = document.getElementById('locationSelector');
        if (locationSelector) {
            var mySelect = new mdb.Select(locationSelector, {
                filter: true
            });
        }
    });
}

function getAssigned() {

    var surveyor = document.getElementById('surveyorSelector').value;
    var name = document.getElementById('surveyorSelector').options[document.getElementById('surveyorSelector').selectedIndex].text;
    var client = document.getElementById('clientSelector') ? document.getElementById('clientSelector').value : null;

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

    xhr.onload = function() {
        //debug(xhr.responseText);
        if (xhr.status === 200) {
            document.getElementById('assigend').innerHTML = xhr.responseText;

            if (!client) {
                getClientList();
            }
        } else {
            //debug('Error: ' + xhr.status + ' - ' + xhr.statusText);
        }
    };

    xhr.onerror = function() {
        //debug('Network Error: Could not complete the request.');
    };

    // Send the request
    xhr.send('FUNCTION=surverorAssigned&tenant=' + TENANT_URL + '&surveyor=' + encodeURIComponent(surveyor) + '&name=' + encodeURIComponent(name));
}


function assignSite() {

    var surveyor = document.getElementById('surveyorSelector').value;
    var clientnumber = document.getElementById('clientSelector').value;
    var locnumber = document.getElementById('locationSelector').value;

    var xhr = new XMLHttpRequest();
    xhr.open('POST', ROOT_URL + '/includes/surveyor/surveyor_functions.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        if (xhr.status === 200) {

            getAssigned();
            document.getElementById('assetList').innerHTML = '';

            document.getElementById('locationSelector').value = '';
            getClientList();

        }
    };
    xhr.send('FUNCTION=setSiteSurveyor&surveyor=' + encodeURIComponent(surveyor) + '&tenant=' + TENANT_URL + '&clientnumber=' + encodeURIComponent(clientnumber) + '&locnumber=' + encodeURIComponent(locnumber));
}

function assignItems() {
    var i = document.getElementById('selectedItems').innerText;
    var surveyor = document.getElementById('surveyorSelector').value;
    var clientnumber = document.getElementById('clientSelector').value;
    var locnumber = document.getElementById('locationSelector').value;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', ROOT_URL + '/includes/surveyor/assignItems.php?clientnumber=' + encodeURIComponent(clientnumber) + '&tenant=' + TENANT_URL + '&surveyor=' + encodeURIComponent(surveyor) + '&locnumber=' + encodeURIComponent(locnumber) +
        '&items=' +
        encodeURIComponent(i),
        true);
    xhr.onload = function() {
        if (xhr.status === 200) {
            var dest = xhr.responseText;
            loadModalContent(dest, "assetBox", "modal-xl", 1060, "true", 'Surveyor Assign');
        }
    };
    xhr.send();
}

function resetMDBSelect(id) {
    alert(id)
    var selectElement = document.getElementById(id);

    // Reset the value of the select element back to the default unselected option
    selectElement.selectedIndex = 0;

    // Manually trigger change event to ensure MDB components update
    var event = new Event('change', {
        bubbles: true
    });
    selectElement.dispatchEvent(event);
}

function revoke(clientnumber) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', ROOT_URL + '/includes/surveyor/surveyor_functions.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        if (xhr.status === 200) {
            getAssigned();
        }
    };
    xhr.send('FUNCTION=revokeSurveyor&tenant=' + TENANT_URL + '&clientnumber=' + encodeURIComponent(clientnumber));
}

function revokeSite(entry, name) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', ROOT_URL + '/includes/surveyor/surveyor_functions.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        if (xhr.status === 200) {
            getAssigned();
        }
    };
    xhr.send('FUNCTION=revokeSurveyorSite&tenant=' + TENANT_URL + '&assignment=' + encodeURIComponent(entry));
}

function suspendSite(entry, name) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', ROOT_URL + '/includes/surveyor/surveyor_functions.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        if (xhr.status === 200) {
            getAssigned();
            showResponse("success", "Access to " + name + " has been suspended");
        }
    };
    xhr.send('FUNCTION=suspendSite&tenant=' + TENANT_URL + '&assignment=' + encodeURIComponent(entry));
}

function activateSite(entry) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', ROOT_URL + '/includes/surveyor/surveyor_functions.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        if (xhr.status === 200) {
            getAssigned();
            showResponse("success", "Access to " + name + " has been resumed");
        }
    };
    xhr.send('FUNCTION=activateSite&tenant=' + TENANT_URL + '&assignment=' + encodeURIComponent(entry));
}


document.getElementById('navBox').innerHTML = '<li class="breadcrumb-item active">Surveyors: Quick Assign</li>';
</script>