<?php
$r=mysqli_query($GLOBALS['con'],"SELECT * FROM `surveyor` WHERE `id`='".$_REQUEST['id']."'")or die(mysqli_error($GLOBALS['con']));
$cd=mysqli_fetch_array($r);


    $email_values = [
        0 => '0', //client
        1 => $cd['forename'].' '.$cd['surname'], //type
        2 => $cd['email'], //recipient
        3 => '', //subject
        4 => '', //message
        5 => '', //attachment
        6 => '' //source
    ];
    $email64_values = base64_encode(json_encode($email_values));
?>
<style>
.pwstrength_viewport_progress .progress {
    height: 15px !important
}
</style>


<div class="row mb-4">
    <div class="col-12 col-md-3 order-md-2 order-1">
        <div class="float-end">
            <?php if($cd['phone1']!=""){?>
            <a data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" data-mdb-trigger="hover" title="Phone <?= $cd['forename']?> <?= $cd['surname']?>" id="phone" href="tel:<?= $cd['phone1']?>"
               class="btn btn-secondary noprint"><i class="fad fa-phone"></i></a>
            <?php }?>


            <?php if(!filter_var($cd['email'], FILTER_VALIDATE_EMAIL) === false) {?>
            <a data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" data-mdb-trigger="hover" title="Email <?= $cd['forename']?> <?= $cd['surname']?>" href="javascript:void(0)"
               class="btn btn-secondary emailButton"
               data-values="<?= $email64_values?>" data-href="<?=ROOT_URL?>/includes/master/mailer.php"><i class="fad fa-envelope"></i></a>
            <?php }
                if($cd['statuslive']==1){?>
            <a data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" data-mdb-trigger="hover" title="Archive Surveyor" href="javascript:void(0)"
               onClick="archiveSurveyor('surveyor','id','<?= $cd['id']?>','surveyor_functions.php','archiveSupplier')"
               class="btn btn-secondary"><i class="fad fa-archive"></i></a>
            <?php } else {?>
            <a data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" data-mdb-trigger="hover" title="Reinstate Surveyor" href="javascript:void(0)"
               onClick="reinstateSurveyor('surveyor','id','<?= $cd['id']?>','surveyor_functions.php','reinstateSupplier')"
               class="btn btn-secondary"><i class="fad fa-upload"></i></a>
            <?php }?>
        </div>
    </div>

    <div class="col-12 col-md-9 order-md-1 order-2">

        <div class="row mb-3">
            <div class="note note-secondary">
                Surveyor settings <small class="muted">Manage access permissions, assignments and profile details of your surveyors. All changes to permissions are immediate, however any changes would not reflect on any previously
                    created inspection certificates. </small>
            </div>
        </div>
    </div>
</div>
<div id="text" class="mb-3"></div>

<form id="surveyorForm" class="form-horizontal">
    <div class="row">
        <?php require_once(ROOT_URL.'/forms/elements/surveyor_details.frm');?>
    </div>

    <div class="row">
        <div class="col-12 col-md-4 mb-5">
            <div class="card">
                <div class="card-header">Access</div>
                <?php $stmt2 = $GLOBALS['con']->prepare("SELECT AES_DECRYPT(password,email) AS pass, email FROM `surveyor` WHERE `id`=?")or die(mysqli_error($GLOBALS['con']));
                    $stmt2->bind_param('i',$_REQUEST['id']);$stmt2->execute();$p=$stmt2->get_result();$stmt2->close();
                    $data=mysqli_fetch_array($p);
                    $cd['password']=$data['pass'];
                    if($data['pass']=="" && $data['email']!="" ){?>
                <script>
                $(document).ready(function() {
                    $('#text').html(
                        '<div class="alert warning-color-dark text-center text-light p-0"><p style="margin-top:10px">There has been no access password set<br><i>This user will not be able to access the system</i></p></div>'
                    )
                    on()
                })
                </script>
                <?php }
                     $email_values = [
                        0 => '0', // client
                        1 => $cd['forename'].' '.$cd['surname'], // name
                        2 => $cd['email'], // recipient
                        3 => getCompanyDetails('name').' login Details', // subject
                        4 => 'Your login details for access to EnRep are as follows:
                    URL: <a href="'.getCompanyDetails('web').'">'.getCompanyDetails('web').'</a>
                    Username: '.$cd['email'].'
                    Password: '.$data['pass'], // message
                        5 => '', // attachment
                        6 => '' // source
                    ];?>


                <div class="card-body text-center">
                    <div class="row mb-3">
                        <div class="col-12 col-md-3">
                            <label class="form-label" for="password">Password</label>
                        </div>
                        <div id="pcont" class="col-12 col-md-10">
                            <div class="input-group">
                                <input class="form-control form-control-sm" type="text" name="password" id="password" value="<?= $data['pass'] ?>" autocomplete="new-password" required />
                                <button class="btn btn-info btn-sm m-0 px-3 py-2 emailButton"
                                        data-values="<?= $email64_values ?>"
                                        data-href="<?= ROOT_URL ?>/includes/master/mailer.php"
                                        data-mdb-tooltip-init
                                        title="Email surveyor login details"
                                        data-mdb-placement="bottom"
                                        data-mdb-trigger="hover">
                                    <i class="fad fa-envelope"></i>
                                </button>
                            </div>
                            <div class="row mb-3">
                                <div class="col-12" style="padding-top: 30px;">
                                    <div class="pwstrength_viewport_progress" style="height:10px"></div>
                                </div>
                            </div>
                        </div>
                    </div>


                    <!-- Messages section -->
                    <div class="row">
                        <div class="col-12" id="messages"></div>
                    </div>
                </div>


            </div>
        </div>


        <div class="col-12 col-md-4 text-center mb-5">
            <div class="card">
                <div class="card-header">Status</div>
                <div class="card-body row">
                    <!-- Live Surveyor Status -->
                    <div class="form-group col-6">
                        <?php $checked = ($cd['statuslive'] == "1") ? "checked" : ""; ?>
                        <label class="form-label" for="statuslive">Live Surveyor</label>
                        <div id="statusliveBox" class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" <?= $checked ?> name="statuslive" id="statuslive">
                            <label class="form-check-label" for="statuslive"></label>
                        </div>
                    </div>

                    <!-- Delivery Authorisation (only for non-contractor users) -->
                    <?php if($_SESSION['usertype'] != "contractor"): ?>
                    <div class="form-group col-6">
                        <?php $checked = ($cd['delAuth'] == "1") ? "checked" : ""; ?>
                        <label class="form-label" for="delAuth">Delivery Authorisation</label>
                        <div id="deliverylive" class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" <?= $checked ?> name="delAuth" id="delAuth">
                            <label class="form-check-label" for="delAuth"></label>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <?php if($_SESSION['usertype']=="contractor"){}
        else{?>
        <div class="col-12 col-md-4 text-center mb-5">
            <div class="card">
                <div class="card-header">Security level</div>
                <div class="card-body">

                    <div id="surveyorL" class="row">
                        <div class="col-3 text-center"><a id="a0" href="javascript:void(0)" class="secButton btn <?php if($cd['access']==0){echo "btn-success";}else{echo "btn-danger";}?>"
                               onClick="changeSec('<?= $_REQUEST['id']?>','0')">0</a><br>Suspend</div>

                        <div class="col-3 text-center"><a id="a1" href="javascript:void(0)" class="secButton btn <?php if($cd['access']==1){echo "btn-success";}else{echo "btn-secondary";}?>"
                               onClick="changeSec('<?= $_REQUEST['id']?>','1')">1</a><br>Full</div>

                        <div class="col-3 text-center"><a id="a2" href="javascript:void(0)" class="secButton btn <?php if($cd['access']==2){echo "btn-success";}else{echo "btn-secondary";}?>"
                               onClick="changeSec('<?= $_REQUEST['id']?>','2')">2</a><br>Elevated</div>

                        <div class="col-3 text-center"><a id="a3" href="javascript:void(0)" class="secButton btn <?php if($cd['access']==3){echo "btn-success";}else{echo "btn-secondary";}?>"
                               onClick="changeSec('<?= $_REQUEST['id']?>','3')">3</a><br>Assigned</div>

                    </div>


                </div>
            </div>
        </div>
        <?php }?>
        <input type="hidden" name="id" value="<?= $_REQUEST['id']?>" class="form-inline">
        <input type="hidden" name="FUNCTION" value="update">
        <input type="hidden" name="tenant" value="<?=TENANT_URL?>">
        <input id="btn_update" type="submit" name="submit" value="Update" style="display:none" />
</form>

<?php require_once(ROOT_URL.'/forms/elements/signature_edit.frm');?>
<?php require_once(ROOT_URL.'/forms/elements/profile_image.frm');?>
<div class="spacer"></div>
<script type="text/javascript" src="<?=ROOT_URL?>/packages/jqpass/pwstrength-bootstrap.min.js"></script>
<script>
function changeSec(i, s, n) {
    var secButtons = document.querySelectorAll('.secButton');
    for (var j = 0; j < secButtons.length; j++) {
        secButtons[j].classList.remove('btn-success');
    }

    var formData = new FormData();
    formData.append('FCN', 'changeSec');
    formData.append('id', i);
    formData.append('sec', s);
    formData.append('type', 'surveyor');
    formData.append('name', n);
    formData.append('tenant', TENANT_URL);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', ROOT_URL + '/functions/edit_user.php', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {

                document.getElementById('a' + s).classList.remove('btn-secondary');
                document.getElementById('a' + s).classList.add('btn-success');

                var seclev = s;
                switch (seclev) {
                    case "0":
                        showResponse('warning', 'Surveyor access <strong>SUSPENDED</strong>');
                        break;
                    case "1":
                        showResponse('success', 'Security level changed to <strong>Full administrative access</strong>');
                        break;
                    case "2":
                        showResponse('success', 'Security level changed to <strong>Elevated access</strong>');
                        break;
                    case "3":
                        showResponse('success', 'Security level changed to <strong>Assigned access</strong>');
                        break;
                }
            } else {
                // Handle error here
            }
        }
    };
    xhr.send(formData);
}

document.addEventListener("DOMContentLoaded", function() {

        
            document.getElementById('navBox').innerHTML = `
    <li class="breadcrumb-item"><a href="index.php?t=includes/master&p=surveyor.php&view=list">Surveyors</a>
        <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i>
    </li>
    <li class="breadcrumb-item active">Edit Surveyor: <?= $cd['forename']?> <?= $cd['surname']?></li>`;

    document.getElementById('footerControls').innerHTML = '<button class="btn btn-secondary" onclick="triggerAction(\'btn_update\')">UPDATE</button>';


    // Form submission with AJAX using pure JavaScript
    const surveyorForm = document.getElementById('surveyorForm');
    surveyorForm.addEventListener('submit', function(event) {
        event.preventDefault();

        const formData = new FormData(surveyorForm);

        fetch(ROOT_URL + '/includes/surveyor/surveyor_functions.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(result => {
                if (result.trim() === "success") {
                    showResponse('success', 'Your changes have been saved successfully');
                } else {
                    window.location.href = 'index.php?t=includes/master&p=surveyor.php&view=edit&id=' + result;
                }
            })
            .catch(error => console.error('Error:', error));
    });
});

$(document).ready(function() {
    "use strict";
    var options = {
        container: "#pcont",
        colorClasses: ["danger", "danger", "danger", "warning", "warning", "success"]
    };
    options.ui = {
        container: "#pcont",
        viewports: {
            progress: ".pwstrength_viewport_progress"

        },
        colorClasses: ["danger", "danger", "danger", "warning", "warning", "success"],
        showVerdictsInsideProgressBar: true
    }
    $('#password').pwstrength(options);
});
</script>