{% extends 'dashboard/gate_keeper_dashboard/main.html' %}
{% load static %}
{% block content %}
<!-- Right side column. Contains the navbar and content of the page -->
<style>
    /* Ensure Time and Visitors Timing fields have white background */
    #timepicker, #timepickere {
        background-color: #fff !important;
    }
</style>
<h4 class="fw-bold py-3 mb-4"><span class="text-muted fw-light">Forms/</span> Edit Appointment</h4>
{% if messages %}
    {% for message in messages %}
    <div class="alert {% if 'success' in message.tags %}alert-success{% elif 'danger' in message.tags %}alert-danger{% endif %}" role="alert" id="success-alert">
        {{ message }}
        <button type="button" class="close" data-bs-dismiss="alert" aria-label="Close">
        </button>
    </div>
    {% endfor %}
{% endif %}
<div class="row">
    <div class="col-xl">
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Quick Edit Appointment</h5>
                <small class="text-muted float-end">Control Panel</small>
            </div>
            <div class="card-body">
                  <!-- form start -->
                    <form role="form" method="POST" enctype="multipart/form-data" action="" onsubmit="const btn=this.querySelector('button[type=submit]'); btn.disabled=true; btn.innerText='Processing...';">
                        {% csrf_token %}
                        
                            <div class='row'>
                                <div class='col-md-6'>
                                    <div class="mb-3">
                                        <label for="exampleInputFirstname1" class="form-label">First name <span style="color:red">*</span></label>
                                        <div class="input-group">
                                        <span class="input-group-addon"><i class="fa fa-user"></i></span>
                                        <input type="text" class="form-control" id="exampleInputFirstname1" placeholder="Enter Firstname" name="Firstname" value='{{user.first_name}}' required>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label for="exampleInputLastname1" class="form-label">Last name <span style="color:red">*</span></label>
                                        <div class="input-group">
                                        <span class="input-group-addon"><i class="fa fa-user"></i></span>
                                        <input type="text" class="form-control"  id="exampleInputLastname1" placeholder="Enter Lastname" name="Lastname" value='{{user.last_name}}' required>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label for="exampleInputEmail1" class="form-label">Email Address</label>
                                        <div class="input-group">
                                        <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
                                        <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" name="Email" value='{{ user.email |default:'' }}'>
                                        <select id="emailSuggestions" class="form-control" size="10" style="display: none;"></select>
                                        </div>
                                    </div>
                
                                 
                                    <div class="mb-3">
                                        <label class="form-label">Mobile Number</label>
                                        <div class="input-group">
                                        <div class="input-group-addon">
                                            <i class="fa fa-phone"></i>
                                        </div>
                                        <input type="text" class="form-control" id="mobileNumberInput" placeholder="Enter Mobile Number" pattern="[0-9]*" inputmode="numeric" minlength ="10" maxlength='11' name="mobile" value='{{user.mobile}}' oninput="validateNumericInput(this)"> 
                                        <select id="mobileSuggestions" class="form-control" size="10" style="display: none;"></select>
                                        </div><!-- /.input group -->
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Gender <span style="color:red">*</span></label>
                                        <select class="form-control" name="gender" required>
                                        <option>Choose Gender</option>
                                        <option {% if user.gender == 'Male'  %} selected {% endif %}>Male</option>
                                    <option {% if user.gender == 'Female'  %} selected {% endif %}>Female</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Visitors Type <span style="color:red">*</span></label>
                                        <select class="form-control select2" name="visitors_type" required>
                                            <option value="">Choose visitors type</option>
                                            <option value="auditor"{% if appointment.visitors_type == 'auditor'  %} selected {% endif %}>Auditor</option>
                                            <option value="candidate"{% if appointment.visitors_type == 'candidate'  %} selected {% endif %}>Candidate </option>
                                            <option value="customer"{% if appointment.visitors_type == 'customer'  %} selected {% endif %}>Customer</option>
                                            <option value="general"{% if appointment.visitors_type == 'general'  %} selected {% endif %}>General</option>
                                            <option value="government officer"{% if appointment.visitors_type  == 'government officer'  %} selected {% endif %}>Government Officer</option>
                                            <option value="interviewer"{% if appointment.visitors_type == 'interviewer'  %} selected {% endif %}>Inter viewer</option>
                                            <option value="vendor"{% if appointment.visitors_type == 'vendor'  %} selected {% endif %}>vendor</option>
                                            <option value="other"{% if appointment.visitors_type == 'other'  %} selected {% endif %}>Other</option>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label" for="visitor_company_name">Visitor Company Name</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="visitor_company_name" name="visitor_company_name" placeholder="Enter Visitor Company Name" value="{{appointment.visitor_company_name}}">
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label">Address <span style="color:red">*</span></label>
                                        <textarea class="form-control" rows="3" placeholder="Enter your address ..." name="Address" required>{{user.address}}</textarea>
                                    </div>
                    
                                    <div class ='col-md-6'>
                                        <div class="form-group mb-3 mt-3">
                                            {% if user.image %}
                                                <img src="{{ user_data.users_images }}/{{ user.image }}" alt="Visitor Image" style="width: 100px; height: 97px;" >
                                            {% else %}
                                                <img src="{{ user_data.default_image}}" alt="Default Image">
                                            {% endif %} 
                                        </div>
                                    </div>
                                    <div class="form-group mb-3">

                                        <label for="exampleInputFile" class="form-label">Profile Image</label>

                                        
                                        <div class="picture-container">
                                            <div class='col-lg-12 mt-3 mb-3' style="display: flex;gap: 20px;">
                                                <video id="video" width="150" height="150" autoplay style='border:1px solid #ccc;object-fit: cover;'></video>
                                                <canvas id="canvas" style="display:none;" width='150' height='150'></canvas>
                                                <div class="form-group" id='image_user' style='display:none' >                                        
                                                    <img src="" alt="" width="150" height="150">
                                                    <input type="hidden" value="" id="base_user_image" name='user_image'>
                                                </div>
                                                <br>
                                                
                                            </div>
                                            <button type="button" class="btn btn-primary btn-open-camera" style="margin-right: 10px;">Open Camera</button>
                                            <button type="button" class="btn btn-info btn-take-picture">Take a Picture</button>
                                            
                                        </div>
    

                                        
                                    </div>
                                    
                                </div>
                            <div class='col-md-6'>                             
                                <div class="form-group mb-3">
                                    <label class="form-label">Employee <span style="color:red">*</span></label>
                                    <select class="form-control select2"  id="employee-dropdown" name="employee" required>
                                        <option value="">Choose employee</option>
                                        {% for i in all_employee %}
                                            <option value="{{ i.id }}" {% if i.id == appointment.employee_id %} selected {% endif %}>{{i.employee_code}} {{ i.first_name }} {{i.last_name}}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="form-group mb-3">
                                    <label class="form-label">Company <span class="color_red" style="color:red">*</span></label>
                                    <select name="company_id" id="company_ide" class="form-control" required="">
                                        <option value="">-- Select Company  --</option>
                                        {% for companyes in companyes %}
                                        <option value="{{companyes.id}}" {% if user.company_id == companyes.id %} selected {% endif %}>{{companyes.company_name}}</option>
                                        {% endfor%}
                                    </select>
                                </div>
                                <div class="form-group mb-3">
                                    <label class="form-label">Department <span class="color_red" style="color:red">*</span></label>
                                    <select name="department_id" id="department_ide" class="form-control" required="">
                                        <option value="">-- Select Department --</option>    
                                        {% for departments in departmentes %}
                                        <option value="{{departments.id}}" {% if user.department_id == departments.id %} selected {% endif %}>{{departments.department_name}}</option>
                                        {% endfor%}
                                    </select>
                                </div>
    
                                <div class="form-group mb-3">
                                    <label class="form-label">Location<span class="color_red" style="color:red">*</span></label>
                                    <select name="location_id" id="location_id" class="form-control" required="">
                                        <option value="">-- Select Location --</option> 
                                        {% for locationes in locationes %}
                                        <option value="{{locationes.id}}" {% if user.location_id == locationes.id %} selected {% endif %}>{{locationes.location_name}}</option>
                                        {% endfor%}
                                    </select>
                                </div>
                             
                                <div class="form-group mb-3">
                                    <label for="exampleInputDate1" class="form-label">Check In Date <span style="color:red">*</span></label>
                                    <div class="input-group">
                                    <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                    <input type="date" class="form-control"  id="datepicker" placeholder="" name="date"  value='{{appointment.date}}' required>
                                    </div>
                                </div>
                                <div class="form-group mb-3">
                                    <label for="exampleInputTime1" class="form-label">Check In Time <span style="color:red">*</span></label>
                                    <div class="input-group">
                                        <span class="input-group-addon"><i class="fa fa-fw fa-clock-o"></i></span>
                                        <input type="text" class="form-control" id="timepicker" placeholder="Select time" name="time" value='{{appointment.time}}' required>
                                    </div>
                                </div>
                                
                                 <div class="form-group mb-3">
                                    <label for="exampleInputTime1" class="form-label">Visitors Timing </label>
                                    <div class="input-group">
                                        <span class="input-group-addon"><i class="fa fa-fw fa-clock-o"></i></span>
                                        <input type="text" class="form-control" id="timepickere" placeholder="Select time" name="visitors_timing" value='{{appointment.visitors_timing}}'>
                                    </div>
                                </div>
                                <div class="form-group mb-3">
                                    <label class="form-label">Other Detail</label>
                                    <textarea class="form-control" rows="3" placeholder="Other Detail ..." name="detail">{{appointment.detail}}</textarea>
                                </div>
                                <div class="form-group mb-3">
                                    <label class="form-label">Purpose <span style="color:red">*</span></label>
                                    <textarea class="form-control" rows="3" placeholder="Purpose ..." name="Purpose" required>{{appointment.purpose}}</textarea>
                                </div>
                                <div class="mt-3 mb-3">
                              <label class="form-label">Device</label>
                              <textarea class="form-control" rows="3" placeholder="Device ..." name="devices">{{appointment.devices|default_if_none:""}}</textarea>
                            </div>
                                <div class="form-group mb-3">
                                    <label class="form-label">Status  <span style="color:red">*</span></label>
                                    <select name="status" id="status" class="form-control" required="">
                                      <option value="1" {% if user.is_active == '1'  %} selected {% endif %}>Active</option>
                                      <option value="0" {% if user.is_active == '0'  %} selected {% endif %}>Inactive</option>
                                    </select>
                                  </div>
                                
                            </div>                       
                        
    
                        <div class="box-footer text-right">
                            <button type="submit" class="btn btn-primary">Submit</button>
                        </div>
                    </form>
                </div>    
              </div>
            </div>   <!-- /.row -->
        </div>
    </section>
</div>
<script src="{% static 'plugins/fastclick/fastclick.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'default/header/flatpickr.min.css' %}">
<script src="{% static 'default/header/flatpickr.js' %}"></script>
<script src="{% static 'plugins/jQuery/jquery-3.6.0.min.js' %}"></script>
<script src="{% static 'select2/js/select2.min.js' %}"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize Flatpickr for timepicker
        flatpickr("#timepicker", {
            enableTime: true,
            noCalendar: true,
            dateFormat: "h:i K", // AM/PM format
            time_24hr: false // Use 12-hour format
        });

        // Set the minimum date for datepicker
        var dateInput = document.getElementById('datepicker');
        var today = new Date().toISOString().split('T')[0];
        dateInput.setAttribute('min', today);

        // Initialize Select2
        $('.select2').select2({
            placeholder: "Select an option",
            allowClear: true
        });
    });
</script>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        const openCameraBtn = document.querySelector('.btn-open-camera');
        const takePictureBtn = document.querySelector('.btn-take-picture');
        const video = document.getElementById('video');
        const canvas = document.getElementById('canvas');
        const imageElement = document.querySelector('#image_user img');
        const inputElement = document.querySelector('#image_user input');
        const context = canvas.getContext('2d');
        let imageCount = 0; // Counter for the number of images captured
        const capturePhotoUrl = '{% url "capture_photo" %}';
        console.log('Capture Photo URL:', capturePhotoUrl); 
        
        function openCamera() {
            try {
                if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                    navigator.mediaDevices.getUserMedia({ video: true })
                    .then(function(stream) {
                        video.srcObject = stream;
                    })
                    .catch(function(error) {
                        console.error('Error accessing the camera:', error);
                    });
                } else {
                    console.error("Camera not supported by this browser.");
                }
            } catch(err) {
                console.error('Error:', err);
            }
        }

        function takePicture() {
            if (imageCount < 1) { // Take pictures until 5 images are captured
                context.drawImage(video, 0, 0, 150, 150);
                console.log('context:', context);
                const imageDataURL = canvas.toDataURL('image/jpeg');
                console.log('Picture taken:', imageDataURL);

                if (imageElement) {
                    imageElement.src = imageDataURL;
                    inputElement.value = imageDataURL;
                    $("#image_user").show();
                    $('#btn_submit').prop('disabled', false);
                }

                // Send the captured image data to the server using AJAX
                /*$.ajax({
                    url: capturePhotoUrl,
                    type: 'POST',
                    data: {
                        image: imageDataURL,
                        name: firstNameInput.value
                    },
                    success: function(data) {
                        console.log('Server response:', data);
                        // Handle the server response as needed
                        if (data.status === 'success') {
                            imageCount++;
                            if (imageCount === 1) {
                                // Close the camera after capturing 5 images
                                video.srcObject.getTracks().forEach(track => {
                                    track.stop();
                                });
                            }
                        } else {
                            console.error('Image capture failed.');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Error sending image data:', error);
                        // Handle error
                    }
                });*/
            }
        }

        openCameraBtn.addEventListener('click', openCamera);
        takePictureBtn.addEventListener('click', takePicture);
    });
</script>
<script type="text/javascript">
    $(document).ready(function() {
        $('#emp_area').multiselect({search: true,});
    });
</script>
<script>
    $(document).ready(function() {
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!/^(GET|HEAD|OPTIONS|TRACE)$/.test(settings.type)) {
                    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                }
            }
        });

        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.startsWith(name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // Mobile Number Autocomplete
        $('#mobileNumberInput').on('input', function() {
            const inputMobile = $(this).val();
            console.log('Input mobile number:', inputMobile);
            if (inputMobile.length === 0) {
                clearUserFields();
                clearSuggestions();
                return;
            }
            if (inputMobile.length >= 2) {
                $.ajax({
                    url: '/autocomplete-mobile-numbers/',
                    type: 'GET',
                    data: { term: inputMobile },
                    success: function(data) {
                        $('#mobileSuggestions').empty().hide();
                        if (data.length > 0) {
                            data.forEach(function(mobile) {
                                const parts = mobile.split(' - ');
                                const mobileNumber = parts[0];
                                const userId = parts[3];
                                $('#mobileSuggestions').append(`<option value="${mobileNumber}" data-id="${userId}">${mobile}</option>`);
                            });
                            $('#mobileSuggestions').show();
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Error:', status, error);
                    }
                });
            } else {
                clearSuggestions();
            }
        });

        // Email Autocomplete
        $('#exampleInputEmail1').on('input', function() {
            const inputEmail = $(this).val();
            console.log('inputEmail',inputEmail)
            if (inputEmail.length === 0) {
                clearUserFields();
                clearSuggestions();
                return;
            }
            if (inputEmail.length >= 3) {
                $.ajax({
                    url: '/autocomplete-emails/',
                    type: 'GET',
                    data: { term: inputEmail },
                    success: function(data) {
                        $('#emailSuggestions').empty().hide();
                        if (data.length > 0) {
                            data.forEach(function(email) {
                                const parts = email.split(' - ');
                                const emailAddress = parts[0];
                                const userId = parts[3];
                                $('#emailSuggestions').append(`<option value="${emailAddress}" data-id="${userId}">${email}</option>`);
                            });
                            $('#emailSuggestions').show();
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Error:', status, error);
                    }
                });
            } else {
                clearSuggestions();
            }
        });

        // Handle Mobile Suggestions Selection
        $('#mobileSuggestions').on('change', function() {
            let selectedMobile = $(this).val();
            const userId = $(this).find(':selected').data('id');
            $('input[name="user_id"]').val(userId);
            $('#mobileNumberInput').val(selectedMobile);
            clearSuggestions();
            fetchUserData(selectedMobile, userId);
        });

        // Handle Email Suggestions Selection
        $('#emailSuggestions').on('change', function() {
            let selectedEmail = $(this).val();
            const userId = $(this).find(':selected').data('id');
            $('input[name="user_id"]').val(userId);
            $('#exampleInputEmail1').val(selectedEmail);
            clearSuggestions();
            fetchUserDataByEmail(selectedEmail, userId);
        });

        function fetchUserData(mobile, userId) {
            $.ajax({
                url: '/get-user-data/',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ mobile: mobile, id: userId }),
                success: function(response) {
                    if (response.success) {
                        populateUserFields(response.user);
                    } else {
                        $('#mobileCheckResult').text('User not found.').css('color', 'red');
                        clearUserFields();
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error:', status, error);
                    $('#mobileCheckResult').text('Error fetching user data.').css('color', 'red');
                    clearUserFields();
                }
            });
        }

        function fetchUserDataByEmail(email, userId) {
            $.ajax({
                url: '/get-user-data-by-email/',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ email: email, id: userId }),
                success: function(response) {
                    if (response.success) {
                        populateUserFields(response.user);
                    } else {
                        $('#emailCheckResult').text('User not found.').css('color', 'red');
                        clearUserFields();
                    }
                },
                error: function(xhr, status, error) {
                    $('#emailCheckResult').text('Error fetching user data.').css('color', 'red');
                    clearUserFields();
                }
            });
        }

        function populateUserFields(user) {
            $('#Firstnames').val(user.first_name);
            $('#exampleInputLastname1').val(user.last_name);
            $('#exampleInputEmail1').val(user.email);
            $('#mobileNumberInput').val(user.mobile_number);
            $('#Address').val(user.address);
            $('#genderSelect').val(user.genderSelect ? user.genderSelect.trim() : '');
            if (user.image) {
                $('#userImage').attr('src', user.image).show();
                $('#base_user_image').val(user.image);
                $('#image_user').show();
            } else {
                $('#userImage').hide();
                $('#image_user').hide();
            }
            $('#btn_submit').prop('disabled', false);
        }

        function clearUserFields() {
            $('#Firstnames').val('');
            $('#exampleInputLastname1').val('');
            $('#exampleInputEmail1').val('');
            $('#mobileNumberInput').val('');
            $('#Address').val('');
            $('#userImage').attr('src', '').hide();
            $('#genderSelect').val('');
            $('#mobileCheckResult').text('');
            $('#emailCheckResult').text('');
            $('#image_user').hide();
            $('#btn_submit').prop('disabled', true);
        }

        function clearSuggestions() {
            $('#mobileSuggestions').empty().hide();
            $('#emailSuggestions').empty().hide();
            $('#btn_submit').prop('disabled', true);
        }
    });
</script>
{% endblock %}