{% extends 'dashboard/gate_keeper_dashboard/main.html' %}
{% load static %}
{% block content %}
<!-- jQuery (Required for your scripts) -->
<!--<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>-->

 <!--Flatpickr (Time Picker) -->
<!--<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">-->
<!--<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>-->

 <!--Bootstrap JS (Optional, required for alert close buttons, modals, etc.) -->
<!--<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>-->
 <!--Select2 CSS-->
<!--<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />-->

 <!--Select2 JS (AFTER jQuery) -->
<!--<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>-->
 <!--Order matters: jQuery first, then Select2 -->
<!--<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>-->
<!--<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />-->
<!--<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>-->

<!-- Styles for Autocomplete Suggestions -->
<style>
    #mobileSuggestions, #emailSuggestions {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        background-color: #fff;
        border: 1px solid #ccc;
        border-radius: 4px;
        max-height: 179px;
        overflow-y: auto;
        z-index: 1001;
        display: none;
        width: 100%;
    }

    #mobileSuggestions option, #emailSuggestions option {
        padding: 10px;
        cursor: pointer;
    }

    #mobileSuggestions option:hover, #emailSuggestions option:hover {
        background-color: #f0f0f0;
    }

    /* Media Queries for Responsiveness */
    @media (max-width: 768px) {
        #mobileSuggestions, #emailSuggestions {
            max-width: 90%;
            left: 5%;
            right: 5%;
        }
    }

    @media (max-width: 576px) {
        #mobileSuggestions, #emailSuggestions {
            max-height: 150px;
        }
    }

    #timepicker, #timepickere {
        background-color: #fff !important;
    }
</style>

<h4 class="fw-bold py-3 mb-4"><span class="text-muted fw-light">Forms/</span> Add Appointment</h4>

<!-- Messages Section -->
{% 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 %}

<!-- Form Section -->
<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 Add Appointment</h5>
                <small class="text-muted float-end">Control Panel</small>
            </div>
            <div class="card-body">
                <form role="form" method="POST" enctype="multipart/form-data" action="" autocomplete="off" onsubmit="const btn=this.querySelector('button[type=submit]'); btn.disabled=true; btn.innerText='Processing...';">
                    {% csrf_token %}
                    <div class="row">
                        <!-- Left Column -->
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label" for="Firstnames">First name <span style="color:red">*</span></label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="Firstnames" name="Firstname" placeholder="Enter Firstname" required>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="exampleInputLastname1">Last name <span style="color:red">*</span></label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="exampleInputLastname1" name="Lastname" placeholder="Enter Lastname" required>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="exampleInputEmail1">Email address</label>
                                <div class="input-group">
                                    <input type="email" class="form-control" id="exampleInputEmail1" name="Email" placeholder="Email">
                                    <select id="emailSuggestions" class="form-control" size="10" style="display: none;"></select>
                                </div>
                                <div class="form-text">You can use letters, numbers & periods</div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="mobileNumberInput">Mobile Number</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="mobileNumberInput" name="mobile" placeholder="Enter Mobile Number" pattern="[0-9]*" inputmode="numeric" minlength="10" maxlength="11" oninput="validateNumericInput(this)">
                                    <select id="mobileSuggestions" class="form-control" size="10" style="display: none;"></select>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="genderSelect">Gender <span style="color:red">*</span></label>
                                <select class="form-control" id="genderSelect" name="gender" required>
                                    <option value="">Choose Gender</option>
                                    <option value="Male">Male</option>
                                    <option value="Female">Female</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="vtd">Visitors Type <span style="color:red">*</span></label>
                                <select class="form-control" id="vtd" name="visitors_type" required>
                                    <option value="">Choose visitors type</option>
                                    <option value="auditor">Auditor</option>
                                    <option value="candidate">Candidate</option>
                                    <option value="customer">Customer</option>
                                    <option value="general">General</option>
                                    <option value="government officer">Government Officer</option>
                                    <option value="interviewer">Interviewer</option>
                                    <option value="vendor">Vendor</option>
                                    <option value="other">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">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="Address">Address <span style="color:red">*</span></label>
                                <textarea class="form-control" id="Address" name="Address" rows="3" placeholder="Enter your address ..." required></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Profile Image <span style="color:red">*</span></label>
                                <div class="picture-container">
                                    <div class="col-lg-6">
                                        <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>
                                        <br>
                                        <button type="button" class="btn btn-primary btn-open-camera">Open Camera</button>
                                        <button type="button" class="btn btn-success btn-take-picture">Take a Picture</button>
                                    </div>
                                    <div class="col-lg-3">
                                        <div class="form-group" id="image_user" style="display:none;">
                                            <img src="" alt="" width="150" height="150" id="userImage">
                                            <input type="hidden" value="" id="base_user_image" name="user_image">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Right Column -->
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label" for="employee-dropdown">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 }}">{{ i.employee_code }} {{ i.first_name }} {{ i.last_name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="company_ide">Company <span style="color:red">*</span></label>
                                <select class="form-control" id="company_ide" name="company_id" required>
                                    <option value="">-- Select Company --</option>
                                    {% for companyes in companyes %}
                                        <option value="{{ companyes.id }}">{{ companyes.company_name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="department_ide">Department <span style="color:red">*</span></label>
                                <select class="form-control" id="department_ide" name="department_id" required>
                                    <option value="">-- Select Department --</option>
                                    {% for departments in departmentes %}
                                        <option value="{{ departments.id }}">{{ departments.department_name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="location_id">Location <span style="color:red">*</span></label>
                                <select class="form-control" id="location_id" name="location_id" required>
                                    <option value="">-- Select Location --</option>
                                    {% for locationes in locationes %}
                                        <option value="{{ locationes.id }}">{{ locationes.location_name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="datepicker">Check In Date <span style="color:red">*</span></label>
                                <div class="input-group">
                                    <input type="date" class="form-control" id="datepicker" name="date" required>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="timepicker">Check In Time <span style="color:red">*</span></label>
                                <div class="input-group">
                                    <input type="time" class="form-control" id="timepicker" name="time" placeholder="Select time" required>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" >Visitors Timing</label>
                                <div class="input-group">
                                    <input type="time" class="form-control"  name="visitors_timing" placeholder="Select time">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="detail">Other Detail</label>
                                <textarea class="form-control" id="detail" name="detail" rows="3" placeholder="Other Detail ..."></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="Purpose">Purpose <span style="color:red">*</span></label>
                                <textarea class="form-control" id="Purpose" name="Purpose" rows="3" placeholder="Purpose ..." required></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="devices">Devices</label>
                                <textarea class="form-control" id="devices" name="devices" rows="3" placeholder="Devices ..."></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="status">Status <span style="color:red">*</span></label>
                                <select class="form-control" id="status" name="status" required>
                                    <option value="1">Active</option>
                                    <option value="0">Inactive</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <input type="hidden" name="user_id" value="">
                    <button type="submit" class="btn btn-primary" id="btn_submit" disabled>Submit</button>
                </form>
            </div>
        </div>
    </div>
</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>
<!-- Scripts -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize Flatpickr for timepickers
        flatpickr("#timepicker, #timepickere", {
            enableTime: true,
            noCalendar: true,
            dateFormat: "h:i K",
            time_24hr: false,
            defaultDate: new Date()
        });

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

        // Initialize Select2 for employee dropdown
        $('#employee-dropdown').select2();
    });
</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;
        const capturePhotoUrl = '{% url "capture_photo" %}';

        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) {
                context.drawImage(video, 0, 0, 150, 150);
                const imageDataURL = canvas.toDataURL('image/jpeg');
                if (imageElement && inputElement) {
                    imageElement.src = imageDataURL;
                    inputElement.value = imageDataURL;
                    $("#image_user").show();
                    $('#btn_submit').prop('disabled', false);
                }
                imageCount++;
                video.srcObject.getTracks().forEach(track => track.stop());
            }
        }

        openCameraBtn.addEventListener('click', openCamera);
        takePictureBtn.addEventListener('click', takePicture);
    });
</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>
<script type="text/javascript">
  $("#employee-dropdown").change(function () {
      var url = "{% url 'gate_keeper_ajax_load_employee' %}";
      var employeeId = $(this).val();
      console.log('employeeId:-', employeeId)
      if (employeeId === '') {
          $("#company_ide").html('<option value="">-- Select Company --</option>');
          $("#department_ide").html('<option value="">-- Select Department --</option>');
          $("#location_id").html('<option value="">-- Select Location --</option>');

          return; // Exit the function early if no employee is selected
      }

      $.ajax({
          url: url,
          data: {
              'employee_id': employeeId
          },
          success: function (data) {
              $("#company_ide").html('<option value="">-- Select Company --</option>');
              $("#department_ide").html('<option value="">-- Select Department --</option>');
              $("#location_id").html('<option value="">-- Select Location --</option>');
              console.log('employeedata:-', data)
              console.log('employeedata:-', data.company[0].id)

              if (data.company[0].id) {
                  $("#company_ide").append('<option value="' + data.company[0].id + '" selected>' + data.company[0].company_name + '</option>');

              if (data.departments[0].id) {
                  $("#department_ide").append('<option value="' + data.departments[0].id + '" selected>' + data.departments[0].department_name + '</option>');
              }

              if (data.location[0].id) {
                  $("#location_id").append('<option value="' + data.location[0].id + '" selected>' + data.location[0].location_name + '</option>');
              }

              } else {
                  console.log('No company data returned');
              }
          },
          error: function(xhr, status, error) {
              console.log('Error:', error);
          }
      });
  });
</script>

{% endblock %}