@extends('layouts.app')

@section('title', '카카오톡 전송내역')

@section('content')
<div class="flex flex-col h-full">
    <!-- 페이지 헤더 -->
    <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 mb-6 flex-shrink-0">
        <div>
            <div class="flex items-center gap-2 text-sm text-gray-500 mb-1">
                <a href="{{ route('barobill.kakaotalk.index') }}" class="hover:text-gray-700">카카오톡</a>
                <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="M9 5l7 7-7 7" /></svg>
                <span class="text-gray-700">전송내역</span>
            </div>
            <h1 class="text-2xl font-bold text-gray-800">전송내역</h1>
            <p class="text-sm text-gray-500 mt-1">카카오톡 발송 이력 조회 및 예약 관리</p>
        </div>
    </div>

    @if(!$barobillMember)
    <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-6 text-center">
        <h3 class="text-lg font-semibold text-yellow-800 mb-1">바로빌 회원사 연동 필요</h3>
        <p class="text-sm text-yellow-600">전송내역을 조회하려면 먼저 바로빌 회원사를 등록해주세요.</p>
    </div>
    @else
    <!-- 조회 필터 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6 mb-6">
        <h3 class="font-semibold text-gray-800 mb-4">전송키로 조회</h3>
        <div class="flex gap-3">
            <input type="text" id="search-send-key" placeholder="전송키를 입력하세요" class="flex-1 px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-yellow-500">
            <button type="button" onclick="searchBySendKey()" class="px-4 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition text-sm flex items-center gap-2">
                <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="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" /></svg>
                조회
            </button>
        </div>
        <p class="text-xs text-gray-500 mt-2">여러 건 조회 시 전송키를 쉼표(,)로 구분하세요.</p>
    </div>

    <!-- 조회 결과 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-100">
        <div id="history-result" class="p-6">
            <div class="text-center py-12 text-gray-400">
                <svg class="w-12 h-12 mx-auto mb-3" 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 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
                </svg>
                <p class="text-sm">전송키를 입력하여 발송 결과를 조회하세요.</p>
            </div>
        </div>
    </div>
    @endif
</div>
@endsection

@push('scripts')
<script>
function searchBySendKey() {
    const input = document.getElementById('search-send-key').value.trim();
    const container = document.getElementById('history-result');

    if (!input) {
        alert('전송키를 입력해주세요.');
        return;
    }

    container.innerHTML = '<div class="text-center py-12 text-gray-400"><svg class="w-10 h-10 mx-auto mb-3 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /></svg><p class="text-sm">조회 중...</p></div>';

    const keys = input.split(',').map(k => k.trim()).filter(k => k);

    if (keys.length === 1) {
        // 단건 조회
        fetch('/api/admin/barobill/kakaotalk/send/' + encodeURIComponent(keys[0]), {
            headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
        })
        .then(r => r.json())
        .then(data => renderResult(data, container))
        .catch(err => { container.innerHTML = '<div class="text-center py-12"><p class="text-sm text-red-500">조회 오류: ' + err.message + '</p></div>'; });
    } else {
        // 다건 조회
        fetch('/api/admin/barobill/kakaotalk/send/results', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content },
            body: JSON.stringify({ send_keys: keys }),
        })
        .then(r => r.json())
        .then(data => renderResult(data, container))
        .catch(err => { container.innerHTML = '<div class="text-center py-12"><p class="text-sm text-red-500">조회 오류: ' + err.message + '</p></div>'; });
    }
}

function renderResult(data, container) {
    if (!data.success) {
        container.innerHTML = '<div class="text-center py-12"><p class="text-sm text-red-500">' + (data.error || data.message) + '</p></div>';
        return;
    }

    const raw = data.data;
    let items = [];

    // 단건 결과
    if (raw && !Array.isArray(raw) && (raw.SendKey || raw.ReceiverNum)) {
        items = [raw];
    }
    // 다건 결과
    else if (Array.isArray(raw)) {
        items = raw;
    }
    else if (raw && raw.KakaotalkSendResult) {
        items = Array.isArray(raw.KakaotalkSendResult) ? raw.KakaotalkSendResult : [raw.KakaotalkSendResult];
    }

    if (items.length === 0) {
        container.innerHTML = '<div class="text-center py-12 text-gray-400"><p class="text-sm">조회된 결과가 없습니다.</p></div>';
        return;
    }

    let html = '<div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="border-b border-gray-200">';
    html += '<th class="text-left py-3 px-4 font-medium text-gray-600">전송키</th>';
    html += '<th class="text-left py-3 px-4 font-medium text-gray-600">수신번호</th>';
    html += '<th class="text-left py-3 px-4 font-medium text-gray-600">수신자</th>';
    html += '<th class="text-center py-3 px-4 font-medium text-gray-600">상태</th>';
    html += '<th class="text-center py-3 px-4 font-medium text-gray-600">발송일시</th>';
    html += '<th class="text-center py-3 px-4 font-medium text-gray-600">작업</th>';
    html += '</tr></thead><tbody>';

    items.forEach(item => {
        const statusMap = { '0': '대기', '1': '전송중', '2': '성공', '3': '실패', '-1': '취소' };
        const statusLabel = statusMap[String(item.Status)] || item.Status || item.ResultCode || '-';
        const statusColor = item.Status == 2 ? 'green' : (item.Status == 3 || item.Status == -1 ? 'red' : 'yellow');

        html += '<tr class="border-b border-gray-50 hover:bg-gray-50">';
        html += '<td class="py-3 px-4 font-mono text-xs">' + (item.SendKey || '-') + '</td>';
        html += '<td class="py-3 px-4">' + (item.ReceiverNum || '-') + '</td>';
        html += '<td class="py-3 px-4">' + (item.ReceiverName || '-') + '</td>';
        html += '<td class="py-3 px-4 text-center"><span class="px-2 py-0.5 rounded-full text-xs font-medium bg-' + statusColor + '-100 text-' + statusColor + '-700">' + statusLabel + '</span></td>';
        html += '<td class="py-3 px-4 text-center text-xs text-gray-500">' + (item.SendDT || item.ReserveDT || '-') + '</td>';
        html += '<td class="py-3 px-4 text-center">';
        if (item.Status == 0 || String(item.Status) === '대기') {
            html += '<button onclick="cancelReserved(\'' + item.SendKey + '\')" class="text-xs text-red-600 hover:text-red-800">예약취소</button>';
        }
        html += '</td></tr>';
    });
    html += '</tbody></table></div>';
    container.innerHTML = html;
}

function cancelReserved(sendKey) {
    if (!confirm('전송키 ' + sendKey + '의 예약을 취소하시겠습니까?')) return;

    fetch('/api/admin/barobill/kakaotalk/send/' + encodeURIComponent(sendKey) + '/cancel', {
        method: 'DELETE',
        headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content },
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            alert('예약이 취소되었습니다.');
            searchBySendKey();
        } else {
            alert('취소 실패: ' + (data.error || data.message));
        }
    })
    .catch(err => alert('오류: ' + err.message));
}

// Enter 키로 조회
document.getElementById('search-send-key')?.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') searchBySendKey();
});
</script>
@endpush
