@extends('layouts.dash')

@section('title', 'Support')

@section('content')
<style>
    .fc-user-support{max-width:1120px;margin:0 auto;padding:18px}.fc-user-grid{display:grid;grid-template-columns:340px 1fr;gap:18px}.fc-user-card{background:#fff;border:1px solid #e9eef5;border-radius:10px;box-shadow:0 12px 28px rgba(15,23,42,.06);padding:18px}.fc-user-card h4{font-weight:800;color:#172b4d;margin-bottom:10px}.fc-user-card label{font-size:12px;font-weight:800;color:#64748b}.fc-user-card .form-control{border-radius:10px}.fc-ticket-list{display:flex;flex-direction:column;gap:10px}.fc-ticket-item{border:1px solid #e5eaf1;border-radius:10px;padding:12px;display:flex;align-items:center;justify-content:space-between;gap:12px}.fc-ticket-item strong{color:#172b4d}.fc-ticket-meta{font-size:12px;color:#64748b}.fc-ticket-pill{border-radius:999px;padding:4px 8px;background:#eef4ff;color:#145ea8;font-size:11px;font-weight:800}.fc-user-modal .modal-dialog{max-width:720px}.fc-user-stream{padding:16px;display:flex;flex-direction:column;gap:10px;max-height:360px;overflow:auto}.fc-user-chat-row{display:flex;gap:8px;align-items:flex-end}.fc-user-chat-row.support{justify-content:flex-end}.fc-user-avatar{width:32px;height:32px;border-radius:999px;background:#e8f1ff;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:800;color:#145ea8;overflow:hidden;flex:0 0 auto}.fc-user-avatar img{width:100%;height:100%;object-fit:cover}.fc-user-bubble{max-width:78%;border:1px solid #dbe5ef;border-radius:14px;padding:10px 12px;color:#102229;font-size:13px;line-height:1.45;background:#f8fafc}.fc-user-chat-row.support .fc-user-bubble{background:#eaf3ff;border-color:#c7d9f5}.fc-user-meta{font-size:11px;opacity:.72;margin-top:5px}.fc-user-composer{border-top:1px solid #e5eaf1;padding:12px;display:grid;grid-template-columns:42px 1fr 88px;gap:8px}.fc-user-attach{height:42px;border:1px solid #d7e2e8;border-radius:10px;display:flex;align-items:center;justify-content:center;position:relative;overflow:hidden;cursor:pointer}.fc-user-attach input{position:absolute;inset:0;opacity:0;cursor:pointer}.fc-user-composer textarea{height:42px;resize:vertical;border-radius:10px}@media(max-width:900px){.fc-user-grid{grid-template-columns:1fr}.fc-user-support{padding:12px}.fc-user-composer{grid-template-columns:42px 1fr}.fc-user-composer button{grid-column:1/-1}}
</style>

<div class="fc-user-support">
    @if(session('success'))
        <div class="alert alert-success">{{ session('success') }}</div>
    @endif
    <div class="fc-user-grid">
        <form class="fc-user-card" action="{{ route('support.create') }}" method="POST">
            @csrf
            <h4>Create Ticket</h4>
            <div class="form-group">
                <label>Department</label>
                <select name="department" class="form-control" required>
                    @foreach($departments as $department)
                        @if($department !== 'General Enquiry')
                            <option>{{ $department }}</option>
                        @endif
                    @endforeach
                </select>
            </div>
            <div class="form-group">
                <label>Message</label>
                <textarea name="message" class="form-control" rows="5" required></textarea>
            </div>
            <button class="btn btn-primary btn-block" type="submit">Send Ticket</button>
        </form>
        <div class="fc-user-card">
            <h4>Your Tickets</h4>
            <div class="fc-ticket-list">
                @forelse($tickets as $ticket)
                    <div class="fc-ticket-item">
                        <div>
                            <strong>{{ $ticket->ticketid }}</strong>
                            <div class="fc-ticket-meta">{{ $ticket->department }} - {{ $ticket->datecreated }}</div>
                        </div>
                        <div class="d-flex align-items-center" style="gap:8px;">
                            <span class="fc-ticket-pill">{{ $ticket->status }}</span>
                            <button type="button" class="btn btn-sm btn-primary js-user-chat-open" data-ticket="{{ $ticket->ticketid }}">Open</button>
                        </div>
                    </div>
                @empty
                    <div class="text-muted">No support ticket yet.</div>
                @endforelse
            </div>
        </div>
    </div>
</div>

<div class="modal fade fc-user-modal" id="fcUserSupportModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header" style="background:#12385f;color:#fff;">
                <div>
                    <h5 class="modal-title mb-0" id="fcUserTicketTitle">Support Chat</h5>
                    <small id="fcUserTicketSub" style="opacity:.82;"></small>
                </div>
                <button type="button" class="close text-white" data-dismiss="modal" data-bs-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="fc-user-stream" id="fcUserStream"></div>
            <div class="fc-user-composer">
                <label class="fc-user-attach" title="Attach file">&#128206;<input type="file" id="fcUserAttachment" accept=".pdf,.png,.jpg,.jpeg,.gif,.webp,.txt,.doc,.docx,.xls,.xlsx,.csv,.zip"></label>
                <textarea class="form-control" id="fcUserReplyText" placeholder="Type your reply"></textarea>
                <button class="btn btn-primary" type="button" id="fcUserSendReply">Send</button>
            </div>
            <div class="px-3 pb-3 small text-muted" id="fcUserReplyResult"></div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){
    var activeTicket='',timer=null,supportAvatar=@json($supportAvatarUrl),csrf=(document.querySelector('meta[name="csrf-token"]')||{}).content||'',modalEl=document.getElementById('fcUserSupportModal'),bsModal=null,stream=document.getElementById('fcUserStream'),result=document.getElementById('fcUserReplyResult');
    function showModal(){if(window.bootstrap&&bootstrap.Modal){bsModal=bsModal||new bootstrap.Modal(modalEl);bsModal.show();}else if(window.jQuery&&jQuery.fn.modal){jQuery(modalEl).modal('show');}else{modalEl.style.display='block';modalEl.classList.add('show');}}
    function esc(v){return String(v||'').replace(/[&<>"']/g,function(m){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[m];});}
    function avatar(side){if(side==='support'&&supportAvatar){return '<span class="fc-user-avatar"><img src="'+esc(supportAvatar)+'" alt=""></span>';}return '<span class="fc-user-avatar">'+(side==='support'?'CC':'YU')+'</span>';}
    function render(data){if(!data||!data.success)return;supportAvatar=data.support_avatar_url||supportAvatar;document.getElementById('fcUserTicketTitle').textContent=data.ticket.department||'Support Chat';document.getElementById('fcUserTicketSub').textContent=data.ticket.ticket_id+' - '+data.ticket.status;stream.innerHTML=(data.rows||[]).map(function(row){var sup=row.side==='support',att=row.attachment_url?'<div class="fc-user-meta"><a href="'+esc(row.attachment_url)+'" target="_blank">Attachment'+(row.attachment_ext?' ('+esc(row.attachment_ext.toUpperCase())+')':'')+'</a></div>':'';return '<div class="fc-user-chat-row '+(sup?'support':'user')+'">'+(!sup?avatar('user'):'')+'<div class="fc-user-bubble">'+esc(row.message)+att+'<div class="fc-user-meta">'+esc(row.author)+' - '+esc(row.datecreated)+'</div></div>'+(sup?avatar('support'):'')+'</div>';}).join('');stream.scrollTop=stream.scrollHeight;}
    function load(){if(!activeTicket)return;fetch('{{ route('support.thread') }}?ticket_id='+encodeURIComponent(activeTicket),{headers:{'Accept':'application/json'}}).then(function(r){return r.json();}).then(render);}
    document.addEventListener('click',function(e){var btn=e.target.closest('.js-user-chat-open');if(!btn)return;activeTicket=btn.getAttribute('data-ticket');result.textContent='';showModal();load();if(timer)clearInterval(timer);timer=setInterval(load,4000);});
    modalEl.addEventListener('hidden.bs.modal',function(){if(timer)clearInterval(timer);timer=null;});
    modalEl.querySelector('[data-bs-dismiss], [data-dismiss]').addEventListener('click',function(){if(timer)clearInterval(timer);timer=null;});
    document.getElementById('fcUserSendReply').addEventListener('click',function(){var fd=new FormData();fd.append('ticket_id',activeTicket);fd.append('message',document.getElementById('fcUserReplyText').value||'');var file=document.getElementById('fcUserAttachment').files[0];if(file)fd.append('attachment',file);this.disabled=true;result.textContent='Sending...';fetch('{{ route('support.reply') }}',{method:'POST',headers:{'X-CSRF-TOKEN':csrf,'Accept':'application/json'},body:fd}).then(function(r){return r.json();}).then(function(data){if(!data.success){result.textContent=data.error||'Send failed.';return;}document.getElementById('fcUserReplyText').value='';document.getElementById('fcUserAttachment').value='';result.textContent='Reply sent.';render(data.thread);}).catch(function(){result.textContent='Send failed.';}).finally(function(){document.getElementById('fcUserSendReply').disabled=false;});
    });
});
</script>
@endsection
