{% extends 'dashboard/employee_dashboard/main.html' %}
{% load static %}
{% block content %}

<!-- Consolidated Styles for Autocomplete Suggestions and Time Inputs -->
<style>
    .suggestions {
        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%;
    }

    .suggestions option {
        padding: 10px;
        cursor: pointer;
    }

    .suggestions option:hover {
        background-color: #f0f0f0;
    }

    @media (max-width: 768px) {
        .suggestions {
            max-width: 90%;
            left: 5%;
            right: 5%;
        }
    }

    @media (max-width: 576px) {
        .suggestions {
            max-height: 150px;
        }
    }

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

<h4 class="fw-bold py-3 mb-4"> 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="btn-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="exampleInputFirstname1">First name</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="exampleInputFirstname1" name="Firstname" placeholder="Enter Firstname">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="exampleInputLastname1">Last name</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="exampleInputLastname1" name="Lastname" placeholder="Enter Lastname">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="exampleInputEmail1">Email address <span style="color:red">*</span></label>
                                <div class="input-group input-group">
                                    <input type="email" class="form-control" id="exampleInputEmail1" name="Email" placeholder="Email" required>
                                    <select id="emailSuggestions" class="form-control suggestions" size="10" style="display: none;"></select>
                                </div>
                                <div class="form-text">You can use letters, numbers & periods</div>
                                <div id="emailCheckResult" class="form-text" style="color: red;"></div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="mobileNumberInput">Mobile Number</label>
                                <div class="input-group 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 suggestions" size="10" style="display: none;"></select>
                                </div>
                                <div id="mobileCheckResult" class="form-text" style="color: red;"></div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="genderSelect">Gender</label>
                                <select class="form-control" id="genderSelect" name="gender">
                                    <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</label>
                                <select class="form-control" id="vtd" name="visitors_type">
                                    <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</label>
                                <textarea class="form-control" id="Address" name="Address" rows="3" placeholder="Enter your address ..."></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="exampleInputFile">Profile Image</label>
                                <input type="file" name="image" id="exampleInputFile" class="form-control" accept=".png,.jpg,.jpeg">
                                <input type="hidden" id="base_user_image" name="user_image" value="">
                                <img id="userImage" style="display: none; max-width: 100px; margin-top: 10px;" alt="Profile Image">
                                <div id="image_user" style="display: none;">Selected Image</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_id" required>
                                    <option value="">Choose employee</option>
                                    {% for i in all_employee %}
                                        <option value="{{ i.id }}" {% if i.id == select_employee %}selected{% endif %}>{{ 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 }}" {% if companyes.id == select_companyes %}selected{% endif %}>{{ 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 }}" {% if departments.id == select_departmentes %}selected{% endif %}>{{ 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 }}" {% if locationes.id == select_locationes %}selected{% endif %}>{{ 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="text" class="form-control" id="timepicker" name="time" placeholder="Select time" required>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="visitorsTiming">Visitors Timing</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="visitorsTiming" 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="mt-3 mb-3">
                              <label class="form-label">Device</label>
                              <textarea class="form-control" rows="3" placeholder="Device ..." name="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="">
                    <div class="mt-3 d-flex justify-content-end">
                        <button type="submit" class="btn btn-primary" id="btn_submit">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- Scripts -->
<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 () {
    // === Flatpickr Initialization ===
    flatpickr("#timepicker", {
        enableTime: true,
        noCalendar: true,
        dateFormat: "h:i K",
        time_24hr: false,
        defaultDate: new Date()
    });

    flatpickr("#visitorsTiming", {
        enableTime: true,
        noCalendar: true,
        dateFormat: "h:i K",
        time_24hr: false
    });

    // === Datepicker: Set Min Date and Default to Today ===
    const dateInput = document.getElementById('datepicker');
    const today = new Date().toISOString().split('T')[0];
    dateInput.min = today;
    dateInput.value = today;

    // === Initialize Select2 ===
    $('.select2').select2({
        placeholder: "Select an option",
        allowClear: false // REMOVE clear (x) button
    });

    $('#employee-dropdown').select2({
        placeholder: "Select an employee",
        allowClear: false // REMOVE clear (x) button
    });

    // === Handle Employee Change and Load Company/Dept/Location ===
    $('#employee-dropdown').on('change', function () {
        const url = "{% url 'gate_keeper_ajax_load_employee' %}";
        const employeeId = $(this).val();
        console.log("Selected Employee ID:", 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;
        }

        $.ajax({
            url: url,
            data: { employee_id: employeeId },
            success: function (data) {
                console.log("AJAX Response:", data);
                $("#company_ide").html('');
                $("#department_ide").html('');
                $("#location_id").html('');

                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>`);
                }
            },
            error: function (xhr, status, error) {
                console.error('AJAX Error:', error);
            }
        });
    });
});
</script>

<script>
    $(document).ready(function() {
    // Set CSRF token for Ajax requests
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/.test(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
            }
        }
    });

    // Function to get CSRF token
    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;
    }

    // Handle input in the mobile number field
    $('#mobileNumberInput').on('input', function() {
        const inputMobile = $(this).val();
        if (inputMobile.length === 0) {
            clearUserFields();
            clearSuggestions('#mobileSuggestions');
            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('#mobileSuggestions');
        }
    });

    // Handle input in the email address field
    $('#exampleInputEmail1').on('input', function() {
        const inputEmail = $(this).val();
        if (inputEmail.length === 0) {
            clearUserFields();
            clearSuggestions('#emailSuggestions');
            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('#emailSuggestions');
        }
    });

    // Handle change event for mobile suggestions
    $('#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('#mobileSuggestions');
        fetchUserData(selectedMobile, userId);
    });

    // Handle change event for email suggestions
    $('#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('#emailSuggestions');
        fetchUserDataByEmail(selectedEmail, userId);
    });

    // Fetch user data based on mobile number
    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) {
                $('#mobileCheckResult').text('Error fetching user data.').css('color', 'red');
                clearUserFields();
            }
        });
    }

    // Fetch user data based on email address
    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();
            }
        });
    }

    // Populate user fields with fetched data
    function populateUserFields(user) {
        $('#exampleInputFirstname1').val(user.first_name);
        $('#exampleInputLastname1').val(user.last_name);
        if (user.email) {
            $('#exampleInputEmail1').val(user.email);
        }
        if (user.mobile_number) {
            $('#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();
            setBaseUserImage(user.image);
            $('#image_user').show();
        } else {
            $('#userImage').hide();
            $('#image_user').hide();
        }
    }

    // Clear user input fields
    function clearUserFields() {
        $('#exampleInputFirstname1').val('');
        $('#exampleInputLastname1').val('');
        $('#exampleInputEmail1').val('');
        $('#mobileNumberInput').val('');
        $('#genderSelect').val('');
        $('#Address').val('');
        $('#userImage').attr('src', '').hide();
        setBaseUserImage('');
        $('#image_user').hide();
        $('#mobileCheckResult').text('');
        $('#emailCheckResult').text('');
    }

    // Clear suggestion dropdowns
    function clearSuggestions(selector) {
        $(selector).empty().hide();
    }

    // Update hidden input field value based on user image
    function setBaseUserImage(src) {
        $('#base_user_image').val(src);
    }

    // Handle file input change for profile image
    $('#exampleInputFile').on('change', function() {
        const file = this.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const imageSrc = e.target.result;
                $('#userImage').attr('src', imageSrc).show();
                setBaseUserImage(imageSrc);
                $('#image_user').show();
            };
            reader.readAsDataURL(file);
        } else {
            $('#userImage').attr('src', '').hide();
            setBaseUserImage('');
            $('#image_user').hide();
        }
    });

    // Validate numeric input for mobile number
    function validateNumericInput(input) {
        input.value = input.value.replace(/[^0-9]/g, '');
    }
});
</script>
{% endblock %}