@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">{{ $year }}년 {{ $month }}월 현재</p>
        </div>
        <div class="flex flex-wrap items-center gap-2">
            <button type="button" onclick="openCreateModal()"
               class="inline-flex items-center gap-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg transition-colors">
                <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 class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        {{-- 입금 예정 --}}
        <div class="bg-white rounded-lg shadow-sm p-4 border-l-4 border-green-500">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">입금 예정</p>
                    <p class="text-xl font-bold text-green-600">{{ number_format($summary['income']['total']) }}원</p>
                </div>
                <div class="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
                    <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                    </svg>
                </div>
            </div>
            <p class="text-xs text-gray-400 mt-1">{{ $summary['income']['count'] }}건</p>
        </div>

        {{-- 지급 예정 --}}
        <div class="bg-white rounded-lg shadow-sm p-4 border-l-4 border-red-500">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">지급 예정</p>
                    <p class="text-xl font-bold text-red-600">{{ number_format($summary['expense']['total']) }}원</p>
                </div>
                <div class="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center">
                    <svg class="w-5 h-5 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4"/>
                    </svg>
                </div>
            </div>
            <p class="text-xs text-gray-400 mt-1">{{ $summary['expense']['count'] }}건</p>
        </div>

        {{-- 순 자금 흐름 --}}
        <div class="bg-white rounded-lg shadow-sm p-4 border-l-4 border-blue-500">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">순 자금 흐름</p>
                    <p class="text-xl font-bold {{ $summary['net'] >= 0 ? 'text-blue-600' : 'text-orange-600' }}">
                        {{ $summary['net'] >= 0 ? '+' : '' }}{{ number_format($summary['net']) }}원
                    </p>
                </div>
                <div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                    <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"/>
                    </svg>
                </div>
            </div>
        </div>

        {{-- 총 건수 --}}
        <div class="bg-white rounded-lg shadow-sm p-4 border-l-4 border-purple-500">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">총 일정</p>
                    <p class="text-xl font-bold text-purple-600">{{ $summary['total_count'] }}건</p>
                </div>
                <div class="w-10 h-10 bg-purple-100 rounded-full flex items-center justify-center">
                    <svg class="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                    </svg>
                </div>
            </div>
        </div>
    </div>

    {{-- 캘린더 섹션 --}}
    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
            <h2 class="text-lg font-semibold text-gray-800">자금 일정 달력</h2>

            {{-- 월 네비게이션 --}}
            <div class="flex items-center gap-2">
                @php
                    $prevMonth = $month - 1;
                    $prevYear = $year;
                    if ($prevMonth < 1) {
                        $prevMonth = 12;
                        $prevYear--;
                    }
                    $nextMonth = $month + 1;
                    $nextYear = $year;
                    if ($nextMonth > 12) {
                        $nextMonth = 1;
                        $nextYear++;
                    }
                @endphp
                <a href="{{ route('finance.fund-schedules.index', ['year' => $prevYear, 'month' => $prevMonth]) }}"
                   class="p-2 hover:bg-gray-100 rounded-lg transition-colors">
                    <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                    </svg>
                </a>
                <span class="px-4 py-2 font-medium text-gray-700">{{ $year }}년 {{ str_pad($month, 2, '0', STR_PAD_LEFT) }}월</span>
                <a href="{{ route('finance.fund-schedules.index', ['year' => $nextYear, 'month' => $nextMonth]) }}"
                   class="p-2 hover:bg-gray-100 rounded-lg transition-colors">
                    <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                    </svg>
                </a>

                {{-- 일정 복사 버튼 --}}
                <button type="button" onclick="openCopyModal()"
                        class="ml-2 inline-flex items-center gap-1.5 px-3 py-1.5 text-sm bg-indigo-50 text-indigo-700 hover:bg-indigo-100 border border-indigo-200 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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                    </svg>
                    일정복사
                </button>
            </div>
        </div>

        {{-- 캘린더 그리드 --}}
        <div id="calendar-container">
            @include('finance.fund-schedules.partials.calendar', ['year' => $year, 'month' => $month, 'calendarData' => $calendarData])
        </div>
    </div>

    {{-- 범례 --}}
    <div class="mt-4 flex items-center gap-6 text-sm text-gray-600">
        <div class="flex items-center gap-2">
            <span class="w-4 h-4 bg-green-100 border border-green-300 rounded"></span>
            <span>입금 예정</span>
        </div>
        <div class="flex items-center gap-2">
            <span class="w-4 h-4 bg-red-100 border border-red-300 rounded"></span>
            <span>지급 예정</span>
        </div>
    </div>
</div>

{{-- 일정 복사 모달 --}}
<div id="copyModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50" onclick="closeCopyModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-xl shadow-2xl w-full max-w-md relative">
            <div class="px-6 py-4 border-b flex items-center justify-between">
                <h3 class="text-lg font-bold text-gray-800">일정 복사</h3>
                <button type="button" onclick="closeCopyModal()" class="text-gray-400 hover:text-gray-600">
                    <svg class="w-6 h-6" 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>
            </div>
            <div class="p-6">
                <div id="copy-modal-message"></div>

                <div class="mb-5">
                    <p class="text-sm text-gray-600 mb-3">
                        <span class="font-semibold text-gray-800">{{ $year }}년 {{ str_pad($month, 2, '0', STR_PAD_LEFT) }}월</span>의 일정을 아래 선택한 월로 복사합니다.
                    </p>
                    <p class="text-xs text-gray-400">복사된 일정의 상태는 모두 '대기'로 설정됩니다.</p>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label for="copy_target_year" class="block text-sm font-medium text-gray-700 mb-1">대상 연도</label>
                        <select id="copy_target_year" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
                            @for($y = $year - 1; $y <= $year + 2; $y++)
                                <option value="{{ $y }}" {{ $y === $nextYear ? 'selected' : '' }}>{{ $y }}년</option>
                            @endfor
                        </select>
                    </div>
                    <div>
                        <label for="copy_target_month" class="block text-sm font-medium text-gray-700 mb-1">대상 월</label>
                        <select id="copy_target_month" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
                            @for($m = 1; $m <= 12; $m++)
                                <option value="{{ $m }}" {{ $m === $nextMonth ? 'selected' : '' }}>{{ $m }}월</option>
                            @endfor
                        </select>
                    </div>
                </div>
            </div>
            <div class="px-6 py-4 border-t bg-gray-50 flex justify-end gap-3 rounded-b-xl">
                <button type="button" onclick="closeCopyModal()" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                    취소
                </button>
                <button type="button" onclick="copySchedules()" id="copySubmitBtn" class="px-6 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg transition-colors">
                    복사
                </button>
            </div>
        </div>
    </div>
</div>

{{-- 일정 편집/등록 모달 --}}
<div id="scheduleModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50" onclick="closeScheduleModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto relative">
            {{-- 모달 헤더 --}}
            <div class="sticky top-0 bg-white px-6 py-4 border-b flex items-center justify-between z-10">
                <h3 id="modalTitle" class="text-lg font-bold text-gray-800">일정 등록</h3>
                <button type="button" onclick="closeScheduleModal()" class="text-gray-400 hover:text-gray-600">
                    <svg class="w-6 h-6" 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>
            </div>

            {{-- 모달 바디 --}}
            <div class="p-6">
                <form id="modalScheduleForm" class="space-y-5">
                    <input type="hidden" name="id" id="modal_id">

                    {{-- 메시지 영역 --}}
                    <div id="modal-form-message"></div>

                    {{-- 일정 유형 --}}
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            일정 유형 <span class="text-red-500">*</span>
                        </label>
                        <div class="grid grid-cols-2 gap-3">
                            <label class="relative flex cursor-pointer rounded-lg border p-3 border-green-300 bg-green-50 has-[:checked]:border-green-500 has-[:checked]:ring-2 has-[:checked]:ring-green-500">
                                <input type="radio" name="schedule_type" value="income" class="sr-only">
                                <span class="flex flex-1 items-center justify-center">
                                    <span class="text-sm font-medium text-green-900">입금</span>
                                </span>
                                <svg class="h-5 w-5 text-green-600 hidden [input:checked~&]:block absolute right-2" viewBox="0 0 20 20" fill="currentColor">
                                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z" clip-rule="evenodd" />
                                </svg>
                            </label>
                            <label class="relative flex cursor-pointer rounded-lg border p-3 border-red-300 bg-red-50 has-[:checked]:border-red-500 has-[:checked]:ring-2 has-[:checked]:ring-red-500">
                                <input type="radio" name="schedule_type" value="expense" class="sr-only" checked>
                                <span class="flex flex-1 items-center justify-center">
                                    <span class="text-sm font-medium text-red-900">지급</span>
                                </span>
                                <svg class="h-5 w-5 text-red-600 hidden [input:checked~&]:block absolute right-2" viewBox="0 0 20 20" fill="currentColor">
                                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z" clip-rule="evenodd" />
                                </svg>
                            </label>
                        </div>
                    </div>

                    {{-- 일정명 --}}
                    <div>
                        <label for="modal_title" class="block text-sm font-medium text-gray-700 mb-1">
                            일정명 <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="title" id="modal_title" required
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                    </div>

                    {{-- 예정일 & 금액 --}}
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label for="modal_scheduled_date" class="block text-sm font-medium text-gray-700 mb-1">
                                예정일 <span class="text-red-500">*</span>
                            </label>
                            <input type="date" name="scheduled_date" id="modal_scheduled_date" required
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                        </div>
                        <div>
                            <label for="modal_amount_display" class="block text-sm font-medium text-gray-700 mb-1">
                                금액 <span class="text-red-500">*</span>
                            </label>
                            <input type="text" id="modal_amount_display" required inputmode="numeric"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 text-right"
                                   oninput="formatModalAmount(this)" onblur="formatModalAmount(this)">
                            <input type="hidden" name="amount" id="modal_amount">
                        </div>
                    </div>

                    {{-- 거래상대방 --}}
                    <div>
                        <label for="modal_counterparty" class="block text-sm font-medium text-gray-700 mb-1">
                            거래상대방
                        </label>
                        <input type="text" name="counterparty" id="modal_counterparty"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                    </div>

                    {{-- 출금 계좌 --}}
                    <div>
                        <label for="modal_bank_account" class="block text-sm font-medium text-gray-700 mb-1">
                            출금 계좌
                        </label>
                        <select name="related_bank_account_id" id="modal_bank_account"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                            <option value="">선택안함</option>
                            @foreach($accounts ?? [] as $account)
                            <option value="{{ $account->id }}">{{ $account->bank_name }} - {{ $account->account_number }}</option>
                            @endforeach
                        </select>
                    </div>

                    {{-- 분류 & 상태 --}}
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label for="modal_category" class="block text-sm font-medium text-gray-700 mb-1">분류</label>
                            <select name="category" id="modal_category"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                                <option value="">선택안함</option>
                                <option value="매출">매출</option>
                                <option value="매입">매입</option>
                                <option value="급여">급여</option>
                                <option value="임대료">임대료</option>
                                <option value="운영비">운영비</option>
                                <option value="세금">세금</option>
                                <option value="대출">대출</option>
                                <option value="투자">투자</option>
                                <option value="기타">기타</option>
                            </select>
                        </div>
                        <div>
                            <label for="modal_status" class="block text-sm font-medium text-gray-700 mb-1">상태</label>
                            <select name="status" id="modal_status"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                                <option value="pending">대기</option>
                                <option value="completed">완료</option>
                                <option value="cancelled">취소</option>
                            </select>
                        </div>
                    </div>

                    {{-- 설명 --}}
                    <div>
                        <label for="modal_description" class="block text-sm font-medium text-gray-700 mb-1">설명</label>
                        <textarea name="description" id="modal_description" rows="2"
                                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500"></textarea>
                    </div>

                    {{-- 메모 --}}
                    <div>
                        <label for="modal_memo" class="block text-sm font-medium text-gray-700 mb-1">메모</label>
                        <textarea name="memo" id="modal_memo" rows="2"
                                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500"></textarea>
                    </div>
                </form>
            </div>

            {{-- 모달 푸터 --}}
            <div class="sticky bottom-0 bg-gray-50 px-6 py-4 border-t flex justify-between">
                <button type="button" id="deleteBtn" onclick="deleteSchedule()" class="px-4 py-2 text-red-600 hover:text-red-800 hover:bg-red-50 rounded-lg transition-colors hidden">
                    삭제
                </button>
                <div class="flex gap-3 ml-auto">
                    <button type="button" onclick="closeScheduleModal()" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors">
                        취소
                    </button>
                    <button type="button" onclick="saveSchedule()" class="px-6 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg transition-colors">
                        저장
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
    let currentScheduleId = null;
    const csrfToken = '{{ csrf_token() }}';

    // 모달 열기 (신규 등록)
    function openCreateModal(date) {
        currentScheduleId = null;
        document.getElementById('modalTitle').textContent = '일정 등록';
        document.getElementById('deleteBtn').classList.add('hidden');

        // 폼 초기화
        document.getElementById('modalScheduleForm').reset();
        document.getElementById('modal_id').value = '';
        document.getElementById('modal_scheduled_date').value = date || new Date().toISOString().split('T')[0];
        document.getElementById('modal_amount_display').value = '';
        document.getElementById('modal_amount').value = '';

        // 기본값: 지급
        document.querySelector('input[name="schedule_type"][value="expense"]').checked = true;

        document.getElementById('scheduleModal').classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }

    // 모달 열기 (수정)
    async function openEditModal(id) {
        currentScheduleId = id;
        document.getElementById('modalTitle').textContent = '일정 수정';
        document.getElementById('deleteBtn').classList.remove('hidden');

        try {
            const response = await fetch(`/api/admin/fund-schedules/${id}`, {
                headers: { 'Accept': 'application/json' }
            });
            const result = await response.json();

            if (result.success) {
                const data = result.data;
                document.getElementById('modal_id').value = data.id;
                document.getElementById('modal_title').value = data.title;
                document.getElementById('modal_scheduled_date').value = data.scheduled_date;
                document.getElementById('modal_amount').value = data.amount;
                document.getElementById('modal_amount_display').value = Number(data.amount).toLocaleString('ko-KR');
                document.getElementById('modal_counterparty').value = data.counterparty || '';
                document.getElementById('modal_bank_account').value = data.related_bank_account_id || '';
                document.getElementById('modal_category').value = data.category || '';
                document.getElementById('modal_status').value = data.status || 'pending';
                document.getElementById('modal_description').value = data.description || '';
                document.getElementById('modal_memo').value = data.memo || '';

                // 일정 유형
                document.querySelector(`input[name="schedule_type"][value="${data.schedule_type}"]`).checked = true;

                document.getElementById('scheduleModal').classList.remove('hidden');
                document.body.style.overflow = 'hidden';
            } else {
                alert('일정 정보를 불러오는데 실패했습니다.');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('일정 정보를 불러오는데 실패했습니다.');
        }
    }

    // 모달 닫기
    function closeScheduleModal() {
        document.getElementById('scheduleModal').classList.add('hidden');
        document.body.style.overflow = '';
        document.getElementById('modal-form-message').innerHTML = '';
    }

    // 금액 포맷
    function formatModalAmount(input) {
        let value = input.value.replace(/[^\d]/g, '');
        if (!value) value = '0';
        const numValue = parseInt(value, 10);
        input.value = numValue.toLocaleString('ko-KR');
        document.getElementById('modal_amount').value = numValue;
    }

    // 저장
    async function saveSchedule() {
        const form = document.getElementById('modalScheduleForm');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());

        // 금액 숫자로 변환
        data.amount = parseInt(document.getElementById('modal_amount').value) || 0;

        const isEdit = currentScheduleId !== null;
        const url = isEdit
            ? `/api/admin/fund-schedules/${currentScheduleId}`
            : '/api/admin/fund-schedules';
        const method = isEdit ? 'PUT' : 'POST';

        try {
            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.success) {
                closeScheduleModal();
                window.location.reload();
            } else {
                document.getElementById('modal-form-message').innerHTML =
                    `<div class="p-3 bg-red-50 text-red-700 rounded-lg text-sm">${result.message || '저장에 실패했습니다.'}</div>`;
            }
        } catch (error) {
            console.error('Error:', error);
            document.getElementById('modal-form-message').innerHTML =
                '<div class="p-3 bg-red-50 text-red-700 rounded-lg text-sm">저장 중 오류가 발생했습니다.</div>';
        }
    }

    // 삭제
    async function deleteSchedule() {
        if (!currentScheduleId) return;
        if (!confirm('이 일정을 삭제하시겠습니까?')) return;

        try {
            const response = await fetch(`/api/admin/fund-schedules/${currentScheduleId}`, {
                method: 'DELETE',
                headers: {
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                }
            });

            const result = await response.json();

            if (result.success) {
                closeScheduleModal();
                window.location.reload();
            } else {
                alert(result.message || '삭제에 실패했습니다.');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('삭제 중 오류가 발생했습니다.');
        }
    }

    // ESC 키로 모달 닫기
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            if (!document.getElementById('copyModal').classList.contains('hidden')) {
                closeCopyModal();
            } else if (!document.getElementById('scheduleModal').classList.contains('hidden')) {
                closeScheduleModal();
            }
        }
    });

    // =========================================
    // 일정 복사 기능
    // =========================================

    function openCopyModal() {
        document.getElementById('copy-modal-message').innerHTML = '';
        document.getElementById('copySubmitBtn').disabled = false;
        document.getElementById('copyModal').classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }

    function closeCopyModal() {
        document.getElementById('copyModal').classList.add('hidden');
        document.body.style.overflow = '';
    }

    async function copySchedules() {
        const targetYear = parseInt(document.getElementById('copy_target_year').value);
        const targetMonth = parseInt(document.getElementById('copy_target_month').value);
        const sourceYear = {{ $year }};
        const sourceMonth = {{ $month }};

        if (sourceYear === targetYear && sourceMonth === targetMonth) {
            document.getElementById('copy-modal-message').innerHTML =
                '<div class="p-3 mb-4 bg-red-50 text-red-700 rounded-lg text-sm">원본 월과 대상 월이 동일합니다.</div>';
            return;
        }

        if (!confirm(`${sourceYear}년 ${sourceMonth}월의 일정을 ${targetYear}년 ${targetMonth}월로 복사하시겠습니까?`)) {
            return;
        }

        const btn = document.getElementById('copySubmitBtn');
        btn.disabled = true;
        btn.textContent = '복사 중...';

        try {
            const response = await fetch('/api/admin/fund-schedules/copy', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify({
                    source_year: sourceYear,
                    source_month: sourceMonth,
                    target_year: targetYear,
                    target_month: targetMonth
                })
            });

            const result = await response.json();

            if (result.success) {
                closeCopyModal();
                if (confirm(result.message + '\n\n대상 월로 이동하시겠습니까?')) {
                    window.location.href = `{{ route('finance.fund-schedules.index') }}?year=${targetYear}&month=${targetMonth}`;
                } else {
                    window.location.reload();
                }
            } else {
                document.getElementById('copy-modal-message').innerHTML =
                    `<div class="p-3 mb-4 bg-red-50 text-red-700 rounded-lg text-sm">${result.message || '복사에 실패했습니다.'}</div>`;
                btn.disabled = false;
                btn.textContent = '복사';
            }
        } catch (error) {
            console.error('Error:', error);
            document.getElementById('copy-modal-message').innerHTML =
                '<div class="p-3 mb-4 bg-red-50 text-red-700 rounded-lg text-sm">복사 중 오류가 발생했습니다.</div>';
            btn.disabled = false;
            btn.textContent = '복사';
        }
    }
</script>
@endpush
