@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="flex border-b border-gray-200 mb-6">
        <button type="button" onclick="switchTab('alimtalk')" id="tab-alimtalk" class="px-6 py-3 text-sm font-medium border-b-2 border-yellow-500 text-yellow-700 bg-yellow-50/50">알림톡</button>
        <button type="button" onclick="switchTab('friendtalk')" id="tab-friendtalk" class="px-6 py-3 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700">친구톡</button>
    </div>

    <!-- 알림톡 발송 폼 -->
    <div id="panel-alimtalk" class="space-y-6">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h3 class="font-semibold text-gray-800 mb-4">알림톡 발송</h3>
            <form id="alimtalk-form" class="space-y-4">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                    <!-- 채널/템플릿 선택 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">채널 (발신프로필)</label>
                        <select name="sender_id" id="at-sender-id" onchange="loadTemplateOptions('at')" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-yellow-500">
                            <option value="">로딩 중...</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">템플릿</label>
                        <select name="template_name" id="at-template" onchange="fillTemplateContent('at')" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-yellow-500">
                            <option value="">채널을 먼저 선택하세요</option>
                        </select>
                    </div>
                </div>
                <!-- 수신자 -->
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">수신자명</label>
                        <input type="text" name="receiver_name" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="홍길동">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">수신번호</label>
                        <input type="tel" name="receiver_num" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="01012345678">
                    </div>
                </div>
                <!-- 제목 / 메시지 -->
                <div>
                    <label class="block text-sm font-medium text-gray-600 mb-1">제목</label>
                    <input type="text" name="title" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="알림톡 제목">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-600 mb-1">메시지 내용</label>
                    <textarea name="message" id="at-message" rows="6" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="템플릿 선택 시 자동 입력됩니다"></textarea>
                </div>
                <!-- SMS 대체발송 -->
                <div class="bg-gray-50 rounded-lg p-4 space-y-3">
                    <div class="flex items-center gap-2">
                        <input type="checkbox" id="at-sms-toggle" onchange="toggleSmsSection('at')" class="w-4 h-4 text-yellow-600 rounded">
                        <label for="at-sms-toggle" class="text-sm font-medium text-gray-700">SMS 대체발송</label>
                        <span class="text-xs text-gray-500">(카카오톡 발송 실패 시 SMS로 발송)</span>
                    </div>
                    <div id="at-sms-fields" class="hidden space-y-3">
                        <input type="text" name="sms_subject" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="SMS 제목 (LMS일 경우)">
                        <textarea name="sms_message" rows="3" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="SMS 메시지 (90바이트 초과 시 LMS)"></textarea>
                    </div>
                </div>
                <!-- 예약 발송 -->
                <div>
                    <label class="block text-sm font-medium text-gray-600 mb-1">예약 발송</label>
                    <input type="datetime-local" name="reserve_dt" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm">
                    <p class="text-xs text-gray-500 mt-1">비워두면 즉시 발송됩니다.</p>
                </div>
                <div class="flex justify-end">
                    <button type="submit" class="px-6 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition font-medium 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="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" /></svg>
                        알림톡 발송
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 친구톡 발송 폼 -->
    <div id="panel-friendtalk" class="space-y-6 hidden">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h3 class="font-semibold text-gray-800 mb-4">친구톡 발송</h3>
            <form id="friendtalk-form" class="space-y-4">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">채널 (발신프로필)</label>
                        <select name="sender_id" id="ft-sender-id" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-yellow-500">
                            <option value="">로딩 중...</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">발송 유형</label>
                        <select id="ft-type" onchange="toggleFtImageFields()" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm">
                            <option value="text">텍스트</option>
                            <option value="image">이미지</option>
                            <option value="wide">와이드 이미지</option>
                        </select>
                    </div>
                </div>
                <!-- 수신자 -->
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">수신자명</label>
                        <input type="text" name="receiver_name" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="홍길동">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-600 mb-1">수신번호</label>
                        <input type="tel" name="receiver_num" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="01012345678">
                    </div>
                </div>
                <!-- 메시지 -->
                <div>
                    <label class="block text-sm font-medium text-gray-600 mb-1">메시지 내용</label>
                    <textarea name="message" rows="6" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="친구톡 메시지 내용을 입력하세요"></textarea>
                </div>
                <!-- 이미지 URL -->
                <div id="ft-image-fields" class="hidden">
                    <label class="block text-sm font-medium text-gray-600 mb-1">이미지 URL</label>
                    <input type="url" name="image_url" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="https://example.com/image.jpg">
                    <p class="text-xs text-gray-500 mt-1">친구톡 이미지: 500x250px / 와이드 이미지: 800x400px</p>
                </div>
                <!-- 버튼 -->
                <div class="bg-gray-50 rounded-lg p-4">
                    <div class="flex items-center justify-between mb-3">
                        <label class="text-sm font-medium text-gray-700">버튼 설정</label>
                        <button type="button" onclick="addButton('ft')" class="text-xs px-3 py-1 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300">+ 버튼 추가</button>
                    </div>
                    <div id="ft-buttons-container" class="space-y-3"></div>
                </div>
                <!-- 광고 여부 -->
                <div class="flex items-center gap-2">
                    <input type="checkbox" name="ad_yn" id="ft-ad-yn" class="w-4 h-4 text-yellow-600 rounded">
                    <label for="ft-ad-yn" class="text-sm text-gray-700">광고성 메시지</label>
                    <span class="text-xs text-gray-500">(광고 표시 포함)</span>
                </div>
                <!-- SMS 대체발송 -->
                <div class="bg-gray-50 rounded-lg p-4 space-y-3">
                    <div class="flex items-center gap-2">
                        <input type="checkbox" id="ft-sms-toggle" onchange="toggleSmsSection('ft')" class="w-4 h-4 text-yellow-600 rounded">
                        <label for="ft-sms-toggle" class="text-sm font-medium text-gray-700">SMS 대체발송</label>
                    </div>
                    <div id="ft-sms-fields" class="hidden space-y-3">
                        <input type="text" name="sms_subject" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="SMS 제목">
                        <textarea name="sms_message" rows="3" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm" placeholder="SMS 메시지"></textarea>
                    </div>
                </div>
                <!-- 예약 발송 -->
                <div>
                    <label class="block text-sm font-medium text-gray-600 mb-1">예약 발송</label>
                    <input type="datetime-local" name="reserve_dt" class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm">
                </div>
                <div class="flex justify-end">
                    <button type="submit" class="px-6 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition font-medium 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="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" /></svg>
                        친구톡 발송
                    </button>
                </div>
            </form>
        </div>
    </div>
    @endif
</div>
@endsection

@push('scripts')
<script>
let channelList = [];
let templateCache = {};

function switchTab(tab) {
    document.getElementById('panel-alimtalk').classList.toggle('hidden', tab !== 'alimtalk');
    document.getElementById('panel-friendtalk').classList.toggle('hidden', tab !== 'friendtalk');
    document.getElementById('tab-alimtalk').classList.toggle('border-yellow-500', tab === 'alimtalk');
    document.getElementById('tab-alimtalk').classList.toggle('text-yellow-700', tab === 'alimtalk');
    document.getElementById('tab-alimtalk').classList.toggle('bg-yellow-50/50', tab === 'alimtalk');
    document.getElementById('tab-alimtalk').classList.toggle('border-transparent', tab !== 'alimtalk');
    document.getElementById('tab-alimtalk').classList.toggle('text-gray-500', tab !== 'alimtalk');
    document.getElementById('tab-friendtalk').classList.toggle('border-yellow-500', tab === 'friendtalk');
    document.getElementById('tab-friendtalk').classList.toggle('text-yellow-700', tab === 'friendtalk');
    document.getElementById('tab-friendtalk').classList.toggle('bg-yellow-50/50', tab === 'friendtalk');
    document.getElementById('tab-friendtalk').classList.toggle('border-transparent', tab !== 'friendtalk');
    document.getElementById('tab-friendtalk').classList.toggle('text-gray-500', tab !== 'friendtalk');
}

function toggleSmsSection(prefix) {
    const checked = document.getElementById(prefix + '-sms-toggle').checked;
    document.getElementById(prefix + '-sms-fields').classList.toggle('hidden', !checked);
}

function toggleFtImageFields() {
    const type = document.getElementById('ft-type').value;
    document.getElementById('ft-image-fields').classList.toggle('hidden', type === 'text');
}

function addButton(prefix) {
    const container = document.getElementById(prefix + '-buttons-container');
    const idx = container.children.length;
    const html = '<div class="flex gap-2 items-start bg-white p-3 rounded-lg border"><div class="flex-1 grid grid-cols-2 gap-2"><input type="text" placeholder="버튼명" class="btn-name px-2 py-1 border rounded text-sm"><select class="btn-type px-2 py-1 border rounded text-sm"><option value="WL">웹링크</option><option value="AL">앱링크</option><option value="BK">봇키워드</option><option value="MD">메시지전달</option></select><input type="text" placeholder="URL1" class="btn-url1 px-2 py-1 border rounded text-sm"><input type="text" placeholder="URL2" class="btn-url2 px-2 py-1 border rounded text-sm"></div><button type="button" onclick="this.parentElement.remove()" class="text-red-400 hover:text-red-600 mt-1"><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="M6 18L18 6M6 6l12 12" /></svg></button></div>';
    container.insertAdjacentHTML('beforeend', html);
}

function collectButtons(prefix) {
    const container = document.getElementById(prefix + '-buttons-container');
    const buttons = [];
    if (!container) return buttons;
    container.querySelectorAll(':scope > div').forEach(row => {
        const name = row.querySelector('.btn-name')?.value;
        if (name) {
            buttons.push({
                Name: name,
                ButtonType: row.querySelector('.btn-type')?.value || 'WL',
                Url1: row.querySelector('.btn-url1')?.value || '',
                Url2: row.querySelector('.btn-url2')?.value || '',
            });
        }
    });
    return buttons;
}

function loadChannelSelects() {
    fetch('/api/admin/barobill/kakaotalk/channels', {
        headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(r => r.json())
    .then(data => {
        if (!data.success) return;
        const raw = data.data;
        if (Array.isArray(raw)) channelList = raw;
        else if (raw && raw.KakaotalkChannel) channelList = Array.isArray(raw.KakaotalkChannel) ? raw.KakaotalkChannel : [raw.KakaotalkChannel];
        else if (raw) channelList = [raw];

        ['at-sender-id', 'ft-sender-id'].forEach(id => {
            const sel = document.getElementById(id);
            sel.innerHTML = '<option value="">-- 채널 선택 --</option>';
            channelList.forEach(ch => {
                const opt = document.createElement('option');
                opt.value = ch.ChannelId;
                opt.textContent = ch.ChannelName || ch.ChannelId;
                sel.appendChild(opt);
            });
        });
    });
}

function loadTemplateOptions(prefix) {
    const channelId = document.getElementById(prefix + '-sender-id').value;
    const tplSelect = document.getElementById(prefix + '-template');
    if (!tplSelect) return;

    if (!channelId) {
        tplSelect.innerHTML = '<option value="">채널을 먼저 선택하세요</option>';
        return;
    }

    tplSelect.innerHTML = '<option value="">로딩 중...</option>';

    fetch('/api/admin/barobill/kakaotalk/templates?channel_id=' + encodeURIComponent(channelId), {
        headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(r => r.json())
    .then(data => {
        tplSelect.innerHTML = '<option value="">-- 템플릿 선택 --</option>';
        if (!data.success) {
            console.warn('템플릿 조회 실패:', data.error || data.message || data);
            tplSelect.innerHTML = '<option value="">템플릿 조회 실패</option>';
            return;
        }
        const raw = data.data;
        let items = [];
        if (Array.isArray(raw)) items = raw;
        else if (raw && raw.KakaotalkTemplate) items = Array.isArray(raw.KakaotalkTemplate) ? raw.KakaotalkTemplate : [raw.KakaotalkTemplate];
        else if (raw) items = [raw];

        console.log('템플릿 목록:', items);
        templateCache[channelId] = items;
        items.forEach(tpl => {
            const opt = document.createElement('option');
            opt.value = tpl.TemplateName;
            opt.textContent = tpl.TemplateName;
            tplSelect.appendChild(opt);
        });
    })
    .catch(err => {
        console.error('템플릿 API 오류:', err);
        tplSelect.innerHTML = '<option value="">API 오류: ' + err.message + '</option>';
    });
}

function fillTemplateContent(prefix) {
    const channelId = document.getElementById(prefix + '-sender-id').value;
    const tplName = document.getElementById(prefix + '-template').value;
    if (!channelId || !tplName) return;

    const items = templateCache[channelId] || [];
    const tpl = items.find(t => t.TemplateName === tplName);
    if (tpl) {
        document.getElementById(prefix + '-message').value = tpl.TemplateContent || '';
    }
}

function formatReserveDT(datetimeLocal) {
    if (!datetimeLocal) return '';
    return datetimeLocal.replace(/[-T:]/g, '').substring(0, 14);
}

// 알림톡 발송
document.getElementById('alimtalk-form')?.addEventListener('submit', function(e) {
    e.preventDefault();
    const fd = new FormData(this);
    const buttons = collectButtons('at');

    const body = {
        sender_id: fd.get('sender_id'),
        template_name: fd.get('template_name'),
        receiver_name: fd.get('receiver_name'),
        receiver_num: fd.get('receiver_num'),
        title: fd.get('title') || '',
        message: fd.get('message'),
        sms_message: fd.get('sms_message') || '',
        sms_subject: fd.get('sms_subject') || '',
        reserve_dt: formatReserveDT(fd.get('reserve_dt')),
    };
    if (buttons.length > 0) body.buttons = buttons;

    const btn = this.querySelector('button[type="submit"]');
    btn.disabled = true;
    btn.textContent = '발송 중...';

    fetch('/api/admin/barobill/kakaotalk/send/alimtalk', {
        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(body),
    })
    .then(r => r.json())
    .then(data => {
        btn.disabled = false;
        btn.innerHTML = '<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="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" /></svg> 알림톡 발송';
        if (data.success) {
            alert('알림톡 발송 성공!\n전송키: ' + (data.data || ''));
        } else {
            alert('발송 실패: ' + (data.error || data.message));
        }
    })
    .catch(err => {
        btn.disabled = false;
        btn.innerHTML = '<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="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" /></svg> 알림톡 발송';
        alert('오류: ' + err.message);
    });
});

// 친구톡 발송
document.getElementById('friendtalk-form')?.addEventListener('submit', function(e) {
    e.preventDefault();
    const fd = new FormData(this);
    const ftType = document.getElementById('ft-type').value;
    const buttons = collectButtons('ft');
    const channelId = fd.get('sender_id');

    const body = {
        sender_id: channelId,
        channel_id: channelId,
        receiver_name: fd.get('receiver_name'),
        receiver_num: fd.get('receiver_num'),
        message: fd.get('message'),
        sms_message: fd.get('sms_message') || '',
        sms_subject: fd.get('sms_subject') || '',
        ad_yn: document.getElementById('ft-ad-yn').checked,
        reserve_dt: formatReserveDT(fd.get('reserve_dt')),
    };
    if (buttons.length > 0) body.buttons = buttons;

    let endpoint = '/api/admin/barobill/kakaotalk/send/friendtalk';
    if (ftType === 'image') {
        endpoint = '/api/admin/barobill/kakaotalk/send/friendtalk-image';
        body.image_url = fd.get('image_url');
    } else if (ftType === 'wide') {
        endpoint = '/api/admin/barobill/kakaotalk/send/friendtalk-wide';
        body.image_url = fd.get('image_url');
    }

    const btn = this.querySelector('button[type="submit"]');
    btn.disabled = true;
    btn.textContent = '발송 중...';

    fetch(endpoint, {
        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(body),
    })
    .then(r => r.json())
    .then(data => {
        btn.disabled = false;
        btn.innerHTML = '<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="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" /></svg> 친구톡 발송';
        if (data.success) {
            alert('친구톡 발송 성공!\n전송키: ' + (data.data || ''));
        } else {
            alert('발송 실패: ' + (data.error || data.message));
        }
    })
    .catch(err => {
        btn.disabled = false;
        btn.innerHTML = '<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="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" /></svg> 친구톡 발송';
        alert('오류: ' + err.message);
    });
});

document.addEventListener('DOMContentLoaded', loadChannelSelects);
</script>
@endpush
