﻿{{ Form::open([
    'route' => 'appraisal_reviews.store',
    'method' => 'POST',
    'class' => 'needs-validation',
    'novalidate',
    'id' => 'appraisal-review-form'
]) }}

<div class="modal-body">
    <div class="row">
        <div class="col-12">
            <div class="form-group">
                {{ Form::label('appraisal_date', __('Appraisal Date'), ['class' => 'form-label']) }}
                <div class="form-icon-user">
                    {{ Form::date('appraisal_date', \Carbon\Carbon::now()->format('Y-m-d'), [
    'class' => 'form-control',
    'id' => 'appraisal_date',
    'required' => true,
    'placeholder' => __('Select Appraisal Date')
]) }}
                </div>
            </div>


        </div>
        {{-- Employee --}}
        <div class="col-12">
            <div class="form-group">
                {{ Form::label('employee_id', __('Select Employee'), ['class' => 'form-label']) }}
                <div class="form-icon-user">
                    {{ Form::select('employee_id', $employees, null, [
    'class' => 'form-control select2',
    'id' => 'employee-select',
    'placeholder' => __('Choose Employee'),
    'required' => true
]) }}
                </div>
            </div>
        </div>


        {{-- Rating Type --}}
        <div class="col-12">
            <div class="form-group">
                {{ Form::label('rating_type_id', __('Rating Type'), ['class' => 'form-label']) }}
                <div class="form-icon-user">
                    {{ Form::select('rating_type_id', $ratingTypes, null, [
    'class' => 'form-control',
    'placeholder' => __('Choose Rating Type'),
    'required' => true
]) }}
                </div>
            </div>
        </div>

        {{-- Review Type --}}
        <div class="col-12 mb-3">
            <div class="form-group">
                {{ Form::label('review_type', __('Review Type'), ['class' => 'form-label']) }}
                {{ Form::select('review_type', [
    '90' => '90 Degree (Manager Only)',
    '180' => '180 Degree (Manager + Self)',
    '360' => '360 Degree (Manager + Self + Peers)'
], null, ['class' => 'form-control', 'required' => true]) }}
            </div>
        </div>

        {{-- Goals (multi-select) --}}
        <div class="col-12">
            <div class="form-group">
                {{ Form::label('goal_ids', __('Select Goals'), ['class' => 'form-label']) }}
                <div class="goal-select-container">
                    <div class="selected-goals-display" id="selected-goals-display" style="display: none;">
                        <div class="selected-goals-list" id="selected-goals-list"></div>
                    </div>
                    <div class="dropdown">
                        <button class="btn btn-outline-secondary dropdown-toggle w-100 text-start" type="button"
                            id="goal-dropdown-btn" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fas fa-target me-2"></i>{{ __('Select Goals') }}
                        </button>
                        <ul class="dropdown-menu w-100" id="goal-dropdown-menu"
                            style="max-height: 300px; overflow-y: auto;">
                            <li><span class="dropdown-item-text text-muted">{{ __('No goals available') }}</span></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label for="competencySelect">Select Competencies</label>
            <select class="form-control select2" id="competencySelect" name="competencies[]" multiple>
                @foreach ($competencies as $id => $name)
                    <option value="{{ $id }}">{{ $name }}</option>
                @endforeach
            </select>
        </div>

        <div id="selectedCompetencies" class="mt-2">
            <!-- Tags will appear here -->
        </div>


        {{-- Allow goal-update toggle --}}
        <div class="col-12 mt-2 mb-3">
            {{ Form::hidden('allow_goal_update', 0) }}
            <div class="form-check custom-checkbox">
                {{ Form::checkbox('allow_goal_update', 1, false, [
    'class' => 'form-check-input custom-checkbox-input',
    'id' => 'allow_goal_update'
]) }}
                <span class="checkmark"></span>
                <span class="label-text">{{ __('Allow employee to update goals during appraisal') }}</span>
            </div>
        </div>

    </div>
</div>

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

{{ Form::close() }}

<style>
    .goal-select-container {
        position: relative;
    }

    .selected-goals-display {
        background: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 0.375rem;
        padding: 0.5rem;
        margin-bottom: 0.5rem;
        min-height: 2.5rem;
    }

    .selected-goals-list {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
    }

    .goal-tag {
        background: #007bff;
        color: white;
        padding: 0.25rem 0.5rem;
        border-radius: 1rem;
        font-size: 0.875rem;
        display: flex;
        align-items: center;
        gap: 0.25rem;
    }

    .goal-tag .remove-goal {
        background: rgba(255, 255, 255, 0.3);
        border: none;
        border-radius: 50%;
        width: 1.2rem;
        height: 1.2rem;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        font-size: 0.75rem;
        color: white;
    }

    .goal-tag .remove-goal:hover {
        background: rgba(255, 255, 255, 0.5);
    }

    .dropdown {
        border: 1px solid;
        border-radius: 1rem;
    }

    .dropdown-item:hover {
        background-color: #f8f9fa;
    }

    .dropdown-item.selected {
        background-color: #e3f2fd;
        color: #1976d2;
    }

    .dropdown-item.selected::after {
        content: "✓";
        float: right;
        color: #1976d2;
        font-weight: bold;
    }
</style>

<script>
    $(document).ready(function() {
        $('.select2').select2({
            placeholder: "Choose Competencies",
            allowClear: true
        });
    });

    /* ------------------------------------------------------------------
    Dynamic goal loading & table builder
    ------------------------------------------------------------------ */
    const empSelect = document.getElementById('employee-select');
    const goalDropdownBtn = document.getElementById('goal-dropdown-btn');
    const goalDropdownMenu = document.getElementById('goal-dropdown-menu');
    const selectedGoalsDisplay = document.getElementById('selected-goals-display');
    const selectedGoalsList = document.getElementById('selected-goals-list');

    let availableGoals = [];
    let selectedGoals = new Map(); // goalId -> goalData

    /* 1. Load goals when employee changes */
    empSelect.addEventListener('change', async () => {
        // Reset state
        selectedGoals.clear();
        availableGoals = [];
        updateSelectedGoalsDisplay();
        updateDropdownButton();

        goalDropdownMenu.innerHTML =
        `<li><span class="dropdown-item-text text-muted">{!! json_encode(__('Loading…')) !!}</span></li>`;

        const id = empSelect.value;
        if (!id) {
            goalDropdownMenu.innerHTML =
            `<li><span class="dropdown-item-text text-muted">{!! json_encode(__('No goals available')) !!}</span></li>`;
            return;
        }

        try {
            const res = await fetch(`/appraisal_reviews/goals-for-employee/${id}`);
            const data = await res.json();

            availableGoals = data;
            updateGoalDropdown();

        } catch (e) {
            console.error(e);
            goalDropdownMenu.innerHTML =
            `<li><span class="dropdown-item-text text-danger">{!! json_encode(__('Error loading goals')) !!}</span></li>
            `;
        }
    });

    /* 2. Update goal dropdown */
    function updateGoalDropdown() {
        goalDropdownMenu.innerHTML = '';

        if (!availableGoals.length) {
            goalDropdownMenu.innerHTML =
            `<li><span class="dropdown-item-text text-muted">{!! json_encode(__('No goals available')) !!}</span></li>`;
            return;
        }

        availableGoals.forEach(goal => {
            const li = document.createElement('li');
            const a = document.createElement('a');
            const formattedDate = goal.due_date ?
                new Intl.DateTimeFormat('en-GB', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric'
                }).format(new Date(goal.due_date)) :
                '—';
            a.className = `dropdown-item ${selectedGoals.has(goal.id.toString()) ? 'selected' : ''}`;
            a.href = '#';
            a.textContent = `${goal.title} (${formattedDate ?? 'No due date'})`;
            a.onclick = (e) => {
                e.preventDefault();
                toggleGoalSelection(goal);
            };
            li.appendChild(a);
            goalDropdownMenu.appendChild(li);
        });
    }

    /* 3. Toggle goal selection */
    function toggleGoalSelection(goal) {
        const goalId = goal.id.toString();

        if (selectedGoals.has(goalId)) {
            // Remove goal
            selectedGoals.delete(goalId);
        } else {
            // Add goal
            selectedGoals.set(goalId, goal);
        }

        updateSelectedGoalsDisplay();
        updateGoalDropdown();
        updateDropdownButton();
    }

    /* 4. Update selected goals display */
    function updateSelectedGoalsDisplay() {
        selectedGoalsList.innerHTML = '';

        if (selectedGoals.size === 0) {
            selectedGoalsDisplay.style.display = 'none';
            return;
        }

        selectedGoalsDisplay.style.display = 'block';

        selectedGoals.forEach((goal, goalId) => {
            const tag = document.createElement('div');
            tag.className = 'goal-tag';
            tag.innerHTML = `
                <span>${goal.title}</span>
                <button type="button" class="remove-goal" onclick="removeGoal('${goalId}')">×</button>
                <input type="hidden" name="goal_ids[]" value="${goalId}">
            `;
            selectedGoalsList.appendChild(tag);
        });
    }

    /* 5. Update dropdown button text */
    function updateDropdownButton() {
        const count = selectedGoals.size;
        if (count === 0) {
            goalDropdownBtn.innerHTML = `<i class="fas fa-target me-2"></i>Select Goals`;
        } else {
            goalDropdownBtn.innerHTML = `<i class="fas fa-target me-2"></i>${count} Goals selected - Select More`;
        }
    }

    /* 6. Remove goal function for tag buttons */
    function removeGoal(goalId) {
        selectedGoals.delete(goalId);
        updateSelectedGoalsDisplay();
        updateGoalDropdown();
        updateDropdownButton();
    }

    document.addEventListener('DOMContentLoaded', function() {
        const competencySelect = document.getElementById('competencySelect');
        const selectedCompetencies = document.getElementById('selectedCompetencies');

        competencySelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const competencyId = selectedOption.value;
            const competencyName = selectedOption.text;

            // Check if already selected
            if (document.getElementById('competency-tag-' + competencyId)) return;

            const tag = document.createElement('span');
            tag.classList.add('badge', 'badge-primary', 'mr-1', 'mb-1');
            tag.id = 'competency-tag-' + competencyId;
            tag.innerHTML = `
                ${competencyName}
                <button type="button" class="ml-1 close text-white" aria-label="Remove" onclick="this.parentElement.remove(); document.getElementById('competency-input-${competencyId}').remove();">
                    <span aria-hidden="true">&times;</span>
                </button>
            `;

            const hiddenInput = document.createElement('input');
            hiddenInput.type = 'hidden';
            hiddenInput.name = 'competencies[]';
            hiddenInput.value = competencyId;
            hiddenInput.id = 'competency-input-' + competencyId;

            selectedCompetencies.appendChild(tag);
            selectedCompetencies.appendChild(hiddenInput);
        });
    });
</scrip