
<?php $__env->startSection('title', 'Edit Employee'); ?>
<?php $__env->startPush('plugin-styles'); ?>
    <style>
        .select2-container--bootstrap-5{
            border: 1px solid #ddd !important;
            border-radius: 8px !important;
            width: 100% !important;
        }
        .select2-selection__rendered{
            padding-top: 1.8% !important;
        }
        .select2-container .select2-selection--single{
            height: 45px !important;
        }
    </style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="page-content">
    <div class="row">
        <div class="col-md-12 grid-margin stretch-card">
            <div class="card">
                <div class="card-body">
                    <h6 class="card-title">Edit Employee</h6>
                    <p class="text-muted">Update employee information</p>

                    <?php if($errors->any()): ?>
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <li><?php echo e($error); ?></li>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </ul>
                        </div>
                    <?php endif; ?>

                    <?php echo $__env->make('employees.form', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>
<?php $__env->startPush('plugin-scripts'); ?>

<script>
    document.addEventListener('DOMContentLoaded', function() {

        // == DECLARE ALL VARS FIRST ==
        const allowLoginCheckbox = document.getElementById('allow_login');
        const shopSelection      = document.getElementById('shop_selection');
        const salaryFields       = document.getElementById('salary_fields');
        const dailyWageField     = document.getElementById('daily_wage_field');
        const contractAmountField = document.getElementById('contract_amount_field');
        const loginCredentials   = document.getElementById('login_credentials');
        const incentivesSection  = document.getElementById('incentives_section');
        const emailField         = document.getElementById('email');

        // Initialize data attributes early
        allowLoginCheckbox.dataset.autoChecked = 'false';
        allowLoginCheckbox.dataset.userChecked = 'false';

        function makeLoginFieldsRequired(required) {
            document.getElementById('username').required          = required;
            document.getElementById('user_role').required         = required;
            document.getElementById('password').required          = required;
            document.getElementById('password_confirmation').required = required;
        }

        // == SELECT2 INITS ==
        $('#gender').select2({ theme: 'bootstrap-5', placeholder: 'Select Gender', allowClear: true });
        $('#user_role').select2({ theme: 'bootstrap-5', placeholder: 'Select Role', allowClear: true });
        $('#shop_id').select2({ theme: 'bootstrap-5', placeholder: 'Select Shop', allowClear: true });
        $('#work_category').select2({ theme: 'bootstrap-5', placeholder: 'Select Work Category', allowClear: true });

        // == EMPLOYEE TYPE ==
        $('#employee_type').select2({
            theme: 'bootstrap-5',
            placeholder: 'Select Employee Type',
            allowClear: false
        }).on('change', function() {
            const value = this.value;

            document.getElementById('work_category_field').style.display =
                (value === 'worker' || value === 'employee') ? 'block' : 'none';

            if (value === 'shop_manager' || value === 'shop_employee') {
                shopSelection.style.display = 'block';
                document.getElementById('shop_id').required = true;

                if (value === 'shop_manager') {
                    allowLoginCheckbox.checked = true;
                    allowLoginCheckbox.dataset.autoChecked = 'true';
                    loginCredentials.style.display = 'block';
                    makeLoginFieldsRequired(true);
                    emailField.required = true;
                }
            } else {
                shopSelection.style.display = 'none';
                document.getElementById('shop_id').required = false;

                if (allowLoginCheckbox.dataset.autoChecked === 'true') {
                    allowLoginCheckbox.checked = false;
                    allowLoginCheckbox.dataset.autoChecked = 'false';
                    loginCredentials.style.display = 'none';
                    makeLoginFieldsRequired(false);
                    emailField.required = false;
                }
            }
        }).trigger('change');

        // == WAGE TYPE ==
        $('#wage_type').select2({
            theme: 'bootstrap-5',
            placeholder: 'Select Wage Type',
            allowClear: false
        }).on('change', function() {
            const value = this.value;

            salaryFields.style.display      = 'none';
            dailyWageField.style.display    = 'none';
            contractAmountField.style.display = 'none';
            incentivesSection.style.display = 'none';

            document.getElementById('basic_salary').required      = false;
            document.getElementById('working_hours').required     = false;
            document.getElementById('holidays_per_week').required = false;
            document.getElementById('daily_wage').required        = false;
            document.getElementById('contract_amount').required   = false;

            if (value === 'salary') {
                salaryFields.style.display      = 'block';
                incentivesSection.style.display = 'block';
                document.getElementById('basic_salary').required      = true;
                document.getElementById('working_hours').required     = true;
                document.getElementById('holidays_per_week').required = true;
            } else if (value === 'daily_wager') {
                dailyWageField.style.display = 'block';
                document.getElementById('daily_wage').required = true;
            } else if (value === 'contract') {
                contractAmountField.style.display = 'block';
                document.getElementById('contract_amount').required = true;
            }
        }).trigger('change');

        // == ALLOW LOGIN ==
        allowLoginCheckbox.addEventListener('change', function() {
            if (this.checked) {
                loginCredentials.style.display = 'block';
                makeLoginFieldsRequired(true);
                emailField.required = true;
                if (this.dataset.autoChecked !== 'true') {
                    this.dataset.userChecked = 'true';
                }
            } else {
                loginCredentials.style.display = 'none';
                makeLoginFieldsRequired(false);
                emailField.required = false;
                this.dataset.userChecked = 'false';
            }
        });
        allowLoginCheckbox.dispatchEvent(new Event('change'));

        // == INCENTIVES ==
        let incentiveRowCount = 0;

        <?php if(old('incentives')): ?>
            const oldIncentives = <?php echo json_encode(old('incentives'), 15, 512) ?>;
            const tbody = document.querySelector('#incentives_table tbody');
            tbody.innerHTML = '';
            oldIncentives.forEach(function(incentive, index) {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${index + 1}</td>
                    <td><input type="text" name="incentives[${index}][name]" class="form-control" value="${incentive.name || ''}" placeholder="Incentive name"></td>
                    <td><input type="number" name="incentives[${index}][amount]" class="form-control" value="${incentive.amount || ''}" placeholder="Amount" step="0.01" min="0"></td>
                    <td><button type="button" class="btn btn-sm btn-danger remove-incentive">Delete</button></td>
                `;
                tbody.appendChild(row);
                incentiveRowCount++;
            });
        <?php elseif($isEdit && isset($incentives) && $incentives->count() > 0): ?>
            const existingIncentives = <?php echo json_encode($incentives, 15, 512) ?>;
            const tbody = document.querySelector('#incentives_table tbody');
            existingIncentives.forEach(function(incentive, index) {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${index + 1}</td>
                    <td><input type="text" name="incentives[${index}][name]" class="form-control" value="${incentive.name || ''}" placeholder="Incentive name"></td>
                    <td><input type="number" name="incentives[${index}][amount]" class="form-control" value="${incentive.amount || ''}" placeholder="Amount" step="0.01" min="0"></td>
                    <td><button type="button" class="btn btn-sm btn-danger remove-incentive">Delete</button></td>
                `;
                tbody.appendChild(row);
                incentiveRowCount++;
            });
        <?php endif; ?>

        document.getElementById('add_incentive').addEventListener('click', function() {
            const tbody = document.querySelector('#incentives_table tbody');
            const newRow = document.createElement('tr');
            newRow.innerHTML = `
                <td>${incentiveRowCount + 1}</td>
                <td><input type="text" name="incentives[${incentiveRowCount}][name]" class="form-control" placeholder="Incentive name"></td>
                <td><input type="number" name="incentives[${incentiveRowCount}][amount]" class="form-control" placeholder="Amount" step="0.01" min="0"></td>
                <td><button type="button" class="btn btn-sm btn-danger remove-incentive">Delete</button></td>
            `;
            tbody.appendChild(newRow);
            incentiveRowCount++;
        });

        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('remove-incentive')) {
                e.target.closest('tr').remove();
                document.querySelectorAll('#incentives_table tbody tr').forEach((row, index) => {
                    row.cells[0].textContent = index + 1;
                });
            }
        });

        // == LOAD SHOPS ==
        function loadShops() {
            const selectedShopId = <?php echo json_encode(old('shop_id', $isEdit ? $employee->shop_id : ''), 512) ?>;
            fetch('/api/shops')
                .then(response => response.json())
                .then(data => {
                    const shopSelect = document.getElementById('shop_id');
                    shopSelect.innerHTML = '<option value="">Select Shop</option>';
                    data.forEach(shop => {
                        const option = document.createElement('option');
                        option.value = shop.id;
                        option.textContent = shop.name;
                        if (selectedShopId && shop.id == selectedShopId) {
                            option.selected = true;
                        }
                        shopSelect.appendChild(option);
                    });
                    if ($('#shop_id').data('select2')) {
                        $('#shop_id').trigger('change');
                    }
                })
                .catch(error => console.error('Error loading shops:', error));
        }

        loadShops();

    });
</script>







<?php $__env->stopPush(); ?>


<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\habibcables-ERP\resources\views\employees\edit.blade.php ENDPATH**/ ?>