@extends('layouts.app')

@section('title', '견적수식 관리')

@section('content')
<div class="container mx-auto max-w-7xl">
    <!-- 헤더 -->
    <div class="flex flex-col sm:flex-row sm:justify-between sm: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 gap-2">
            <a href="{{ route('quote-formulas.categories.index') }}"
               class="flex-1 sm:flex-none bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors text-center">
                카테고리 관리
            </a>
            <a href="{{ route('quote-formulas.simulator') }}"
               class="flex-1 sm:flex-none bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors text-center">
                시뮬레이터
            </a>
            <a href="{{ route('quote-formulas.create') }}"
               class="w-full sm:w-auto bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors text-center">
                + 수식 추가
            </a>
        </div>
    </div>

    <!-- 필터 -->
    <x-filter-collapsible id="filterForm">
        <form id="filterForm" class="flex flex-wrap gap-2 sm:gap-4 items-end">
            <!-- 카테고리 필터 -->
            <div class="w-full sm:w-48">
                <label class="block text-xs font-medium text-gray-600 mb-1">카테고리</label>
                <select name="category_id" id="categoryFilter" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">전체</option>
                </select>
            </div>

            <!-- 유형 필터 -->
            <div class="w-full sm:w-40">
                <label class="block text-xs font-medium text-gray-600 mb-1">수식 유형</label>
                <select name="type" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">전체</option>
                    <option value="input">입력값</option>
                    <option value="calculation">계산식</option>
                    <option value="range">범위별</option>
                    <option value="mapping">매핑</option>
                </select>
            </div>

            <!-- 활성 상태 필터 -->
            <div class="w-full sm:w-32">
                <label class="block text-xs font-medium text-gray-600 mb-1">상태</label>
                <select name="is_active" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">전체</option>
                    <option value="1">활성</option>
                    <option value="0">비활성</option>
                </select>
            </div>

            <!-- 삭제된 항목 포함 -->
            <div class="w-full sm:w-36">
                <label class="block text-xs font-medium text-gray-600 mb-1">삭제 포함</label>
                <select name="trashed" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">활성만</option>
                    <option value="with">삭제 포함</option>
                    <option value="only">삭제만</option>
                </select>
            </div>

            <!-- 검색 -->
            <div class="flex-1 min-w-0 w-full sm:w-auto">
                <label class="block text-xs font-medium text-gray-600 mb-1">검색</label>
                <input type="text" name="search"
                       placeholder="수식명, 변수명, 수식 내용..."
                       class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <!-- 검색 버튼 -->
            <button type="submit"
                    class="w-full sm:w-auto bg-gray-800 hover:bg-gray-900 text-white px-6 py-2 rounded-lg text-sm font-medium transition-colors">
                검색
            </button>
        </form>
    </x-filter-collapsible>

    <!-- 테이블 영역 (HTMX로 로드) -->
    <div id="formula-table"
         hx-get="/api/admin/quote-formulas/formulas"
         hx-trigger="load, filterSubmit from:body"
         hx-include="#filterForm"
         hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'
         class="bg-white rounded-lg shadow-sm overflow-hidden">
        <!-- 로딩 스피너 -->
        <div class="flex justify-center items-center p-12">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
<script>
    // 카테고리 목록 로드
    document.addEventListener('DOMContentLoaded', function() {
        fetch('/api/admin/quote-formulas/categories/dropdown', {
            headers: {
                'Accept': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                const select = document.getElementById('categoryFilter');
                data.data.forEach(cat => {
                    const option = document.createElement('option');
                    option.value = cat.id;
                    option.textContent = cat.name;
                    select.appendChild(option);
                });
            }
        })
        .catch(err => console.error('카테고리 로드 실패:', err));
    });

    // 폼 제출 시 HTMX 이벤트 트리거
    document.getElementById('filterForm').addEventListener('submit', function(e) {
        e.preventDefault();
        htmx.trigger('#formula-table', 'filterSubmit');
    });

    // 삭제 확인
    window.confirmDelete = function(id, name) {
        showDeleteConfirm(`"${name}" 수식`, () => {
            htmx.ajax('DELETE', `/api/admin/quote-formulas/formulas/${id}`, {
                target: '#formula-table',
                swap: 'none',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                }
            }).then(() => {
                htmx.trigger('#formula-table', 'filterSubmit');
            });
        });
    };

    // 복원 확인
    window.confirmRestore = function(id, name) {
        showConfirm(`"${name}" 수식을 복원하시겠습니까?`, () => {
            htmx.ajax('POST', `/api/admin/quote-formulas/formulas/${id}/restore`, {
                target: '#formula-table',
                swap: 'none',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                }
            }).then(() => {
                htmx.trigger('#formula-table', 'filterSubmit');
            });
        }, { title: '복원 확인', icon: 'question' });
    };

    // 영구삭제 확인
    window.confirmForceDelete = function(id, name) {
        showPermanentDeleteConfirm(`"${name}" 수식`, () => {
            htmx.ajax('DELETE', `/api/admin/quote-formulas/formulas/${id}/force`, {
                target: '#formula-table',
                swap: 'none',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                }
            }).then(() => {
                htmx.trigger('#formula-table', 'filterSubmit');
            });
        });
    };

    // 활성/비활성 토글
    window.toggleActive = function(id) {
        htmx.ajax('POST', `/api/admin/quote-formulas/formulas/${id}/toggle-active`, {
            target: '#formula-table',
            swap: 'none',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        }).then(() => {
            htmx.trigger('#formula-table', 'filterSubmit');
        });
    };

    // 수식 복제
    window.duplicateFormula = function(id) {
        showConfirm('이 수식을 복제하시겠습니까?', () => {
            htmx.ajax('POST', `/api/admin/quote-formulas/formulas/${id}/duplicate`, {
                target: '#formula-table',
                swap: 'none',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                }
            }).then(() => {
                htmx.trigger('#formula-table', 'filterSubmit');
            });
        }, { title: '수식 복제', icon: 'question' });
    };
</script>
@endpush
