﻿<!-- @php
$plan = App\Models\Plan::first();
@endphp -->

{{ Form::open(['url' => 'appraisal', 'method' => 'post', 'id' => 'ratingForm', 'class' => 'needs-validation', 'novalidate']) }}
<div class="modal-body">

    <div class="row">
        <div class="col-md-12">
            <div class="form-group">
                {{ Form::label('branch', __('Select Branch'), ['class' => 'col-form-label']) }}<x-required></x-required>
                <select name="brances" id="brances" class="form-control " required>
                    <option selected disabled value="">{{ __('Select Branch') }}</option>
                    @foreach ($brances as $value)
                    <option value="{{ $value->id }}">{{ $value->name }}</option>
                    @endforeach
                </select>
            </div>
        </div>

        <div class="col-md-12">
            <div class="form-group">
                {{ Form::label('department', __('Select Department'), ['class' => 'col-form-label']) }}
                <select name="department" id="department" class="form-control">
                    <option selected disabled value="">{{ __('Select Department') }}</option>
                </select>
            </div>
        </div>

        <!-- Multi-employee selection toggle -->
        <div class="col-md-12 mt-2">
            <div class="form-check">
                <input class="form-check-input" type="checkbox" id="multiEmployeeMode" name="multi_employee_mode">
                <label class="form-check-label" for="multiEmployeeMode">
                    {{ __('Apply same rating to multiple employees') }}
                </label>
            </div>
        </div>

        <!-- Single Employee Selection (default) -->
        <div class="col-md-6 mt-2" id="singleEmployeeDiv">
            <div class="form-group">
                {{ Form::label('employee', __('Employee'), ['class' => 'form-label']) }}<x-required></x-required>
                <div class="employee_div">
                    <select name="employee" id="employee" class="form-control">
                    </select>
                </div>
            </div>
        </div>

        <!-- Multiple Employee Selection (hidden by default) -->
        <div class="col-md-6 mt-2" id="multiEmployeeDiv" style="display: none;">
            <div class="form-group">
                {{ Form::label('employees', __('Select Employees'), ['class' => 'form-label']) }}<x-required></x-required>
                <div class="employee_multi_div">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center py-2">
                            <span class="text-sm font-weight-bold">{{ __('Available Employees') }}</span>
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="selectAllEmployees">
                                    {{ __('Select All') }}
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" id="clearAllEmployees">
                                    {{ __('Clear All') }}
                                </button>
                            </div>
                        </div>
                        <div class="card-body p-2" style="max-height: 200px; overflow-y: auto;">
                            <div id="employeeCheckboxList">
                                <div class="text-muted text-center py-3">
                                    <i class="fas fa-users"></i>
                                    <p class="mb-0">{{ __('Please select a branch first') }}</p>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer py-2">
                            <small class="text-muted">
                                <span id="selectedCount">0</span> {{ __('employee(s) selected') }}
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="form-group">
                {{ Form::label('appraisal_date', __('Select Month'), ['class' => 'col-form-label']) }}<x-required></x-required>
                {{ Form::month('appraisal_date', '', ['class' => 'form-control current_date', 'autocomplete' => 'off', 'required' => 'required', 'min' => date('Y-m')]) }}
            </div>
        </div>

        <div class="col-md-12" id="performanceCategoriesSection" style="display: none;">
            <div class="form-group">
                {{ Form::label('performance_types', __('Add Performance Categories'), ['class' => 'col-form-label']) }}
                <select id="performanceTypeSelect" class="form-control" style="display:none;">
                    <option value="">Select Performance Type</option>
                </select>

                <!-- Performance Evaluation Section -->
                <div id="starRatingsContainer" style="margin-top:30px"></div>
            </div>
        </div>

        <div class="col-md-12">
            <div class="form-group">
                {{ Form::label('remark', __('Remarks'), ['class' => 'col-form-label']) }}
                {{ Form::textarea('remark', null, ['class' => 'form-control', 'rows' => '3', 'placeholder' => __('Enter remark')]) }}
            </div>
        </div>
    </div>
    <div class="row" id="stares">
    </div>
</div>

<div class="modal-footer">
    <input type="button" value="{{ __('Cancel') }}" class="btn btn-light" data-bs-dismiss="modal">
    <input type="submit" id="submit" value="{{ __('Create') }}" class="btn btn-primary">
</div>
{{ Form::close() }}

<style>
    .employee-checkbox:checked+.form-check-label {
        background-color: #e3f2fd;
        border-radius: 4px;
        padding: 2px 8px;
    }

    .form-check-label {
        padding: 2px 8px;
        border-radius: 4px;
        transition: background-color 0.2s ease;
        cursor: pointer;
    }

    .form-check-label:hover {
        background-color: #f5f5f5;
    }

    #employeeCheckboxList .form-check {
        border-bottom: 1px solid #f0f0f0;
        padding-bottom: 8px;
        margin-bottom: 8px;
    }

    #employeeCheckboxList .form-check:last-child {
        border-bottom: none;
        margin-bottom: 0;
    }

    .card-header {
        background-color: #f8f9fa;
        border-bottom: 1px solid #dee2e6;
    }

    .btn-outline-primary:hover,
    .btn-outline-secondary:hover {
        transform: translateY(-1px);
        transition: all 0.2s ease;
    }

    /* Star Rating Styles */
    .rate {
        float: left;
        height: 46px;
        padding: 0 10px;
    }

    .rate:not(:checked)>input {
        position: absolute;
        top: -9999px;
    }

    .rate:not(:checked)>label {
        float: right;
        width: 1em;
        overflow: hidden;
        white-space: nowrap;
        cursor: pointer;
        font-size: 30px;
        color: #ccc;
    }

    .rate:not(:checked)>label:before {
        content: '★ ';
    }

    .rate>input:checked~label {
        color: #ffc700;
    }

    .rate:not(:checked)>label:hover,
    .rate:not(:checked)>label:hover~label {
        color: #deb217;
    }

    .rate>input:checked+label:hover,
    .rate>input:checked+label:hover~label,
    .rate>input:checked~label:hover,
    .rate>input:checked~label:hover~label,
    .rate>label:hover~input:checked~label {
        color: #c59b08;
    }

    /* Disabled stars for previous rating */
    fieldset[disabled] .rate:not(:checked)>label {
        cursor: default;
    }

    fieldset[disabled] .rate:not(:checked)>label:hover,
    fieldset[disabled] .rate:not(:checked)>label:hover~label {
        color: #ccc;
    }

    fieldset[disabled] .rate>input:checked~label {
        color: #ffc700;
    }
</style>

<script>
    // Toggle between single and multi-employee mode
    $('#multiEmployeeMode').change(function() {
        if ($(this).is(':checked')) {
            $('#singleEmployeeDiv').hide();
            $('#multiEmployeeDiv').show();
            $('#employee').removeAttr('required');
            // Clear performance section when switching modes
            clearPerformanceSection();
            hidePerformanceCategoriesSection();
        } else {
            $('#singleEmployeeDiv').show();
            $('#multiEmployeeDiv').hide();
            $('#employee').attr('required', 'required');
            // Clear selections when switching back
            $('.employee-checkbox').prop('checked', false);
            updateSelectedCount();
            clearPerformanceSection();
            hidePerformanceCategoriesSection();
        }
    });

    // Handle employee change for single selection
    $('#employee').change(function() {
        var emp_id = $('#employee').val();
        if (emp_id && !$('#multiEmployeeMode').is(':checked')) {
            loadEmployeePerformanceTypes(emp_id, false);
            showPerformanceCategoriesSection();
        } else {
            hidePerformanceCategoriesSection();
        }
    });

    // Handle employee checkbox changes for multiple selection
    $(document).on('change', '.employee-checkbox', function() {
        updateSelectedCount();
        var checkedEmployees = $('.employee-checkbox:checked');
        if (checkedEmployees.length > 0 && $('#multiEmployeeMode').is(':checked')) {
            // For multiple employees, we'll load performance types for the first selected employee as template
            loadEmployeePerformanceTypes(checkedEmployees.first().val(), true);
            showPerformanceCategoriesSection();
        } else if (checkedEmployees.length === 0 && $('#multiEmployeeMode').is(':checked')) {
            // Clear the rating section when no employees are selected
            clearPerformanceSection();
            hidePerformanceCategoriesSection();
        }
    });

    // Select all employees
    $('#selectAllEmployees').click(function() {
        $('.employee-checkbox').prop('checked', true);
        updateSelectedCount();
        var firstEmployee = $('.employee-checkbox:first');
        if (firstEmployee.length > 0) {
            loadEmployeePerformanceTypes(firstEmployee.val(), true);
            showPerformanceCategoriesSection();
        }
    });

    // Clear all employees
    $('#clearAllEmployees').click(function() {
        $('.employee-checkbox').prop('checked', false);
        updateSelectedCount();
        clearPerformanceSection();
        hidePerformanceCategoriesSection();
    });

    // Show/Hide Performance Categories Section
    function showPerformanceCategoriesSection() {
        $('#performanceCategoriesSection').show();
    }

    function hidePerformanceCategoriesSection() {
        $('#performanceCategoriesSection').hide();
    }

    // Update selected count
    function updateSelectedCount() {
        var count = $('.employee-checkbox:checked').length;
        $('#selectedCount').text(count);
    }

    function loadEmployeeStars(emp_id, isMultiple) {
        $.ajax({
            url: "{{ route('empByStar') }}",
            type: "post",
            data: {
                "employee": emp_id,
                "is_multiple": isMultiple,
                "_token": "{{ csrf_token() }}",
            },
            cache: false,
            success: function(data) {
                $('#stares').html(data.html);
            }
        });
    }

    // New function to load performance types (replaces the old loadEmployeeStars for new functionality)
    function loadEmployeePerformanceTypes(emp_id, isMultiple) {
        $.ajax({
            url: "{{ route('empByStarModified') }}",
            type: "post",
            data: {
                "employee": emp_id,
                "is_multiple": isMultiple,
                "_token": "{{ csrf_token() }}",
            },
            cache: false,
            success: function(data) {
                const select = $('#performanceTypeSelect');
                select.empty().append('<option value="">Select Performance Type</option>');

                if (data.performance_types.length) {
                    select.show();
                    data.performance_types.forEach(pt => {
                        select.append(`<option value="${pt.id}">${pt.name}</option>`);
                    });
                } else {
                    select.hide();
                }

                // Store data in global vars
                window.performanceTypes = data.performance_types;
                window.ratings = data.ratings;
                window.selectedPerformanceTypes = new Set(); // Track selected types
                $('#starRatingsContainer').empty();
            }
        });
    }

    // Clear performance section
    function clearPerformanceSection() {
        $('#performanceTypeSelect').hide().empty().append('<option value="">Select Performance Type</option>');
        $('#starRatingsContainer').empty();
        window.selectedPerformanceTypes = new Set();
        window.performanceTypes = [];
        window.ratings = {};
    }

    // Handle branch change
    $('#brances').on('change', function() {
        var branch_id = this.value;

        // Clear performance section when branch changes
        clearPerformanceSection();
        hidePerformanceCategoriesSection();

        // 1. Fetch and show employees by branch
        fetchEmployeesByBranch(branch_id);

        // 2. Fetch and populate departments
        $.ajax({
            url: "{{ route('getDepartmentByBranch') }}",
            type: "post",
            data: {
                branch_id: branch_id,
                _token: "{{ csrf_token() }}"
            },
            cache: false,
            success: function(response) {
                $('#department').html('<option value="">-- All Departments (by Branch) --</option>');

                if (response.exists && response.departments.length > 0) {
                    $.each(response.departments, function(key, value) {
                        $('#department').append('<option value="' + value.id + '">' + value.name + '</option>');
                    });
                    $('#department').prop('disabled', false);
                } else {
                    $('#department').append('<option disabled>No Departments Available</option>');
                    $('#department').prop('disabled', true);
                }

                // Auto-reset department select
                $('#department').val('');
            }
        });
    });

    // Handle department change
    $('#department').on('change', function() {
        var department_id = this.value;
        var branch_id = $('#brances').val();

        // Clear performance section when department changes
        clearPerformanceSection();
        hidePerformanceCategoriesSection();

        if (department_id === '') {
            fetchEmployeesByBranch(branch_id); // revert to all employees in branch
        } else {
            $.ajax({
                url: "{{ route('getEmployeesByDepartment') }}",
                type: "post",
                data: {
                    department_id: department_id,
                    _token: "{{ csrf_token() }}"
                },
                cache: false,
                success: function(data) {
                    populateEmployees(data);
                }
            });
        }
    });

    // Helper function to fetch employees by branch
    function fetchEmployeesByBranch(branch_id) {
        $.ajax({
            url: "{{ route('getemployee') }}",
            type: "post",
            data: {
                branch_id: branch_id,
                _token: "{{ csrf_token() }}"
            },
            cache: false,
            success: function(data) {
                populateEmployees(data.employee);
            }
        });
    }

    // Helper function to populate employees in both dropdowns
    function populateEmployees(employeeList) {
        // Update single employee dropdown
        $('#employee').html('<option value="">Select Employee</option>');

        // Update checkbox list for multiple employees
        var checkboxHtml = '';

        if (employeeList && employeeList.length > 0) {
            $.each(employeeList, function(key, value) {
                $("#employee").append('<option value="' + value.id + '">' + value.name + '</option>');

                checkboxHtml += '<div class="form-check mb-2">';
                checkboxHtml += '<input class="form-check-input employee-checkbox" type="checkbox" ';
                checkboxHtml += 'name="employees[]" value="' + value.id + '" id="emp_' + value.id + '">';
                checkboxHtml += '<label class="form-check-label d-flex justify-content-between align-items-center w-100" for="emp_' + value.id + '">';
                checkboxHtml += '<span>' + value.name + '</span>';
                if (value.employee_id) {
                    checkboxHtml += '<small class="text-muted">(' + value.employee_id + ')</small>';
                }
                checkboxHtml += '</label>';
                checkboxHtml += '</div>';
            });
        } else {
            checkboxHtml = '<div class="text-muted text-center py-3">';
            checkboxHtml += '<i class="fas fa-exclamation-circle"></i>';
            checkboxHtml += '<p class="mb-0">{{ __("No employees found") }}</p>';
            checkboxHtml += '</div>';
        }

        $('#employeeCheckboxList').html(checkboxHtml);
        updateSelectedCount();
        $('#submit').prop('disabled', false);
    }

    // Performance type selection logic
    $('#performanceTypeSelect').change(function() {
        const selectedValue = $(this).val();

        // If nothing is selected or empty value, return
        if (!selectedValue || selectedValue === '') {
            return;
        }

        // Check if this performance type is already selected
        if (window.selectedPerformanceTypes && window.selectedPerformanceTypes.has(selectedValue)) {
            // Reset the select to show "Select Performance Type"
            $(this).val('');
            return;
        }

        // Add to selected types
        if (!window.selectedPerformanceTypes) {
            window.selectedPerformanceTypes = new Set();
        }
        window.selectedPerformanceTypes.add(selectedValue);

        // Reset the select to allow selecting another type
        $(this).val('');

        // Find the selected performance type
        const selectedType = window.performanceTypes ? window.performanceTypes.find(pt => pt.id == selectedValue) : null;
        const ratings = window.ratings || {};

        if (selectedType) {
            let html = `
            <div class="performance-type-section card mb-4" data-type-id="${selectedValue}">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">${selectedType.name}</h6>
                    <button type="button" class="btn btn-sm btn-danger remove-performance-type" data-type-id="${selectedValue}">
                        <i class="fas fa-times"></i> Remove
                    </button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th style="width: 40%;">Performance Criteria</th>
                                    <th style="width: 30%;" class="text-center">Previous Rating</th>
                                    <th style="width: 30%;" class="text-center">Current Rating</th>
                                </tr>
                            </thead>
                            <tbody>
        `;

            selectedType.types.forEach(type => {
                html += `
                <tr>
                    <td class="align-middle">
                        <strong>${type.name}</strong>
                    </td>
                    <td class="text-center align-middle">
                        <fieldset class="rate" disabled>
                            ${[5, 4, 3, 2, 1].map(rating => `
                                <input type="radio" id="prev-${rating}-${type.id}" name="prev_ratings[${type.id}]" value="${rating}" ${ratings[type.id] == rating ? 'checked' : ''} disabled>
                                <label class="full" for="prev-${rating}-${type.id}" title="${rating} stars"></label>
                            `).join('')}
                        </fieldset>
                    </td>
                    <td class="text-center align-middle">
                        <fieldset class="rate">
                            ${[5, 4, 3, 2, 1].map(rating => `
                                <input type="radio" id="curr-${rating}-${type.id}" name="rating[${type.id}]" value="${rating}" required>
                                <label class="full" for="curr-${rating}-${type.id}" title="${rating} stars"></label>
                            `).join('')}
                        </fieldset>
                    </td>
                </tr>
            `;
            });

            html += `
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        `;

            // Append the new performance type section
            $('#starRatingsContainer').append(html);
        }
    });

    // Handle remove performance type
    $(document).on('click', '.remove-performance-type', function() {
        const typeId = $(this).data('type-id');

        // Remove from selected types
        if (window.selectedPerformanceTypes) {
            window.selectedPerformanceTypes.delete(typeId.toString());
        }

        // Remove the section from DOM
        $(`.performance-type-section[data-type-id="${typeId}"]`).remove();
    });

    // Form validation
    $('#ratingForm').on('submit', function(e) {
        var isMultiMode = $('#multiEmployeeMode').is(':checked');

        if (isMultiMode) {
            var selectedEmployees = $('.employee-checkbox:checked');
            if (selectedEmployees.length === 0) {
                e.preventDefault();
                alert('Please select at least one employee.');
                return false;
            }
        } else {
            var selectedEmployee = $('#employee').val();
            if (!selectedEmployee) {
                e.preventDefault();
                alert('Please select an employee.');
                return false;
            }
        }
    });
</scrip