@extends('layouts.app')

@section('title', '연차촉진 관리')

@section('content')
<div class="px-4 py-6">
    {{-- 페이지 헤더 --}}
    <div class="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-4 mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">연차촉진 관리</h1>
            <p class="text-sm text-gray-500 mt-1">연차유급휴가 사용촉진 통지서를 일괄 발송하고 현황을 관리합니다.</p>
        </div>
        <div class="flex flex-wrap items-center gap-2 sm:gap-3">
            {{-- 연도 선택 --}}
            <select id="year-select" onchange="changeYear(this.value)"
                    class="px-3 py-2 border border-gray-300 rounded-lg text-sm bg-white">
                @for ($y = now()->year; $y >= now()->year - 2; $y--)
                    <option value="{{ $y }}" {{ $year == $y ? 'selected' : '' }}>{{ $y }}년</option>
                @endfor
            </select>
            <button type="button" onclick="openBulkModal('1st')"
                    class="inline-flex items-center gap-2 px-4 py-2 bg-orange-500 hover:bg-orange-600 text-white text-sm font-medium rounded-lg transition-colors">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                </svg>
                1차 통지 발송
            </button>
            <button type="button" onclick="openBulkModal('2nd')"
                    class="inline-flex items-center gap-2 px-4 py-2 bg-red-500 hover:bg-red-600 text-white text-sm font-medium rounded-lg transition-colors">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                </svg>
                2차 통지 발송
            </button>
        </div>
    </div>

    {{-- 통계 카드 --}}
    <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
            <div class="text-xs text-gray-500 mb-1">전체 대상</div>
            <div class="text-2xl font-bold text-gray-800">{{ $stats['total'] }}명</div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
            <div class="text-xs text-gray-500 mb-1">미발송</div>
            <div class="text-2xl font-bold text-gray-500">{{ $stats['not_sent'] }}명</div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-orange-100 p-4">
            <div class="text-xs text-orange-600 mb-1">1차 발송</div>
            <div class="text-2xl font-bold text-orange-600">{{ $stats['first_sent'] }}명</div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-green-100 p-4">
            <div class="text-xs text-green-600 mb-1">2차 발송 (완료)</div>
            <div class="text-2xl font-bold text-green-600">{{ $stats['completed'] }}명</div>
        </div>
    </div>

    {{-- 대상자 테이블 --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="px-4 py-3 border-b border-gray-100 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <label class="flex items-center gap-2 text-sm text-gray-600 cursor-pointer">
                    <input type="checkbox" id="select-all" onchange="toggleSelectAll(this)" class="rounded border-gray-300 text-blue-600">
                    전체 선택
                </label>
                <span id="selected-count" class="text-sm text-blue-600 font-medium hidden">0명 선택됨</span>
            </div>
            <div class="flex items-center gap-2">
                <select id="status-filter" onchange="filterByStatus(this.value)" class="px-2 py-1 text-xs border border-gray-300 rounded-lg bg-white">
                    <option value="">전체 상태</option>
                    <option value="not_sent">미발송</option>
                    <option value="first_sent">1차 발송</option>
                    <option value="completed">완료 (2차 발송)</option>
                </select>
            </div>
        </div>

        <x-table-swipe>
            <table class="min-w-full divide-y divide-gray-200 text-sm">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-3 py-2 text-center" style="width: 40px;">
                            <span class="sr-only">선택</span>
                        </th>
                        <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">사원명</th>
                        <th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">부서</th>
                        <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">발생일수</th>
                        <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">사용일수</th>
                        <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">잔여일수</th>
                        <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">사용률</th>
                        <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">상태</th>
                        <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">1차 통지</th>
                        <th class="px-3 py-2 text-center text-xs font-medium text-gray-500 uppercase">2차 통지</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    @forelse ($candidates as $candidate)
                        @php
                            $remaining = $candidate->total_days - $candidate->used_days;
                            $rate = $candidate->total_days > 0 ? round($candidate->used_days / $candidate->total_days * 100) : 0;
                        @endphp
                        <tr class="hover:bg-gray-50 candidate-row" data-status="{{ $candidate->promotion_status }}" data-user-id="{{ $candidate->user_id }}">
                            <td class="px-3 py-2 text-center">
                                <input type="checkbox" name="employee_ids[]" value="{{ $candidate->user_id }}"
                                       class="employee-checkbox rounded border-gray-300 text-blue-600"
                                       onchange="updateSelectedCount()">
                            </td>
                            <td class="px-3 py-2 font-medium text-gray-800">{{ $candidate->employee?->display_name ?? '-' }}</td>
                            <td class="px-3 py-2 text-gray-600">{{ $candidate->employee?->department?->name ?? '-' }}</td>
                            <td class="px-3 py-2 text-center">{{ $candidate->total_days }}일</td>
                            <td class="px-3 py-2 text-center">{{ $candidate->used_days }}일</td>
                            <td class="px-3 py-2 text-center font-bold {{ $remaining >= 5 ? 'text-red-600' : 'text-orange-600' }}">{{ $remaining }}일</td>
                            <td class="px-3 py-2 text-center">
                                <div class="flex items-center justify-center gap-1">
                                    <div class="w-12 h-1.5 bg-gray-200 rounded-full overflow-hidden">
                                        <div class="h-full rounded-full {{ $rate >= 80 ? 'bg-green-500' : ($rate >= 50 ? 'bg-yellow-500' : 'bg-red-500') }}" style="width: {{ $rate }}%"></div>
                                    </div>
                                    <span class="text-xs text-gray-500">{{ $rate }}%</span>
                                </div>
                            </td>
                            <td class="px-3 py-2 text-center">
                                @switch($candidate->promotion_status)
                                    @case('not_sent')
                                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">미발송</span>
                                        @break
                                    @case('first_sent')
                                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-orange-100 text-orange-700">1차 발송</span>
                                        @break
                                    @case('completed')
                                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700">완료</span>
                                        @break
                                @endswitch
                            </td>
                            <td class="px-3 py-2 text-center text-xs">
                                @if ($candidate->first_notice)
                                    <a href="{{ route('approvals.show', $candidate->first_notice->id) }}" class="text-blue-600 hover:underline">
                                        {{ $candidate->first_notice->created_at->format('m/d') }}
                                    </a>
                                @else
                                    <span class="text-gray-400">-</span>
                                @endif
                            </td>
                            <td class="px-3 py-2 text-center text-xs">
                                @if ($candidate->second_notice)
                                    <a href="{{ route('approvals.show', $candidate->second_notice->id) }}" class="text-blue-600 hover:underline">
                                        {{ $candidate->second_notice->created_at->format('m/d') }}
                                    </a>
                                @else
                                    <span class="text-gray-400">-</span>
                                @endif
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="10" class="px-4 py-12 text-center text-gray-400">
                                잔여 연차가 있는 대상자가 없습니다.
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </x-table-swipe>
    </div>
</div>

{{-- 일괄 발송 모달 --}}
<div id="bulk-modal" class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/50" onclick="closeBulkModal()"></div>
    <div class="absolute inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl shadow-xl w-full max-w-md relative" onclick="event.stopPropagation()">
            <div class="px-6 py-4 border-b border-gray-100">
                <h3 id="bulk-modal-title" class="text-lg font-bold text-gray-800">연차촉진 통지서 발송</h3>
            </div>
            <div class="px-6 py-4 space-y-4">
                <div>
                    <p class="text-sm text-gray-600 mb-2">
                        선택된 <span id="bulk-count" class="font-bold text-blue-600">0</span>명에게 통지서를 발송합니다.
                    </p>
                </div>

                {{-- 1차 전용: 제출기한 --}}
                <div id="deadline-section" class="hidden">
                    <label class="block text-sm font-medium text-gray-700 mb-1">사용시기 제출 기한</label>
                    <input type="date" id="bulk-deadline" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm">
                    <p class="text-xs text-gray-500 mt-1">직원이 연차 사용 시기를 제출해야 하는 기한</p>
                </div>

                {{-- 2차 전용: 지정 휴가일 (선택) --}}
                <div id="dates-section" class="hidden">
                    <label class="block text-sm font-medium text-gray-700 mb-1">지정 휴가일 (선택)</label>
                    <p class="text-xs text-gray-500 mb-2">비워두면 개별 결재 문서에서 지정할 수 있습니다.</p>
                    <div id="designated-dates-container">
                        <div class="flex items-center gap-2 mb-2">
                            <input type="date" class="designated-date-input flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm">
                            <button type="button" onclick="addDesignatedDate()" class="px-2 py-2 text-blue-600 hover:text-blue-800">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>

                <div class="bg-amber-50 border border-amber-200 rounded-lg p-3">
                    <p class="text-xs text-amber-800">
                        <strong>안내:</strong> 통지서는 결재 문서로 생성되어 자동 상신됩니다.
                        결재 승인 후 직원에게 통지됩니다.
                    </p>
                </div>
            </div>
            <div class="px-6 py-4 border-t border-gray-100 flex justify-end gap-2">
                <button type="button" onclick="closeBulkModal()"
                        class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg text-sm hover:bg-gray-50">
                    취소
                </button>
                <button type="button" onclick="submitBulkNotice()" id="bulk-submit-btn"
                        class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm hover:bg-blue-700">
                    발송
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
    let currentNoticeType = '1st';

    function changeYear(year) {
        window.location.href = '{{ route("hr.leave-promotions.index") }}?year=' + year;
    }

    // 전체 선택
    function toggleSelectAll(el) {
        const rows = document.querySelectorAll('.candidate-row:not(.hidden)');
        rows.forEach(row => {
            const cb = row.querySelector('.employee-checkbox');
            if (cb) cb.checked = el.checked;
        });
        updateSelectedCount();
    }

    function updateSelectedCount() {
        const checked = document.querySelectorAll('.employee-checkbox:checked').length;
        const countEl = document.getElementById('selected-count');
        if (checked > 0) {
            countEl.textContent = checked + '명 선택됨';
            countEl.classList.remove('hidden');
        } else {
            countEl.classList.add('hidden');
        }
    }

    // 상태 필터
    function filterByStatus(status) {
        document.querySelectorAll('.candidate-row').forEach(row => {
            if (!status || row.dataset.status === status) {
                row.classList.remove('hidden');
            } else {
                row.classList.add('hidden');
            }
        });
        // 전체 선택 해제
        document.getElementById('select-all').checked = false;
        document.querySelectorAll('.employee-checkbox').forEach(cb => cb.checked = false);
        updateSelectedCount();
    }

    // 일괄 발송 모달
    function openBulkModal(type) {
        const checked = document.querySelectorAll('.employee-checkbox:checked');
        if (checked.length === 0) {
            alert('발송할 대상자를 선택해주세요.');
            return;
        }

        currentNoticeType = type;
        const modal = document.getElementById('bulk-modal');
        const title = document.getElementById('bulk-modal-title');
        const count = document.getElementById('bulk-count');
        const deadlineSection = document.getElementById('deadline-section');
        const datesSection = document.getElementById('dates-section');

        count.textContent = checked.length;

        if (type === '1st') {
            title.textContent = '1차 연차촉진 통지서 발송';
            deadlineSection.classList.remove('hidden');
            datesSection.classList.add('hidden');
        } else {
            title.textContent = '2차 연차촉진 통지서 발송';
            deadlineSection.classList.add('hidden');
            datesSection.classList.remove('hidden');
        }

        modal.classList.remove('hidden');
    }

    function closeBulkModal() {
        document.getElementById('bulk-modal').classList.add('hidden');
    }

    // 지정 휴가일 추가
    function addDesignatedDate() {
        const container = document.getElementById('designated-dates-container');
        const div = document.createElement('div');
        div.className = 'flex items-center gap-2 mb-2';
        div.innerHTML = `
            <input type="date" class="designated-date-input flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm">
            <button type="button" onclick="this.parentElement.remove()" class="px-2 py-2 text-red-500 hover:text-red-700">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        `;
        container.appendChild(div);
    }

    // 일괄 발송 실행
    function submitBulkNotice() {
        const checked = document.querySelectorAll('.employee-checkbox:checked');
        const employeeIds = Array.from(checked).map(cb => parseInt(cb.value));

        if (employeeIds.length === 0) {
            alert('대상자를 선택해주세요.');
            return;
        }

        const data = {
            employee_ids: employeeIds,
            notice_type: currentNoticeType,
            year: {{ $year }},
            _token: '{{ csrf_token() }}',
        };

        if (currentNoticeType === '1st') {
            const deadline = document.getElementById('bulk-deadline').value;
            if (!deadline) {
                alert('제출 기한을 입력해주세요.');
                return;
            }
            data.deadline = deadline;
        } else {
            const dateInputs = document.querySelectorAll('.designated-date-input');
            const dates = Array.from(dateInputs).map(i => i.value).filter(v => v);
            if (dates.length > 0) {
                data.designated_dates = dates;
            }
        }

        const btn = document.getElementById('bulk-submit-btn');
        btn.disabled = true;
        btn.textContent = '발송 중...';

        fetch('{{ route("hr.leave-promotions.store") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
            },
            body: JSON.stringify(data),
        })
        .then(res => res.json())
        .then(result => {
            if (result.success) {
                alert(result.message);
                closeBulkModal();
                window.location.reload();
            } else {
                alert(result.message || '발송에 실패했습니다.');
            }
        })
        .catch(err => {
            console.error(err);
            alert('오류가 발생했습니다: ' + err.message);
        })
        .finally(() => {
            btn.disabled = false;
            btn.textContent = '발송';
        });
    }
</script>
@endpush
