@extends('layouts.app')

@section('title', __('whatsapp::lang.whatsapp') . ' — ' . __('whatsapp::lang.outbox'))

@section('content')
<section class="content-header">
    <h1><i class="fab fa-whatsapp"></i> {{ __('whatsapp::lang.whatsapp') }}
        <small>{{ __('whatsapp::lang.outbox') }}</small></h1>
</section>

<section class="content">
    @include('whatsapp::partials._nav')

    <div class="box box-default">
        <div class="box-header with-border">
            <form method="GET" class="form-inline" style="display:inline;">
                <input type="text" name="q" class="form-control input-sm" placeholder="number / text" value="{{ request('q') }}">
                <select name="status" class="form-control input-sm">
                    <option value="">All status</option>
                    @foreach(['pending','queued','sent','delivered','read','failed','received'] as $s)
                        <option value="{{ $s }}" {{ request('status') === $s ? 'selected' : '' }}>{{ __('whatsapp::lang.st_'.$s) }}</option>
                    @endforeach
                </select>
                <select name="direction" class="form-control input-sm">
                    <option value="">All</option>
                    <option value="out" {{ request('direction') === 'out' ? 'selected' : '' }}>Outbound</option>
                    <option value="in" {{ request('direction') === 'in' ? 'selected' : '' }}>Inbound</option>
                </select>
                <button class="btn btn-sm btn-default"><i class="fa fa-filter"></i></button>
            </form>
            <div class="pull-right">
                <button class="btn btn-sm btn-success" data-toggle="modal" data-target="#wa-send"><i class="fa fa-paper-plane"></i> Send</button>
                <form method="POST" action="{{ route('whatsapp.messages.resend_pending') }}" style="display:inline;" onsubmit="return confirm('Re-drive all pending messages now?')">
                    @csrf <button class="btn btn-sm btn-warning"><i class="fa fa-redo"></i> {{ __('whatsapp::lang.resend_pending') }}</button>
                </form>
            </div>
        </div>
        <div class="box-body table-responsive">
            <table class="table table-striped table-condensed">
                <thead><tr>
                    <th>#</th><th>{{ __('whatsapp::lang.direction') }}</th><th>{{ __('whatsapp::lang.to') }}</th>
                    <th>{{ __('whatsapp::lang.body') }}</th><th>{{ __('whatsapp::lang.msg_status') }}</th>
                    <th>{{ __('whatsapp::lang.attempts') }}</th><th>When</th><th></th>
                </tr></thead>
                <tbody>
                @forelse($messages as $m)
                    <tr>
                        <td>{{ $m->id }}</td>
                        <td>{!! $m->direction === 'out' ? '<i class="fa fa-arrow-up text-blue"></i>' : '<i class="fa fa-arrow-down text-green"></i>' !!}</td>
                        <td>{{ $m->wa_id }}</td>
                        <td>{{ Str::limit($m->body, 70) }} @if($m->error)<br><small class="text-red">{{ Str::limit($m->error, 80) }}</small>@endif</td>
                        <td>
                            @php $c = ['pending'=>'default','queued'=>'info','sent'=>'primary','delivered'=>'success','read'=>'success','failed'=>'danger','received'=>'default'][$m->status] ?? 'default'; @endphp
                            <span class="label label-{{ $c }}">{{ __('whatsapp::lang.st_'.$m->status) }}</span>
                        </td>
                        <td>{{ $m->attempts }}</td>
                        <td><small>{{ $m->created_at->diffForHumans() }}</small></td>
                        <td>
                            @if($m->direction === 'out' && in_array($m->status, ['failed','pending']))
                                <form method="POST" action="{{ route('whatsapp.messages.resend', $m->id) }}" style="display:inline;">
                                    @csrf <button class="btn btn-xs btn-warning" title="{{ __('whatsapp::lang.resend') }}"><i class="fa fa-redo"></i></button>
                                </form>
                            @endif
                        </td>
                    </tr>
                @empty
                    <tr><td colspan="8" class="text-center text-muted">No messages.</td></tr>
                @endforelse
                </tbody>
            </table>
        </div>
        <div class="box-footer">{{ $messages->links() }}</div>
    </div>

    <div class="modal fade" id="wa-send" tabindex="-1" role="dialog">
        <div class="modal-dialog"><div class="modal-content">
            <form method="POST" action="{{ route('whatsapp.messages.store') }}">
                @csrf
                <div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Send WhatsApp message</h4></div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>{{ __('whatsapp::lang.channel') }}</label>
                        <select name="channel_id" class="form-control">
                            <option value="">Auto (default / by location)</option>
                            @foreach($channels as $id => $label)
                                <option value="{{ $id }}">{{ $label }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group">
                        <label>{{ __('whatsapp::lang.pick_contact') }}</label>
                        <select id="wa-contact-pick" class="form-control" style="width:100%;"><option></option></select>
                        <small class="text-muted">
                            {{ __('whatsapp::lang.pick_contact_hint') }}
                            <br><i class="fa fa-check-circle" style="color:#00a65a"></i> {{ __('whatsapp::lang.badge_on_wa') }}
                            &nbsp; <i class="fa fa-circle-o" style="color:#999"></i> {{ __('whatsapp::lang.badge_unverified') }}
                        </small>
                    </div>
                    <div class="form-group"><label>{{ __('whatsapp::lang.to') }} *</label>
                        <input type="text" name="to" id="wa-send-to" class="form-control" required placeholder="+20100... {{ __('whatsapp::lang.or_write_number') }}"></div>
                    <div class="form-group">
                        <label>{{ __('whatsapp::lang.insert_template') }}</label>
                        <select id="wa-tpl-picker" class="form-control">
                            <option value="">— {{ __('whatsapp::lang.insert_template') }} —</option>
                            @foreach($templates as $tpl)
                                <option value="{{ $tpl->id }}" data-body="{{ e($tpl->body) }}">{{ $tpl->name }}</option>
                            @endforeach
                        </select>
                        <small class="text-muted">{{ __('whatsapp::lang.template_fill_hint') }}</small>
                    </div>
                    <div class="form-group"><label>{{ __('whatsapp::lang.body') }} *</label>
                        <textarea name="body" id="wa-send-body" rows="4" class="form-control" required></textarea></div>
                </div>
                <div class="modal-footer"><button class="btn btn-success"><i class="fa fa-paper-plane"></i> Send</button></div>
            </form>
        </div></div>
    </div>
</section>
@endsection

@section('javascript')
<script>
(function(){
    // Template → body
    var picker = document.getElementById('wa-tpl-picker');
    var body = document.getElementById('wa-send-body');
    if (picker && body) {
        picker.addEventListener('change', function(){
            var opt = picker.options[picker.selectedIndex];
            var tpl = opt ? opt.getAttribute('data-body') : '';
            if (tpl) {
                body.value = body.value.trim() ? (body.value.replace(/\s+$/,'') + "\n\n" + tpl) : tpl;
                body.focus();
            }
        });
    }

    // Contact picker → fills the "to" field (number stays editable for manual entry).
    // Init when the modal is shown (correct sizing + focus inside a Bootstrap modal).
    function initContactPicker() {
        if (!(window.jQuery && jQuery.fn.select2)) { return; }
        var $el = jQuery('#wa-contact-pick');
        if (!$el.length || $el.hasClass('select2-hidden-accessible')) { return; } // already initialised
        try {
            $el.select2({
                dropdownParent: jQuery('#wa-send'),
                placeholder: "{{ __('whatsapp::lang.pick_contact') }}",
                allowClear: true,
                width: '100%',
                minimumInputLength: 0,
                ajax: {
                    url: "{{ route('whatsapp.contacts.search') }}",
                    dataType: 'json',
                    delay: 250,
                    data: function (params) { return { q: params.term || '' }; },
                    processResults: function (data) { return { results: (data && data.results) || [] }; },
                    cache: true
                },
                templateResult: function (d) {
                    if (!d.id) { return d.text; }
                    var icon = d.available
                        ? '<i class="fa fa-check-circle" title="On WhatsApp" style="color:#00a65a"></i> '
                        : '<i class="fa fa-circle-o" title="WhatsApp not verified yet" style="color:#999"></i> ';
                    var $row = jQuery('<span></span>');
                    $row.append(jQuery(icon));
                    $row.append(jQuery('<span></span>').text(d.text));
                    return $row;
                }
            }).on('select2:select', function (e) {
                var to = document.getElementById('wa-send-to');
                if (to) { to.value = e.params.data.mobile || e.params.data.id || ''; }
            });
        } catch (err) {
            if (window.console) { console.error('WhatsApp contact picker init failed:', err); }
        }
    }

    if (window.jQuery) {
        jQuery('#wa-send').on('shown.bs.modal', initContactPicker);
        initContactPicker(); // also try immediately
    }
})();
</script>
@endsection
