<?php include 'header.php';?>
    
<style>
    /* Password Wrapper */
.password-wrapper {
    position: relative;
}

/* Password Input */
.password-wrapper input {
    padding-right: 40px; /* eye icon ke liye space */
}

/* Eye Icon */
.password-toggle {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
    font-size: 18px;
    color: #6c757d;
}

/* Hover effect */
.password-toggle:hover {
    color: #000;
}
.role-dropdown{
    width: 95% !important;
    left: 15px !important;
}
</style> 

<div class="dashboard-main-body">
    <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
        <h6 class="fw-semibold mb-0">Add User</h6>
    </div>
    <div class="d-flex flex-wrap align-items-center justify-content-end gap-3 mb-3">
        <a type="button" href="user.php" class="tooltip-button btn bg-primary-600 text-white border border-primary-600 radius-8 px-12 py-11 d-flex align-items-center" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-html="true" data-bs-custom-class="tooltip-primary" title="Listing">
            <iconify-icon icon="ic:baseline-arrow-back" class="icon text-xl line-height-1"></iconify-icon>
        </a>
    </div>

    <div class="row gy-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-body">
                    <h6 class="mb-4 text-xl">Add User</h6> <br />
                    <form id="modelform" action="" method="post"  autocomplete="off">
                        <div class="row gy-3">
                            <!-- Name -->
                            <div class="col-sm-6">
                                <label class="form-label">Name<span class="text-danger">*</span></label>
                                <input type="text" name="name" class="form-control" placeholder="Enter Name" value="" />
                            </div>
                            <!-- Mobile Number -->
                            <div class="col-sm-6">
                                <label class="form-label">Mobile Number<span class="text-danger">*</span></label>
                                <input type="tel" name="mobile" class="form-control" placeholder="Enter Mobile Number" value="" minlength="10" maxlength="10" pattern="\d{10}" inputmode="numeric" oninput="this.value = this.value.replace(/[^0-9]/g, '')" />
                            </div>
                            <!-- Eamil -->
                            <div class="col-sm-6">
                                <label class="form-label">Email<span class="text-danger">*</span></label>
                                <input type="email" name="email" class="form-control" placeholder="Enter Email" value="" pattern="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[A-Za-z]{2,}$"  autocomplete="off"/>
                            </div>
                            <!-- Password -->
                            <div class="col-sm-6">
                                <label class="form-label">Password<span class="text-danger">*</span></label>
                                <div class="password-wrapper">
                                    <input type="password" name="password" id="password" class="form-control pe-5" placeholder="Enter Password" />
                                    <i class="bi bi-eye-slash password-toggle" id="togglePassword"></i>
                                </div>
                            </div>
                            <!-- Role -->
                            <div class="col-sm-6 position-relative">
                                <label class="form-label">Role<span class="text-danger">*</span></label>
                                <input type="text" id="search" name="role"  placeholder="Search for Role" class="form-control" autocomplete="off" />
                                <ul id="roleDropdown" class="role-dropdown">
                                    <li>Super Admin</li>
                                    <li>Admin</li>
                                    <li>User</li>
                                    <li>Accountant</li>
                                </ul>
                            </div>
                        </div>
                        <!-- Save Button -->
                        <div class="form-group text-end mt-4">
                            <button type="submit" class="btn-primary-600">
                                <i class="bi bi-floppy"></i>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ============================
     Password Hide/Show Toggle
============================= -->
<script>
document.addEventListener('DOMContentLoaded', function () {
    const togglePassword = document.getElementById('togglePassword');
    const passwordInput = document.getElementById('password');

    if (togglePassword && passwordInput) {
        togglePassword.addEventListener('click', function () {
            const isPassword = passwordInput.type === 'password';
            passwordInput.type = isPassword ? 'text' : 'password';
            this.classList.toggle('bi-eye');
            this.classList.toggle('bi-eye-slash');
        });
    }
});
</script>

<!-- ==================================
     Role Dropdown Search & Selection
=================================== -->
<script>
document.addEventListener('DOMContentLoaded', function () {
    const search = document.getElementById('search');
    const dropdown = document.getElementById('roleDropdown');
    const roleItems = dropdown ? dropdown.querySelectorAll('li') : [];

    function showDropdown() { if (dropdown) dropdown.style.display = 'block'; }
    function hideDropdown() { if (dropdown) dropdown.style.display = 'none'; }
    function showAllItems() { roleItems.forEach(item => item.style.display = 'block'); }

    if (search && dropdown) {
        search.addEventListener('focus', () => { showAllItems(); showDropdown(); });
        search.addEventListener('click', () => { showAllItems(); showDropdown(); });
        search.addEventListener('input', function () {
            const value = search.value.toLowerCase().trim();
            let visibleCount = 0;
            roleItems.forEach(item => {
                if (item.textContent.toLowerCase().includes(value)) {
                    item.style.display = 'block';
                    visibleCount++;
                } else {
                    item.style.display = 'none';
                }
            });
            dropdown.style.display = visibleCount ? 'block' : 'none';
        });

        roleItems.forEach(item => {
            item.addEventListener('click', function () {
                search.value = this.textContent;
                search.style.borderColor = '#28a745'; // mark valid
                hideDropdown();
            });
        });

        document.addEventListener('click', function (e) {
            if (!e.target.closest('#search') && !e.target.closest('#roleDropdown')) {
                hideDropdown();
            }
        });
    }
});
</script>

<!-- ==================================
     Form Validation
=================================== -->
<script>
document.addEventListener('DOMContentLoaded', function () {
    const search = document.getElementById('search');
    const dropdown = document.getElementById('roleDropdown');
    const roleItems = dropdown ? Array.from(dropdown.querySelectorAll('li')) : [];
    const validRoles = roleItems.map(li => li.textContent.trim()); // allowed roles

    // -------------------------
    // Helpers
    // -------------------------
    function showDropdown() { if (dropdown) dropdown.style.display = 'block'; }
    function hideDropdown() { if (dropdown) dropdown.style.display = 'none'; }
    function showAllItems() { roleItems.forEach(item => item.style.display = 'block'); }

    function showError(input, message) {
        const existing = input.parentNode.querySelector('.error-message');
        if (existing) existing.remove();
        const div = document.createElement('div');
        div.className = 'error-message text-danger mt-1 small';
        div.textContent = message;
        input.parentNode.appendChild(div);
    }

    function clearError(input) {
        const existing = input.parentNode.querySelector('.error-message');
        if (existing) existing.remove();
    }

    function validateName() {
        const nameInput = document.querySelector('[name="name"]');
        if (!nameInput.value.trim()) { showError(nameInput, 'Name is required'); return false; }
        return true;
    }

    function validateMobile() {
        const mobileInput = document.querySelector('[name="mobile"]');
        if (!/^\d{10}$/.test(mobileInput.value)) { showError(mobileInput, 'Enter valid 10-digit mobile'); return false; }
        return true;
    }

    function validateEmail() {
        const emailInput = document.querySelector('[name="email"]');
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!re.test(emailInput.value)) { showError(emailInput, 'Enter valid email'); return false; }
        return true;
    }

    function validatePassword() {
        const passwordInput = document.getElementById('password');
        if (!passwordInput.value || passwordInput.value.length < 6) { showError(passwordInput, 'Password min 6 characters'); return false; }
        return true;
    }

    function validateRole() {
        const value = search.value.trim();
        if (!validRoles.includes(value)) {
            showError(search, 'Select a valid role');
            return false;
        }
        return true;
    }

    // -------------------------
    // Role Dropdown Behavior
    // -------------------------
    if (search && dropdown) {
        // open dropdown
        search.addEventListener('focus', () => { showAllItems(); showDropdown(); });
        search.addEventListener('click', () => { showAllItems(); showDropdown(); });

        // filter as user types
        search.addEventListener('input', function () {
            const value = search.value.toLowerCase().trim();
            let visibleCount = 0;
            roleItems.forEach(item => {
                if (item.textContent.toLowerCase().includes(value)) {
                    item.style.display = 'block';
                    visibleCount++;
                } else {
                    item.style.display = 'none';
                }
            });
            dropdown.style.display = visibleCount ? 'block' : 'none';
            clearError(search);
        });

        // click to select
        roleItems.forEach(item => {
            item.addEventListener('click', function () {
                search.value = this.textContent.trim();
                search.style.borderColor = '#28a745';
                hideDropdown();
                clearError(search);
            });
        });

        // hide dropdown when clicking outside
        document.addEventListener('click', function (e) {
            if (!e.target.closest('#search') && !e.target.closest('#roleDropdown')) {
                hideDropdown();
            }
        });
    }

    // -------------------------
    // Form Submission
    // -------------------------
    const form = document.getElementById('modelform');

    // clear errors on input
    ['[name="name"]','[name="mobile"]','[name="email"]','#password','#search'].forEach(sel => {
        const el = document.querySelector(sel);
        if(el) el.addEventListener('input', e => clearError(e.target));
    });

    form.addEventListener('submit', function(e){
        e.preventDefault();

        const isNameValid     = validateName();
        const isMobileValid   = validateMobile();
        const isEmailValid    = validateEmail();
        const isPasswordValid = validatePassword();
        const isRoleValid     = validateRole();

        if (isNameValid && isMobileValid && isEmailValid && isPasswordValid && isRoleValid) {
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                html: 'User added successfully',
                width: '450px',
                heightAuto: false,
                customClass: {
                    popup: 'my-swal-popup',
                    title: 'swal-small-title',
                    htmlContainer: 'swal-small-text',
                    confirmButton: 'swal-small-btn'
                },
                confirmButtonColor: '#4a63ff',
                timer: 2000,
                timerProgressBar: true
            }).then(() => form.submit());
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Missing Information',
                html: 'Please fill all fields correctly!',
                width: '450px',
                heightAuto: false,
                customClass: {
                    popup: 'my-swal-popup',
                    title: 'swal-small-title',
                    htmlContainer: 'swal-small-text',
                    confirmButton: 'swal-small-btn'
                },
                confirmButtonColor: '#dc3545'
            });
        }
    });
});
</script>

 <?php  include 'footer.php'; ?>