@extends('layouts.app')

@section('content')
@php
    // إعدادات التوقيت (آمنة)
    $cfg = [
        'delay'         => (int) \App\Setting::findByKey('whatsapp_marketing_delay', 1),
        'jitter'        => (int) \App\Setting::findByKey('whatsapp_marketing_delay_jitter', 1),
        'batch'         => (int) \App\Setting::findByKey('whatsapp_marketing_batch', 10),
        'pause'         => (int) \App\Setting::findByKey('whatsapp_marketing_pause', 10),
        'max_per_run'   => (int) \App\Setting::findByKey('whatsapp_marketing_max_per_run', 100),
        'session_pause' => (int) \App\Setting::findByKey('whatsapp_marketing_session_pause', 900),
    ];

    $cfg['delay']         = max(0, $cfg['delay']);
    $cfg['jitter']        = max(0, $cfg['jitter']);
    $cfg['batch']         = max(1, $cfg['batch']);
    $cfg['pause']         = max(0, $cfg['pause']);
    $cfg['max_per_run']   = max(1, $cfg['max_per_run']);
    $cfg['session_pause'] = max(0, $cfg['session_pause']);

    // قوائم أولية (آخر 200) لعرض الأرقام التي تم إرسالها/فشلت (عند فتح الصفحة)
    $sentRows = \DB::table('whatsapp_campaign_recipients')
        ->where('campaign_id', (int)$campaign->id)
        ->where('status_label', 'SENT')
        ->orderBy('id', 'desc')
        ->limit(200)
        ->get();

    $failedRows = \DB::table('whatsapp_campaign_recipients')
        ->where('campaign_id', (int)$campaign->id)
        ->where(function ($q) {
            $q->where('status_label', 'FAILED')
              ->orWhere(function ($x) {
                  $x->where('status_label', 'PENDING')
                    ->where('attempts', '>', 0);
              });
        })
        ->orderBy('id', 'desc')
        ->limit(200)
        ->get();
$personIds = collect($sentRows)->pluck('person_id')
        ->merge(collect($failedRows)->pluck('person_id'))
        ->filter()
        ->unique()
        ->values()
        ->all();

    $personNames = [];
    if (count($personIds) > 0) {
        $personNames = \App\Person::whereIn('id', $personIds)->pluck('name', 'id')->toArray();
    }
@endphp

<section class="content-header">
    <h1>حملة واتساب (إرسال يدوي)</h1>
</section>

<section class="content">

    @if(session('success'))
        <div class="alert alert-success">{{ session('success') }}</div>
    @endif
    @if(session('error'))
        <div class="alert alert-danger">{{ session('error') }}</div>
    @endif

    <div class="box box-primary">
        <div class="box-header with-border">
            <div class="pull-right">
                <a href="{{ route('whatsapp.marketing.index') }}" class="btn btn-default">
                    <i class="fa fa-arrow-right"></i> رجوع
                </a>
            </div>
            <h3 class="box-title">
                رقم الحملة: #{{ $campaign->id }}
                <span class="label label-info" style="margin-right:10px;">{{ $campaign->status_label }}</span>
            </h3>
        </div>

        <div class="box-body">

            <div class="row">
                <div class="col-md-6">
                 <div class="callout" style="margin:0; border-left:5px solid #3c8dbc; background:#3c8dbc; color:#fff;">
                        <div style="color:#fff; opacity:.9;">
                            الإرسال يدوي (بدون Cron) — أي إغلاق/تحديث للصفحة يوقف الإرسال.
                        </div>
                        <div style="margin-top:6px;">
                         <div style="margin-top:6px; color:#000; display:inline-block; padding:4px 0; font-weight:700; text-shadow:0 0 2px rgba(255,255,255,.9);">
    Delay: {{ $cfg['delay'] }}s (+Jitter {{ $cfg['jitter'] }}s),
    Batch: {{ $cfg['batch'] }},
    Pause: {{ $cfg['pause'] }}s,
    Max/Run: {{ $cfg['max_per_run'] }},
    SessionPause: {{ $cfg['session_pause'] }}s
</div>
                        </div>
                    </div>
                </div>

                <div class="col-md-6 text-left">
                    <button type="button" id="btnStart" class="btn btn-success">
                        <i class="fa fa-play"></i> بدء / متابعة
                    </button>

                    <form method="post" action="{{ route('whatsapp.marketing.status', $campaign->id) }}" style="display:inline-block;">
                        @csrf
                        <input type="hidden" name="status" value="PAUSED">
                        <button type="submit" class="btn btn-warning">
                            <i class="fa fa-pause"></i> إيقاف مؤقت
                        </button>
                    </form>

                    <form method="post" action="{{ route('whatsapp.marketing.status', $campaign->id) }}" style="display:inline-block;">
                        @csrf
                        <input type="hidden" name="status" value="STOPPED">
                        <button type="submit" class="btn btn-danger" onclick="return confirm('تأكيد إيقاف الحملة؟');">
                            <i class="fa fa-stop"></i> إيقاف نهائي
                        </button>
                    </form>

                    <form method="post" action="{{ route('whatsapp.marketing.resend', $campaign->id) }}" style="display:inline-block;">
                        @csrf
                        <button type="submit" class="btn btn-primary" onclick="return confirm('إعادة تجهيز المتبقي (Pending/Failed)؟');">
                            <i class="fa fa-refresh"></i> إعادة إرسال المتبقي
                        </button>
                    </form>
                </div>
            </div>

            <hr>

            <div class="row">
                <div class="col-md-3">
                    <div class="small-box bg-aqua">
                        <div class="inner">
                            <h3 id="st_total">{{ $stats['total'] ?? 0 }}</h3>
                            <p>الإجمالي</p>
                        </div>
                        <div class="icon"><i class="fa fa-list"></i></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="small-box bg-yellow">
                        <div class="inner">
                            <h3 id="st_pending">{{ $stats['pending'] ?? 0 }}</h3>
                            <p>بانتظار</p>
                        </div>
                        <div class="icon"><i class="fa fa-clock-o"></i></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="small-box bg-green">
                        <div class="inner">
                            <h3 id="st_sent">{{ $stats['sent'] ?? 0 }}</h3>
                            <p>تم الإرسال</p>
                        </div>
                        <div class="icon"><i class="fa fa-paper-plane"></i></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="small-box bg-red">
                        <div class="inner">
                            <h3 id="st_failed">{{ $stats['failed'] ?? 0 }}</h3>
                            <p>فشل</p>
                        </div>
                        <div class="icon"><i class="fa fa-times"></i></div>
                    </div>
                </div>
            </div>

            {{-- جداول SENT / FAILED --}}
            <div class="row">
                <div class="col-md-6">
                    <div class="box box-success">
                        <div class="box-header with-border">
                            <h3 class="box-title">تم الإرسال (آخر {{ count($sentRows) }})</h3>
                        </div>
                        <div class="box-body table-responsive" style="max-height:240px; overflow:auto;">
                            <table class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th style="width:60px;">#</th>
                                        <th>الاسم</th>
                                        <th>الرقم</th>
                                        <th style="width:170px;">وقت الإرسال</th>
                                    </tr>
                                </thead>
                                <tbody id="sentBody">
                                    @forelse($sentRows as $r)
                                        <tr>
                                            <td>{{ $r->id }}</td>
                                            <td>{{ $personNames[$r->person_id] ?? '-' }}</td>
                                            <td>{{ $r->to }}</td>
                                            <td>{{ $r->sent_at ?? '-' }}</td>
                                        </tr>
                                    @empty
                                        <tr><td colspan="4" class="text-muted">لا يوجد.</td></tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="box box-danger">
                        <div class="box-header with-border">
                            <h3 class="box-title">فشل الإرسال (آخر {{ count($failedRows) }})</h3>
                        </div>
                        <div class="box-body table-responsive" style="max-height:240px; overflow:auto;">
                            <table class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th style="width:60px;">#</th>
                                        <th>الاسم</th>
                                        <th>الرقم</th>
                                        <th style="width:90px;">النوع</th>
                                        <th>السبب</th>
                                        <th style="width:70px;">محاولات</th>
                                        <th style="width:170px;">المحاولة القادمة</th>
                                    </tr>
                                </thead>
                                <tbody id="failedBody">
                                    @forelse($failedRows as $r)
                                        @php
                                            $typeLabel = ($r->status_label === 'FAILED') ? 'نهائي' : 'مؤقت';
                                            $typeClass = ($r->status_label === 'FAILED') ? 'label label-danger' : 'label label-warning';
                                        @endphp
                                        <tr>
                                            <td>{{ $r->id }}</td>
                                            <td>{{ $personNames[$r->person_id] ?? '-' }}</td>
                                            <td>{{ $r->to }}</td>
                                            <td><span class="{{ $typeClass }}">{{ $typeLabel }}</span></td>
                                            <td>{{ $r->error ?? '-' }}</td>
                                            <td>{{ $r->attempts ?? 0 }}</td>
                                            <td>{{ $r->next_attempt_at ?? '-' }}</td>
                                        </tr>
                                    @empty
                                        <tr><td colspan="7" class="text-muted">لا يوجد.</td></tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            {{-- سجل الإرسال --}}
            <div class="box box-default">
                <div class="box-header with-border">
                    <h3 class="box-title">سجل الإرسال</h3>
                </div>
                <div class="box-body" style="max-height:320px; overflow:auto;" id="logBox">
                    <div class="text-muted">اضغط "بدء / متابعة" لبدء الإرسال.</div>
                </div>
            </div>

        </div>
    </div>

</section>

<script>
(function(){
    var isRunning = false;

    var cfg = {
        delay: {{ (int)$cfg['delay'] }},
        jitter: {{ (int)$cfg['jitter'] }},
        batch: {{ (int)$cfg['batch'] }},
        pause: {{ (int)$cfg['pause'] }},
        maxPerRun: {{ (int)$cfg['max_per_run'] }},
        sessionPause: {{ (int)$cfg['session_pause'] }}
    };

    var csrf = "{{ csrf_token() }}";
    var lockToken = "{{ $lockToken ?? '' }}";
    var sendUrl = "{{ route('whatsapp.marketing.sendNext', $campaign->id) }}";
    var statsUrl = "{{ route('whatsapp.marketing.stats', $campaign->id) }}";

    var sentThisBatch = 0;
    var sentThisRun = 0;

    function stopLoop(){
        isRunning = false;
        window.onbeforeunload = null;
    }

    function logLine(html){
        var box = document.getElementById('logBox');
        if(!box) return;
        var div = document.createElement('div');
        div.innerHTML = html;
        box.appendChild(div);
        box.scrollTop = box.scrollHeight;
    }

    function esc(s){
        if (s === null || s === undefined) return '';
        return String(s)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function prependSentRow(row){
        if(!row) return;
        var tb = document.getElementById('sentBody');
        if(!tb) return;
        var tr = document.createElement('tr');
        tr.innerHTML =
            '<td>'+ esc(row.id ?? '') +'</td>' +
            '<td>'+ esc(row.name ?? '-') +'</td>' +
            '<td>'+ esc(row.to ?? '-') +'</td>' +
            '<td>'+ esc(row.sent_at ?? '-') +'</td>';
        tb.insertBefore(tr, tb.firstChild);
    }

    function prependFailedRow(row){
        if(!row) return;
        var tb = document.getElementById('failedBody');
        if(!tb) return;
        var tr = document.createElement('tr');
                var typeLabel = (row.status_label === 'FAILED') ? 'نهائي' : 'مؤقت';
        var typeClass = (row.status_label === 'FAILED') ? 'label label-danger' : 'label label-warning';
        tr.innerHTML =
            '<td>'+ esc(row.id ?? '') +'</td>' +
            '<td>'+ esc(row.name ?? '-') +'</td>' +
            '<td>'+ esc(row.to ?? '-') +'</td>' +
            '<td><span class="'+typeClass+'">'+esc(typeLabel)+'</span></td>' +
            '<td>'+ esc(row.error ?? '-') +'</td>' +
            '<td>'+ esc(row.attempts ?? 0) +'</td>' +
            '<td>'+ esc(row.next_attempt_at ?? '-') +'</td>';
        tb.insertBefore(tr, tb.firstChild);
    }

    function sleep(ms){ return new Promise(function(res){ setTimeout(res, ms); }); }

    function nextDelayMs(){
        var j = cfg.jitter > 0 ? Math.floor(Math.random() * (cfg.jitter + 1)) : 0;
        return (cfg.delay + j) * 1000;
    }

    async function refreshStats(){
        try{
            var r = await fetch(statsUrl, {credentials:'same-origin'});
            var j = await r.json();
            if(j && j.ok && j.stats){
                document.getElementById('st_total').innerText = j.stats.total;
                document.getElementById('st_pending').innerText = j.stats.pending;
                document.getElementById('st_sent').innerText = j.stats.sent;
                document.getElementById('st_failed').innerText = j.stats.failed;
            }
        }catch(e){}
    }

    async function sendNext(){
        var r = await fetch(sendUrl, {
            method:'POST',
            credentials:'same-origin',
            headers:{
                'Content-Type':'application/json',
                'X-CSRF-TOKEN': csrf
            },
            body: JSON.stringify({lock_token: lockToken})
        });
        return await r.json();
    }

    async function loop(){
        window.onbeforeunload = function(){ return "الإرسال شغال، لا تغلق الصفحة."; };

        while(isRunning){

            if(sentThisRun >= cfg.maxPerRun){
                logLine('<div class="text-warning">وصلنا الحد الأقصى للجلسة ('+cfg.maxPerRun+'). انتظار '+cfg.sessionPause+' ثانية...</div>');
                await sleep(cfg.sessionPause * 1000);
                sentThisRun = 0;
                sentThisBatch = 0;
            }

            var res = null;
            try{
                res = await sendNext();
            }catch(e){
                logLine('<div class="text-danger">فشل اتصال بالسيرفر. إعادة محاولة بعد 5 ثواني...</div>');
                await sleep(5000);
                continue;
            }

            var msg = (res && res.message) ? String(res.message) : '';

            if(res && (res.action === 'done' || msg.indexOf('انتهت الحملة') >= 0)){
                logLine(res.html || '<div class="text-success"><b>انتهت الحملة ✅</b></div>');
                await refreshStats();
                stopLoop();
                break;
            }


            if(res && res.action === 'locked'){
                logLine(res.html || ('<div class="text-danger">خطأ: '+msg+'</div>'));
                stopLoop();
                break;
            }

            if(res && (res.action === 'not_running' || msg.indexOf('ليست قيد التشغيل') >= 0)){
                logLine(res.html || ('<div class="text-danger">خطأ: '+msg+'</div>'));
                logLine('<div class="text-muted">إذا تريد متابعة المتبقي: اضغط "إعادة إرسال المتبقي" ثم "بدء / متابعة".</div>');
                await refreshStats();
                stopLoop();
                break;
            }

            if(res && res.action === 'wait' && res.wait_seconds){
                logLine(res.html || ('<div class="text-warning">انتظار '+res.wait_seconds+' ثانية...</div>'));
                await sleep(parseInt(res.wait_seconds, 10) * 1000);
                continue;
            }

            if(!res || !res.ok){
                logLine('<div class="text-danger">خطأ: '+ (msg || 'غير معروف') +'</div>');
                await refreshStats();
                stopLoop();
                break;
            }

            sentThisBatch++;
            sentThisRun++;

            logLine(res.html || ('<div class="text-muted">'+(msg||'')+'</div>'));

            // تحديث الجداول مباشرة (يعتمد على row من الكنترولر)
            if(res.action === 'sent' && res.row){
                prependSentRow(res.row);
            }
            if(res.action === 'failed' && res.row){
                if(!res.row.status_label) res.row.status_label = 'FAILED';
                prependFailedRow(res.row);
            }

            await refreshStats();

            if(sentThisBatch >= cfg.batch){
                sentThisBatch = 0;
                if(cfg.pause > 0){
                    logLine('<div class="text-warning">فاصل دفعة: '+cfg.pause+' ثانية...</div>');
                    await sleep(cfg.pause * 1000);
                }
            }

            var ms = nextDelayMs();
            if(ms > 0) await sleep(ms);
        }
    }

    var btn = document.getElementById('btnStart');
    if(btn){
        btn.addEventListener('click', function(){
            if(isRunning) return;
            isRunning = true;
            logLine('<div class="text-info">بدأ الإرسال...</div>');
            loop();
        });
    }
})();
</script>
@endsection
