@extends('layouts.app')

@section('title', '조회회수 집계')

@section('content')
<div class="max-w-7xl mx-auto">
    <!-- 페이지 헤더 -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-800">신용평가 조회회수 집계</h1>
        <p class="text-sm text-gray-500 mt-1">
            @if($isHQ)
                전체 테넌트의 신용평가 조회 현황을 확인합니다
            @else
                월별/기간별 신용평가 조회 현황을 확인합니다
            @endif
        </p>
    </div>

    <!-- 필터 -->
    <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
        <form method="GET" class="flex flex-wrap items-end gap-4">
            <!-- 조회 유형 -->
            <div class="min-w-[120px]">
                <label class="block text-sm font-medium text-gray-700 mb-1">조회 유형</label>
                <select name="view_type" onchange="toggleViewType(this.value)"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="monthly" {{ $filters['view_type'] === 'monthly' ? 'selected' : '' }}>월별</option>
                    <option value="yearly" {{ $filters['view_type'] === 'yearly' ? 'selected' : '' }}>연간</option>
                    <option value="custom" {{ $filters['view_type'] === 'custom' ? 'selected' : '' }}>기간 지정</option>
                </select>
            </div>

            <!-- 연도 선택 -->
            <div id="year-filter" class="min-w-[120px]">
                <label class="block text-sm font-medium text-gray-700 mb-1">연도</label>
                <select name="year" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    @for($y = date('Y'); $y >= date('Y') - 2; $y--)
                        <option value="{{ $y }}" {{ $filters['year'] == $y ? 'selected' : '' }}>{{ $y }}년</option>
                    @endfor
                </select>
            </div>

            <!-- 월 선택 (월별 조회 시) -->
            <div id="month-filter" class="min-w-[120px] {{ $filters['view_type'] !== 'monthly' ? 'hidden' : '' }}">
                <label class="block text-sm font-medium text-gray-700 mb-1">월</label>
                <select name="month" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    @for($m = 1; $m <= 12; $m++)
                        <option value="{{ str_pad($m, 2, '0', STR_PAD_LEFT) }}" {{ $filters['month'] == str_pad($m, 2, '0', STR_PAD_LEFT) ? 'selected' : '' }}>
                            {{ $m }}월
                        </option>
                    @endfor
                </select>
            </div>

            <!-- 기간 지정 (기간 지정 시) -->
            <div id="custom-date-filter" class="{{ $filters['view_type'] !== 'custom' ? 'hidden' : '' }}">
                <label class="block text-sm font-medium text-gray-700 mb-1">기간</label>
                <div class="flex items-center gap-2">
                    <input type="date" name="start_date" value="{{ $filters['start_date'] }}"
                           class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <span class="text-gray-500">~</span>
                    <input type="date" name="end_date" value="{{ $filters['end_date'] }}"
                           class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
            </div>

            @if($isHQ && $tenants->isNotEmpty())
            <!-- 테넌트 필터 (본사만) -->
            <div class="min-w-[180px]">
                <label class="block text-sm font-medium text-gray-700 mb-1">테넌트</label>
                <select name="tenant_id" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">전체</option>
                    @foreach($tenants as $tenant)
                        <option value="{{ $tenant->id }}" {{ $filters['tenant_id'] == $tenant->id ? 'selected' : '' }}>
                            {{ $tenant->company_name }}
                        </option>
                    @endforeach
                </select>
            </div>
            @endif

            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
                조회
            </button>
        </form>
    </div>

    <!-- 요약 카드 -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">총 조회 건수</p>
                    <p class="text-2xl font-bold text-gray-800">{{ number_format($usageData['total_count']) }}건</p>
                </div>
                <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
                    <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                    </svg>
                </div>
            </div>
        </div>

        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">유료 조회 건수</p>
                    <p class="text-2xl font-bold text-orange-600">
                        {{ number_format(max(0, $usageData['total_count'] - (count($usageData['details']) * $policy['free_quota']))) }}건
                    </p>
                </div>
                <div class="w-12 h-12 bg-orange-100 rounded-full flex items-center justify-center">
                    <svg class="w-6 h-6 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                </div>
            </div>
        </div>

        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">예상 청구 금액</p>
                    <p class="text-2xl font-bold text-green-600">{{ number_format($usageData['total_fee']) }}원</p>
                </div>
                <div class="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center">
                    <svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
                    </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">
            <h2 class="text-lg font-semibold text-gray-800">
                @if($isHQ)
                    테넌트별 조회 현황
                @else
                    월별 조회 현황
                @endif
            </h2>
        </div>

        @if(count($usageData['details']) > 0)
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        @if($isHQ)
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">테넌트</th>
                        @endif
                        @if($filters['view_type'] === 'yearly' || !$isHQ)
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">기간</th>
                        @endif
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">총 조회</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">무료 ({{ $policy['free_quota'] }}건)</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">유료</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">요금</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    @foreach($usageData['details'] as $row)
                    <tr class="hover:bg-gray-50">
                        @if($isHQ)
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">{{ $row['tenant_name'] }}</div>
                            @if(isset($row['tenant_code']))
                            <div class="text-xs text-gray-500">{{ $row['tenant_code'] }}</div>
                            @endif
                        </td>
                        @endif
                        @if($filters['view_type'] === 'yearly' || !$isHQ)
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ $row['month'] ?? '-' }}
                        </td>
                        @endif
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-right font-medium text-gray-900">
                            {{ number_format($row['count']) }}건
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-right text-green-600">
                            {{ number_format($row['free_count']) }}건
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-right {{ $row['paid_count'] > 0 ? 'text-orange-600 font-medium' : 'text-gray-500' }}">
                            {{ number_format($row['paid_count']) }}건
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-right {{ $row['fee'] > 0 ? 'text-blue-600 font-medium' : 'text-gray-500' }}">
                            {{ number_format($row['fee']) }}원
                        </td>
                    </tr>
                    @endforeach
                </tbody>
                <tfoot class="bg-gray-50">
                    <tr class="font-semibold">
                        <td class="px-6 py-4 text-sm text-gray-900" colspan="{{ $isHQ ? ($filters['view_type'] === 'yearly' ? 2 : 1) : 1 }}">
                            합계
                        </td>
                        <td class="px-6 py-4 text-sm text-right text-gray-900">{{ number_format($usageData['total_count']) }}건</td>
                        <td class="px-6 py-4 text-sm text-right text-green-600">
                            {{ number_format(array_sum(array_column($usageData['details'], 'free_count'))) }}건
                        </td>
                        <td class="px-6 py-4 text-sm text-right text-orange-600">
                            {{ number_format(array_sum(array_column($usageData['details'], 'paid_count'))) }}건
                        </td>
                        <td class="px-6 py-4 text-sm text-right text-blue-600">{{ number_format($usageData['total_fee']) }}원</td>
                    </tr>
                </tfoot>
            </table>
        </div>
        @else
        <div class="px-6 py-12 text-center text-gray-500">
            <svg class="w-12 h-12 mx-auto text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
            </svg>
            <p>조회 내역이 없습니다.</p>
        </div>
        @endif
    </div>
</div>

@push('scripts')
<script>
function toggleViewType(value) {
    const monthFilter = document.getElementById('month-filter');
    const customDateFilter = document.getElementById('custom-date-filter');

    monthFilter.classList.add('hidden');
    customDateFilter.classList.add('hidden');

    if (value === 'monthly') {
        monthFilter.classList.remove('hidden');
    } else if (value === 'custom') {
        customDateFilter.classList.remove('hidden');
    }
}
</script>
@endpush
@endsection
