<?php
$profileMode = (($_REQUEST['profile'] ?? '') === '1');
$isSelfSurveyorProfile = $profileMode && (($_SESSION['usertype'] ?? '') === 'surveyor');
if ($isSelfSurveyorProfile) {
    $_REQUEST['id'] = (int)($_SESSION['userid'] ?? 0);
}
$surveyorId = (int)($_REQUEST['id'] ?? 0);
if ($surveyorId <= 0) {
    echo '<div class="alert alert-danger">Unable to load surveyor profile.</div>';
    return;
}
$r=mysqli_query($GLOBALS['con'],"SELECT * FROM `surveyor` WHERE `id`='".$surveyorId."'")or die(mysqli_error($GLOBALS['con']));
$cd=mysqli_fetch_array($r);
$dayStartTime = !empty($cd['day_start_time']) ? substr((string)$cd['day_start_time'], 0, 5) : '';


    $email_values = [
        'clientNumber' => '0',
        'clientName' => $cd['forename'].' '.$cd['surname'],
        'primaryEmail' => $cd['email'],
        'secondaryEmail' => '',
        'subject' => '',
        'message' => '',
        'filePath' => '',
        'fileName' => ''
    ];
    $email64_values = base64_encode(json_encode($email_values));
?>
<style>
.pwstrength_viewport_progress .progress {
    height: 15px !important
}
</style>


<div class="row mb-4">
    <?php if (!$isSelfSurveyorProfile) { ?>
    <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="<?= htmlspecialchars($email64_values, ENT_QUOTES) ?>" 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>
    <?php } ?>

    <div class="col-12 <?= $isSelfSurveyorProfile ? '' : 'col-md-9 order-md-1 order-2' ?>">

        <div class="row mb-3">
            <div class="note note-secondary">
                <?php if ($isSelfSurveyorProfile) { ?>
                Profile settings <small class="muted">Update your contact details, work day start time, login details and reporting signature.</small>
                <?php } else { ?>
                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>
                <?php } ?>
            </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" data-help-topic="surveyor_work_day_start">Work day start time</div>
                <div class="card-body"><div class="timepicker" data-mdb-timepicker-init data-mdb-with-icon="false" data-mdb-input-init>
                    <label class="form-label" for="day_start_time">Day start time</label>
                    <input type="text" id="day_start_time" name="day_start_time" class="form-control" value="<?= htmlspecialchars($dayStartTime, ENT_QUOTES) ?>" data-mdb-toggle="timepicker" >
                    <small class="text-muted">Used as the home departure time for the first appointment travel check.</small>
                </div></div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12 col-md-4 mb-5">
            <div class="card">
                <div class="card-header" data-help-topic="surveyor_access_password">Access Password</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 }
                     $login_email_values = [
                        'clientNumber' => '0',
                        'clientName' => $cd['forename'].' '.$cd['surname'],
                        'primaryEmail' => $cd['email'],
                        'secondaryEmail' => '',
                        'subject' => getCompanyDetails('name').' login Details',
                        'message' => 'Your login details for access to EnRep are as follows:
                    URL: <a href="'.getCompanyDetails('web').'">'.getCompanyDetails('web').'</a>
                    Username: '.$cd['email'].'
                    Password: '.$data['pass'],
                        'filePath' => '',
                        'fileName' => ''
                    ];
                    $login_email64_values = base64_encode(json_encode($login_email_values));?>


                <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="password" name="password" id="password" value="<?= $data['pass'] ?>" autocomplete="new-password" required />
                                <button type="button"
                                        id="surveyor_password_toggle"
                                        class="btn btn-outline-secondary btn-sm m-0 px-3 py-2"
                                        onclick="toggleSurveyorPasswordVisibility()"
                                        aria-label="Show surveyor password"
                                        title="Show password">
                                    <i id="surveyor_password_toggle_icon" class="fad fa-eye"></i>
                                </button>
                                <button type="button"
                                        class="btn btn-info btn-sm m-0 px-3 py-2 emailButton"
                                        data-values="<?= htmlspecialchars($login_email64_values, ENT_QUOTES) ?>"
                                        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>


        <?php if (!$isSelfSurveyorProfile) { ?>
        <div class="col-12 col-md-4 text-center mb-5">
            <div class="card">
                <div class="card-header" data-help-topic="surveyor_status">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 } ?>

        <?php if($isSelfSurveyorProfile || $_SESSION['usertype']=="contractor"){}
        else{?>
        <div class="col-12 col-md-4 text-center mb-5">
            <div class="card">
                <div class="card-header" data-help-topic="surveyor_security_level">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="<?= $surveyorId ?>" class="form-inline">
        <input type="hidden" name="FUNCTION" value="update">
        <?php if ($isSelfSurveyorProfile) { ?>
        <input type="hidden" name="profile" value="1">
        <?php } ?>
        <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 toggleSurveyorPasswordVisibility() {
    const passwordField = document.getElementById('password');
    const toggleButton = document.getElementById('surveyor_password_toggle');
    const toggleIcon = document.getElementById('surveyor_password_toggle_icon');
    const isHidden = passwordField.type === 'password';

    passwordField.type = isHidden ? 'text' : 'password';
    toggleButton.setAttribute('aria-label', isHidden ? 'Hide surveyor password' : 'Show surveyor password');
    toggleButton.setAttribute('title', isHidden ? 'Hide password' : 'Show password');
    toggleIcon.className = isHidden ? 'fad fa-eye-slash' : 'fad fa-eye';
}

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 = `
    <?php if ($isSelfSurveyorProfile) { ?>
    <li class="breadcrumb-item active">Profile</li>`;
    <?php } else { ?>
    <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>`;
    <?php } ?>

    document.getElementById('footerControls').innerHTML = '<button class="btn btn-secondary" onclick="triggerAction(\'btn_update\')"><?= $isSelfSurveyorProfile ? 'UPDATE PROFILE' : '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 => {
                result = result.trim();
                if (result === "success") {
                    showResponse('success', '<?= $isSelfSurveyorProfile ? 'Your profile has been saved successfully' : 'Your changes have been saved successfully' ?>');
                } else if (result === "capacity") {
                    showResponse('warning', 'Surveyor limit reached. This email is not recognised as an owner of another EnRep tenant.');
                } else {
                    showResponse('danger', 'Unable to save surveyor changes: ' + 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>
