@extends('layouts.app')

@section('content')
<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

    @if($errors && $errors->any())
        <div class="alert alert-danger">
            <ul style="margin:0; padding-right:18px;">
                @foreach($errors->all() as $e)
                    <li>{{ $e }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <div class="box box-primary">
        <div class="box-header with-border">
            <div class="row">
                <div class="col-md-6">
                    <form id="filterForm" method="get" action="{{ route('whatsapp.marketing.index') }}" class="form-inline">
                        <input type="text" name="q" value="{{ $q }}" class="form-control" placeholder="بحث بالاسم أو الجوال">
                        <button class="btn btn-default">بحث</button>
</form>
                </div>

                <div class="col-md-6 text-left">
                    @if(!empty($activeCampaign))
                        <span class="label label-warning">يوجد حملة شغّالة الآن (ID: {{ $activeCampaign->id }})</span>
                        <a class="btn btn-xs btn-default" href="{{ route('whatsapp.marketing.campaign', $activeCampaign->id) }}">
                            فتح الحملة
                        </a>
                    @endif
                </div>
            </div>
        </div>

        <form method="post" action="{{ route('whatsapp.marketing.create') }}" id="marketingForm" enctype="multipart/form-data">
            @csrf
            <input type="hidden" name="select_mode" id="select_mode" value="manual">
            <input type="hidden" name="q" value="{{ $q }}">
            <input type="hidden" name="delivered" value="{{ $delivered ?? '' }}">
            <input type="hidden" name="per_page" value="{{ $perPage ?? 200 }}">


            <div class="box-body">

                <div class="row">
                    <div class="col-md-4">
                        <label>القوالب</label>
                        <div class="input-group">
                            <select name="template_id" id="template_id" class="form-control">
                                <option value="">-- اختر قالب (أو اكتب رسالة) --</option>
                                @foreach($templates as $t)
                                    <option value="{{ $t->id }}" data-body="{{ e($t->body) }}">
                                        ({{ $t->context }}) {{ $t->name ?? ('Template #' . $t->id) }}
                                    </option>
                                @endforeach
                            </select>
                            <span class="input-group-btn">
                                <a href="{{ route('whatsapp.templates') }}" class="btn btn-default" title="إدارة القوالب">
                                    <i class="fa fa-file-text-o"></i>
                                </a>
                            </span>
                        </div>
                        <small class="text-muted">المتغيرات: {name} {business_name} {today}</small>
                        <hr style="margin:10px 0;">
                        <label style="margin-top:0;">مرفق (اختياري) — ملف واحد فقط</label>
                        <input type="file" name="attachment" class="form-control" accept=".pdf,.png,.jpg,.jpeg">
                        <small class="text-muted">المسموح: PDF / JPG / PNG — الحد 10MB.</small>

                    </div>

                    <div class="col-md-8">
                        <label>نص الرسالة</label>
                        <textarea name="body" id="body" class="form-control" rows="6"
                                  placeholder="اكتب الرسالة أو اختر قالب ليتم تعبئتها تلقائياً..."></textarea>
                    </div>
                </div>
<hr>

                <div class="row" style="margin-bottom:10px;">
                    <div class="col-md-5">

                        <button type="button" class="btn btn-default" id="btnSelectAll">
                            <i class="fa fa-check-square-o"></i> تحديد الكل (الصفحة)
                        </button>
                        <button type="button" class="btn btn-default" id="btnUnselectAll">
                            <i class="fa fa-square-o"></i> إلغاء التحديد
                        </button>
                        <button type="button" class="btn btn-default" id="btnSelectFiltered">
                            <i class="fa fa-filter"></i> تحديد ضمن الفلتر
                        </button>

                    
                    </div>

                    <div class="col-md-4">
                        <div class="form-inline">
                            <select name="delivered" form="filterForm" class="form-control">
                                <option value="" {{ ($delivered ?? '')=='' ? 'selected' : '' }}>كل الحالات</option>
                                <option value="yes" {{ ($delivered ?? '')=='yes' ? 'selected' : '' }}>تم الاستلام</option>
                                <option value="no"  {{ ($delivered ?? '')=='no'  ? 'selected' : '' }}>لم يتم</option>
                            </select>

                            <select name="per_page" form="filterForm" class="form-control">
                                <option value="30"  {{ (int)($perPage ?? 200)==30  ? 'selected' : '' }}>30</option>
                                <option value="50"  {{ (int)($perPage ?? 200)==50  ? 'selected' : '' }}>50</option>
                                <option value="100" {{ (int)($perPage ?? 200)==100 ? 'selected' : '' }}>100</option>
                                <option value="200" {{ (int)($perPage ?? 200)==200 ? 'selected' : '' }}>200</option>
                            </select>

                            <button type="submit" form="filterForm" class="btn btn-default">
                                تطبيق
                            </button>
                        </div>
                    </div>

                    <div class="col-md-3 text-left">

                        <div class="alert alert-info" style="padding:6px 10px; margin:0;">
                            محدد: <strong id="selectedCount">0</strong>
                            من <strong id="pageCount">{{ $people->count() }}</strong>
                            (إجمالي النتائج: <strong>{{ $people->total() }}</strong>)
                        
                    </div>
                </div>
                </div>

                <div class="table-responsive" style="max-height:520px; overflow:auto;">
                    <table class="table table-bordered table-striped">
                        <thead>
                        <tr>
                            <th style="width:30px;"></th>
                            <th>الاسم</th>
                            <th>الجوال</th>
                            <th>آخر إرسال</th>
                            <th>تم الاستلام؟</th>
                        </tr>
                        </thead>
                        <tbody>
                        @foreach($people as $p)
                            @php
                                $r = isset($recipientRows[$p->id]) ? $recipientRows[$p->id] : null;
                                $lastSent = $r ? ($r->sent_at ?: null) : null;
                                $delivered = $r ? in_array($r->status_label, ['DELIVERED','READ']) : false;
                            @endphp
                            <tr>
                                <td><input type="checkbox" class="ck" name="person_ids[]" value="{{ $p->id }}"></td>
                                <td>{{ $p->name }}</td>
                                <td>{{ $p->mobile }}</td>
                                <td>{{ $lastSent ?: '-' }}</td>
                                <td>
                                    @if($r)
                                        {!! $delivered ? '<span class="label label-success">نعم</span>' : '<span class="label label-default">لا</span>' !!}
                                    @else
                                        <span class="text-muted">-</span>
                                    @endif
                                </td>
                            </tr>
                        @endforeach
                        </tbody>
                    </table>
                </div>

                {{ $people->appends(['q' => $q, 'delivered' => ($delivered ?? ''), 'per_page' => ($perPage ?? 50)])->links() }}

            </div>

            <div class="box-footer">
                <button class="btn btn-primary">
                    <i class="fa fa-play"></i> بدء حملة (للمحددين فقط)
                </button>
            </div>
        </form>
    </div>

    {{-- آخر حملات التسويق + حذف المحدد --}}
    @if(isset($campaigns) && $campaigns)
        <div class="box box-default">
            <div class="box-header with-border">
                <h3 class="box-title"> آخر حملات التسويق </h3>
            </div>
            <form method="post" action="{{ route('whatsapp.marketing.deleteCampaigns') }}" onsubmit="return confirm('تأكيد حذف الحملات المحددة؟ سيتم حذف المستلمين معها.');">
                @csrf
                <div class="box-body table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                        <tr>
                            <th style="width:30px;"><input type="checkbox" id="ckCampAll"></th>
                            <th>ID</th>
                            <th>الحالة</th>
                            <th>التاريخ</th>
                            <th>الإجمالي</th>
                            <th>بانتظار</th>
                            <th>تم الإرسال</th>
                            <th>فشل</th>
                            <th>استلام</th>
                            <th style="width:110px;">فتح</th>
                        </tr>
                        </thead>
                        <tbody>
                        @forelse($campaigns as $camp)
                            @php
                                $cnt = $campaignCounts[$camp->id] ?? ['total'=>0,'pending'=>0,'sent'=>0,'failed'=>0,'delivered'=>0];
                            @endphp
                            <tr>
                                <td><input type="checkbox" class="ckCamp" name="campaign_ids[]" value="{{ $camp->id }}"></td>
                                <td>#{{ $camp->id }}</td>
                                <td><span class="label label-info">{{ $camp->status_label }}</span></td>
                                <td>{{ $camp->created_at }}</td>
                                <td>{{ $cnt['total'] }}</td>
                                <td>{{ $cnt['pending'] }}</td>
                                <td>{{ $cnt['sent'] }}</td>
                                <td>{{ $cnt['failed'] }}</td>
                                <td>{{ $cnt['delivered'] }}</td>
                                <td><a class="btn btn-xs btn-primary" href="{{ route('whatsapp.marketing.campaign', $camp->id) }}">فتح</a></td>
                            </tr>
                        @empty
                            <tr><td colspan="10" class="text-muted">لا توجد حملات بعد.</td></tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>

                <div class="box-footer">
                    <button class="btn btn-danger">
                        <i class="fa fa-trash"></i> حذف المحدد
                    </button>
                </div>
            </form>
        </div>
    @endif

</section>

<script>
(function(){
    function updateSelectedCount(){
        var count = document.querySelectorAll('.ck:checked').length;
        var el = document.getElementById('selectedCount');
        if(el) el.textContent = count;
    }

    document.getElementById('btnSelectAll')?.addEventListener('click', function(){
        document.querySelectorAll('.ck').forEach(function(x){ x.checked = true; });
updateSelectedCount();
    });

    document.getElementById('btnUnselectAll')?.addEventListener('click', function(){
        document.querySelectorAll('.ck').forEach(function(x){ x.checked = false; });
    
    // تحديد ضمن الفلتر الحالي (بدون checkbox)
    document.getElementById('btnSelectFiltered')?.addEventListener('click', function(){
        var sm = document.getElementById('select_mode');
        if(sm) sm.value = 'filtered';

        // إزالة أي تحديد يدوي للوضوح
        document.querySelectorAll('.ck').forEach(function(x){ x.checked = false; });
        updateSelectedCount();

        alert('تم اختيار: تحديد ضمن الفلتر الحالي. اضغط "بدء حملة" للمتابعة.');
    });

    // إذا المستخدم بدأ يحدد يدويًا: نرجع للوضع manual
    document.querySelectorAll('.ck').forEach(function(x){
        x.addEventListener('change', function(){
            var sm = document.getElementById('select_mode');
            if(sm) sm.value = 'manual';
        });
    });

    document.getElementById('btnSelectAll')?.addEventListener('click', function(){
        var sm = document.getElementById('select_mode');
        if(sm) sm.value = 'manual';
    });

    document.getElementById('btnUnselectAll')?.addEventListener('click', function(){
        var sm = document.getElementById('select_mode');
        if(sm) sm.value = 'manual';
    });


    updateSelectedCount();
    });

    document.querySelectorAll('.ck').forEach(function(x){
        x.addEventListener('change', updateSelectedCount);
    });

    document.getElementById('template_id')?.addEventListener('change', function(){
        var opt = this.options[this.selectedIndex];
        var body = opt ? (opt.getAttribute('data-body') || '') : '';
        if(body !== '') document.getElementById('body').value = body;
    });

    document.getElementById('ckCampAll')?.addEventListener('change', function(){
        var on = this.checked;
        document.querySelectorAll('.ckCamp').forEach(function(x){ x.checked = on; });
    });

    updateSelectedCount();
})();
</script>
@endsection
