<?php

namespace App\Http\Controllers;

use App\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use App\Services\WasenderApi;

class WhatsappController extends Controller
{
    private function ensureAccess()
    {
        // نفس صلاحية الإعدادات العامة
        if (!auth()->user() || !auth()->user()->can('index SettingController')) {
            abort(403);
        }
    }

    public function settings()
    {
        $this->ensureAccess();

        return view('whatsapp.settings', [
            'whatsapp_enabled'            => Setting::findByKey('whatsapp_enabled', '0'),
            'whatsapp_base_url'           => Setting::findByKey('whatsapp_base_url', 'https://api.wasenderapi.com'),
            'whatsapp_api_key'            => Setting::findByKey('whatsapp_api_key', ''),
            'whatsapp_webhook_secret'     => Setting::findByKey('whatsapp_webhook_secret', ''),

            // Feature toggles
            'whatsapp_auto_welcome'       => Setting::findByKey('whatsapp_auto_welcome', '1'),
            'whatsapp_auto_invoice'       => Setting::findByKey('whatsapp_auto_invoice', '1'),
            'whatsapp_marketing_enabled'  => Setting::findByKey('whatsapp_marketing_enabled', '1'),

        ]);
    }
    
    public function marketingCreateCampaign(Request $request)
    {
        $this->ensureAccess();

        if ((int) Setting::findByKey('whatsapp_marketing_enabled', '0') !== 1) {
            return redirect()->back()->with('error', 'التسويق غير مفعل من الإعدادات');
        }

        // Selected only
        $ids = (array) $request->get('person_ids', []);
        $ids = array_filter(array_map('intval', $ids));
        if (count($ids) === 0) {
            return redirect()->back()->with('error', 'اختر عميل واحد على الأقل');
        }

        $templateId = $request->get('template_id');
        $body = trim((string) $request->get('body'));

        if (empty($templateId) && $body === '') {
            return redirect()->back()->with('error', 'اختر قالب أو اكتب رسالة');
        }

        if (!empty($templateId)) {
            $tpl = DB::table('whatsapp_templates')->where('id', (int) $templateId)->first();
            if (!$tpl) {
                return redirect()->back()->with('error', 'القالب غير موجود');
            }
            $body = (string) $tpl->body;
        }

        $people = \App\Person::where('type', 'client')->whereIn('id', $ids)->get();
        if ($people->count() === 0) {
            return redirect()->back()->with('error', 'لا يوجد عملاء للإرسال');
        }

        $campaignId = DB::table('whatsapp_campaigns')->insertGetId([
            'context'     => 'marketing',
            'title'       => $request->get('title'),
            'template_id' => !empty($templateId) ? (int) $templateId : null,
            'body'        => $body,
            'status_code' => 2,
            'status_label'=> 'RUNNING',
            'next_run_at' => now(),
            'created_by'  => auth()->id(),
            'created_at'  => now(),
            'updated_at'  => now(),
        ]);

        // مرفق واحد للحملة (اختياري)
        $attachmentPath = null;
        $attachmentOriginalName = null;
        $attachmentMime = null;
        $attachmentSize = null;

        if ($request->hasFile('attachment') && $request->file('attachment')->isValid()) {
            $file = $request->file('attachment');

            $ext = strtolower($file->getClientOriginalExtension());
            $allowed = ['pdf', 'png', 'jpg', 'jpeg'];
            if (!in_array($ext, $allowed, true)) {
                return redirect()->back()->with('error', 'صيغة المرفق غير مدعومة (المسموح: PDF / JPG / PNG)');
            }

            if ((int) $file->getSize() > 10 * 1024 * 1024) {
                return redirect()->back()->with('error', 'حجم المرفق كبير (الحد 10MB)');
            }

            $attachmentOriginalName = $file->getClientOriginalName();
            $attachmentMime = $file->getClientMimeType();
            $attachmentSize = (int) $file->getSize();

            $safeName = 'campaign_' . $campaignId . '_' . date('Ymd_His') . '_' . Str::random(6) . '.' . $ext;
            $dir = 'whatsapp/marketing/' . $campaignId;
            $attachmentPath = $file->storeAs($dir, $safeName, 'public');

            DB::table('whatsapp_campaigns')->where('id', $campaignId)->update([
                'attachment_path' => $attachmentPath,
                'attachment_name' => $attachmentOriginalName,
                'attachment_mime' => $attachmentMime,
                'attachment_size' => $attachmentSize,
                'updated_at' => now(),
            ]);
        }

        $minGap = (int) Setting::findByKey('whatsapp_marketing_min_gap_minutes', '1440');
        if ($minGap < 0) $minGap = 0;

        $lastSentMap = [];
        if ($minGap > 0) {
            $lastSentMap = DB::table('whatsapp_campaign_recipients')
                ->select('person_id', DB::raw('MAX(sent_at) as last_sent_at'))
                ->whereIn('person_id', $people->pluck('id')->all())
                ->whereNotNull('sent_at')
                ->groupBy('person_id')
                ->pluck('last_sent_at', 'person_id')
                ->toArray();
        }

        $rows = [];
        $skipped = 0;

        foreach ($people as $p) {
            $seenTo = [];
            $dups = 0;

            $toRaw = trim((string) $p->mobile);
            if ($toRaw === '') {
                $skipped++;
                continue;
            }

            // تطبيع للمنع من التكرار: إزالة غير الأرقام، وإزالة بادئة 00 إن وجدت
            $toDigits = preg_replace('/\D+/', '', $toRaw);
            if (strpos($toDigits, '00') === 0) {
                $toDigits = substr($toDigits, 2);
            }
            $dedupeKey = $toDigits !== '' ? $toDigits : $toRaw;

            if (isset($seenTo[$dedupeKey])) {
                $dups++;
                continue;
            }
            $seenTo[$dedupeKey] = true;

            if ($minGap > 0 && !empty($lastSentMap[$p->id])) {
                $last = \Carbon\Carbon::parse($lastSentMap[$p->id]);
                if (now()->diffInMinutes($last) < $minGap) {
                    $skipped++;
                    continue;
                }
            }

            $rows[] = [
                'campaign_id'     => $campaignId,
                'person_id'       => $p->id,
                'to'              => $toRaw,
                'status_code'     => 1,
                'status_label'    => 'PENDING',
                'attempts'        => 0,
                'next_attempt_at' => null,
                'sent_at'         => null,
                'delivered_at'    => null,
                'api_msg_id'      => null,
                'error'           => null,
                'created_at'      => now(),
                'updated_at'      => now(),
            ];
        }

        if (count($rows) === 0) {
            DB::table('whatsapp_campaigns')->where('id', $campaignId)->update([
                'status_code' => 4,
                'status_label' => 'DONE',
                'run_lock_token' => null,
                'run_lock_until' => null,
                'run_lock_user_id' => null,
                'updated_at' => now(),
            ]);
            return redirect()->route('whatsapp.marketing.index')->with('error', 'لا يوجد مستلمين بعد تطبيق الشروط');
        }

        foreach (array_chunk($rows, 300) as $chunk) {
            DB::table('whatsapp_campaign_recipients')->insert($chunk);
        }

        $msg = 'تم إنشاء الحملة. تم إضافة: ' . count($rows) . '، تم تخطي: ' . $skipped . ' (بسبب منع إعادة الإرسال خلال ' . $minGap . ' دقيقة)';

        return redirect()->route('whatsapp.marketing.campaign', ['id' => $campaignId])
            ->with('success', $msg);
    }
    
    
    public function marketingIndex(Request $request)
{
    $this->ensureAccess();

    // تنظيف تلقائي: أي حملة RUNNING/PAUSED بدون مستلمين PENDING تعتبر منتهية (DONE)
    \DB::table('whatsapp_campaigns')
        ->where('context', 'marketing')
        ->whereIn('status_label', ['RUNNING', 'PAUSED'])
        ->whereNotExists(function ($q) {
            $q->select(\DB::raw(1))
              ->from('whatsapp_campaign_recipients')
              ->whereColumn('whatsapp_campaign_recipients.campaign_id', 'whatsapp_campaigns.id')
              ->where('status_label', 'PENDING');
        })
        ->update([
            'status_code' => 4,
            'status_label' => 'DONE',
            'updated_at' => now(),
        ]);


    if ((int) Setting::findByKey('whatsapp_marketing_enabled', '0') !== 1) {
        return redirect()->back()->with('error', 'التسويق غير مفعل من الإعدادات');
    }

    $q = trim($request->get('q', ''));
    $perPage = (int) $request->get('per_page', 200);
    if ($perPage < 30) $perPage = 30;
    if ($perPage > 500) $perPage = 500;

    $delivered = trim((string) $request->get('delivered', ''));
    if (!in_array($delivered, ['', 'yes', 'no'], true)) $delivered = '';


    $personTable = (new \App\Person)->getTable();

    $people = \App\Person::query()
        ->where('type', 'client')
        ->when($delivered === 'yes', function ($query) use ($personTable) {
            $query->whereRaw("COALESCE((select status_label from whatsapp_campaign_recipients r where r.person_id = {$personTable}.id order by r.id desc limit 1),'') IN ('DELIVERED','READ')");
        })
        ->when($delivered === 'no', function ($query) use ($personTable) {
            $query->whereRaw("COALESCE((select status_label from whatsapp_campaign_recipients r where r.person_id = {$personTable}.id order by r.id desc limit 1),'') NOT IN ('DELIVERED','READ')");
        })
        ->when($q !== '', function ($query) use ($q) {
            $query->where(function ($x) use ($q) {
                $x->where('name', 'like', "%{$q}%")
                    ->orWhere('mobile', 'like', "%{$q}%");
            });
        })
        ->orderBy('id', 'desc')
        ->paginate($perPage);

    
        // قفل عالمي: لا يسمح بتشغيل أكثر من حملة تسويق في نفس الوقت
        $otherRunning = DB::table('whatsapp_campaigns')
            ->where('context', 'marketing')
            ->where('status_label', 'RUNNING')
            ->whereNotNull('run_lock_until')
            ->where('run_lock_until', '>', now())
            ->orderBy('id', 'desc')
            ->first();

        if ($otherRunning) {
            return redirect()->route('whatsapp.marketing.campaign', ['id' => $otherRunning->id])
                ->with('error', 'يوجد حملة تسويق أخرى قيد التشغيل الآن (#'.$otherRunning->id.'). الرجاء إنهاؤها قبل بدء حملة جديدة.');
        }

$personIds = $people->pluck('id')->all();

    // الحملة الشغالة الآن (إن وجدت)
    $activeCampaign = DB::table('whatsapp_campaigns')
        ->whereIn('status_label', ['RUNNING', 'PAUSED'])
        ->orderBy('id', 'desc')
        ->first();

    $recipientRows = collect();

    if ($activeCampaign) {
        $recipientRows = DB::table('whatsapp_campaign_recipients')
            ->where('campaign_id', $activeCampaign->id)
            ->whereIn('person_id', $personIds)
            ->get()
            ->keyBy('person_id');
    } else {
        // آخر رسالة (آخر حملة) لكل عميل
        $lastRecipientIds = DB::table('whatsapp_campaign_recipients')
            ->select('person_id', DB::raw('MAX(id) as last_id'))
            ->whereIn('person_id', $personIds)
            ->groupBy('person_id')
            ->pluck('last_id', 'person_id');

        if ($lastRecipientIds && count($lastRecipientIds->toArray()) > 0) {
            $recipientRows = DB::table('whatsapp_campaign_recipients')
                ->whereIn('id', array_values($lastRecipientIds->toArray()))
                ->get()
                ->keyBy('person_id');
        }
    }

    // كل القوالب (لأنك طلبت تظهر كلها)
    $templates = DB::table('whatsapp_templates')
        ->orderBy('context', 'asc')
        ->orderBy('id', 'desc')
        ->get();

    // آخر الحملات (للاستئناف عند انقطاع الصفحة)
    $campaigns = DB::table('whatsapp_campaigns')
        ->where('context', 'marketing')
        ->orderBy('id', 'desc')
        ->limit(10)
        ->get();

    
    // عدّادات الحملات (مرة واحدة) لعرضها في جدول "آخر حملات التسويق"
    $campaignCounts = [];
    if ($campaigns->count() > 0) {
        $ids = $campaigns->pluck('id')->all();

        $rows = DB::table('whatsapp_campaign_recipients')
            ->selectRaw("
                campaign_id,
                COUNT(*) as total,
                SUM(CASE WHEN status_label='PENDING' THEN 1 ELSE 0 END) as pending,
                SUM(CASE WHEN status_label='SENT' THEN 1 ELSE 0 END) as sent,
                SUM(CASE WHEN status_label='FAILED' THEN 1 ELSE 0 END) as failed,
                SUM(CASE WHEN status_label IN ('DELIVERED','READ') THEN 1 ELSE 0 END) as delivered
            ")
            ->whereIn('campaign_id', $ids)
            ->groupBy('campaign_id')
            ->get();

        foreach ($rows as $r) {
            $campaignCounts[$r->campaign_id] = [
                'total'     => (int)($r->total ?? 0),
                'pending'   => (int)($r->pending ?? 0),
                'sent'      => (int)($r->sent ?? 0),
                'failed'    => (int)($r->failed ?? 0),
                'delivered' => (int)($r->delivered ?? 0),
            ];
        }
    }

return view('whatsapp.marketing', compact('people', 'q', 'templates', 'recipientRows', 'activeCampaign', 'campaigns', 'campaignCounts', 'perPage', 'delivered'));
}


    /**
     * صفحة الحملة (بدون Cron)
     */
    public function marketingCampaign(Request $request, $id)
    {
        $this->ensureAccess();

        $campaign = DB::table('whatsapp_campaigns')->where('id', (int)$id)->first();
        if (!$campaign || $campaign->context !== 'marketing') {
            abort(404);
        }

        $stats = $this->campaignStats((int)$id);

        $settings = [
            'delay'         => (int) Setting::findByKey('whatsapp_marketing_delay', '1'),
            'delay_jitter'  => (int) Setting::findByKey('whatsapp_marketing_delay_jitter', '1'),
            'batch'         => (int) Setting::findByKey('whatsapp_marketing_batch', '10'),
            'pause'         => (int) Setting::findByKey('whatsapp_marketing_pause', '10'),
            'max_retries'   => (int) Setting::findByKey('whatsapp_marketing_max_retries', '2'),
            'retry_delay'   => (int) Setting::findByKey('whatsapp_marketing_retry_delay', '10'),
            'timeout'       => (int) Setting::findByKey('whatsapp_marketing_timeout', '30'),
            'max_per_run'   => (int) Setting::findByKey('whatsapp_marketing_max_per_run', '100'),
            'session_pause' => (int) Setting::findByKey('whatsapp_marketing_session_pause', '900'),
        ];

        $lockToken = Str::random(32);

        return view('whatsapp.marketing_campaign', compact('campaign', 'stats', 'settings', 'lockToken'));
    }

    /**
     * إحصائيات الحملة (AJAX)
     */
    public function marketingCampaignStats(Request $request, $id)
    {
        $this->ensureAccess();

        $campaign = DB::table('whatsapp_campaigns')->where('id', (int)$id)->first();
        if (!$campaign || $campaign->context !== 'marketing') {
            return response()->json(['ok' => false, 'message' => 'الحملة غير موجودة'], 404);
        }

        return response()->json(['ok' => true, 'stats' => $this->campaignStats((int)$id)]);
    }

    /**
     * إرسال التالي (AJAX) - رسالة واحدة فقط
     */
    public function marketingSendNext(Request $request, $id)
    {
        $this->ensureAccess();

        if ((int) Setting::findByKey('whatsapp_enabled', '0') !== 1) {
            return response()->json(['ok' => false, 'message' => 'الواتساب غير مفعّل من الإعدادات'], 400);
        }

        if ((int) Setting::findByKey('whatsapp_marketing_enabled', '0') !== 1) {
            return response()->json(['ok' => false, 'message' => 'التسويق غير مفعل من الإعدادات'], 400);
        }

        $campaign = DB::table('whatsapp_campaigns')->where('id', (int)$id)->first();
        if (!$campaign || $campaign->context !== 'marketing') {
            return response()->json(['ok' => false, 'message' => 'الحملة غير موجودة'], 404);
        }


        // قفل تشغيل الحملة (60 ثانية) لمنع التشغيل من تبويب/جهاز آخر لنفس الحملة
        $lockToken = trim((string) $request->input('lock_token', ''));
        if ($lockToken === '') {
            return response()->json([
                'ok' => false,
                'message' => 'lock_token مفقود',
            ], 400);
        }

        $lockSeconds = 60; // حسب الاتفاق
        $now = now();
        $lockUntil = $now->copy()->addSeconds($lockSeconds);

        $claimedCampaign = DB::table('whatsapp_campaigns')
            ->where('id', (int)$id)
            ->where(function ($q) use ($now, $lockToken) {
                $q->whereNull('run_lock_until')
                  ->orWhere('run_lock_until', '<=', $now)
                  ->orWhere('run_lock_token', '=', $lockToken);
            })
            
            ->whereNotExists(function ($q) use ($id, $now) {
                $q->select(DB::raw(1))
                  ->from('whatsapp_campaigns as c2')
                  ->where('c2.context', 'marketing')
                  ->where('c2.status_label', 'RUNNING')
                  ->whereNotNull('c2.run_lock_until')
                  ->where('c2.run_lock_until', '>', $now)
                  ->where('c2.id', '<>', (int)$id);
            })
->update([
                'run_lock_token' => $lockToken,
                'run_lock_until' => $lockUntil,
                'run_lock_user_id' => auth()->id(),
                'updated_at' => $now,
            ]);

        if ($claimedCampaign === 0) {
            $row = DB::table('whatsapp_campaigns')
                ->select('run_lock_until')
                ->where('context', 'marketing')
                ->where('status_label', 'RUNNING')
                ->whereNotNull('run_lock_until')
                ->where('run_lock_until', '>', $now)
                ->where('id', '<>', (int)$id)
                ->orderBy('run_lock_until', 'asc')
                ->first();
            $wait = $lockSeconds;
            if ($row && !empty($row->run_lock_until)) {
                try {
                    $wait = max(1, $now->diffInSeconds(\Carbon\Carbon::parse($row->run_lock_until)));
                } catch (\Exception $e) {
                    $wait = $lockSeconds;
                }
            }

            return response()->json([
                'ok' => true,
                'action' => 'locked',
                'wait_seconds' => $wait,
                'message' => 'الحملة تعمل في جلسة أخرى',
                'html' => '<div class="text-danger"><b>الحملة تعمل في جلسة أخرى</b> — أغلق التبويب الآخر ثم أعد المحاولة.</div>',
            ]);
        }

        
        // احترام next_run_at (تبريد عام للحملة) — يستخدم خصوصاً عند HTTP 429
        if (!empty($campaign->next_run_at) && now()->lt(\Carbon\Carbon::parse($campaign->next_run_at))) {
            $wait = now()->diffInSeconds(\Carbon\Carbon::parse($campaign->next_run_at));
            return response()->json([
                'ok' => true,
                'action' => 'wait',
                'wait_seconds' => $wait,
                'message' => 'انتظار',
                'html' => '<div class="text-warning">انتظار تبريد الحملة لمدة ' . $wait . ' ثانية...</div>',
            ]);
        }

if (!in_array($campaign->status_label, ['RUNNING'], true)) {
            return response()->json([
                'ok' => true,
                'action' => 'not_running',
                'message' => 'الحملة ليست قيد التشغيل (RUNNING)',
                'html' => '<div class="text-danger">خطأ: الحملة ليست قيد التشغيل (RUNNING)</div>',
            ]);
        }

        $maxRetries = (int) Setting::findByKey('whatsapp_marketing_max_retries', '2');
        $retryDelay = (int) Setting::findByKey('whatsapp_marketing_retry_delay', '10');

        if ($maxRetries < 0) $maxRetries = 0;
        if ($retryDelay < 0) $retryDelay = 0;

        $recipient = DB::table('whatsapp_campaign_recipients')
            ->where('campaign_id', (int)$id)
            ->where(function ($q) use ($maxRetries) {
                $q->where('status_code', 1)
                  ->orWhere(function ($x) use ($maxRetries) {
                      $x->where('status_code', 3)
                        ->where('attempts', '<', $maxRetries);
                  });
            })
            ->where(function ($q) {
                $q->whereNull('next_attempt_at')
                  ->orWhere('next_attempt_at', '<=', now());
            })
            ->orderBy('id', 'asc')
            ->first();

        if (!$recipient) {
            // لو فيه إعادة محاولة مجدولة بالمستقبل => WAIT
            
            $nextAt = DB::table('whatsapp_campaign_recipients')
                ->where('campaign_id', (int)$id)
                ->whereNotNull('next_attempt_at')
                ->where(function ($q) use ($maxRetries) {
                    $q->where('status_code', 1)
                      ->orWhere(function ($x) use ($maxRetries) {
                          $x->where('status_code', 3)
                            ->where('attempts', '<', $maxRetries);
                      });
                })
                ->min('next_attempt_at');
if ($nextAt && now()->lt(\Carbon\Carbon::parse($nextAt))) {
                $wait = now()->diffInSeconds(\Carbon\Carbon::parse($nextAt));
                return response()->json([
                    'ok' => true,
                    'action' => 'wait',
                    'wait_seconds' => $wait,
                    'message' => 'انتظار',
                    'html' => '<div class="text-warning">انتظار إعادة المحاولة بعد ' . $wait . ' ثانية...</div>',
                ]);
            }

            DB::table('whatsapp_campaigns')->where('id', (int)$id)->update([
                'status_code' => 4,
                'status_label' => 'DONE',
                'updated_at' => now(),
            ]);

            return response()->json([
                'ok' => true,
                'action' => 'done',
                'done' => true,
                'message' => 'انتهت الحملة',
                'html' => '<div class="text-success"><b>انتهت الحملة ✅</b></div>',
            ]);
        }


        // منع الإرسال المكرر: نحجز السطر مؤقتاً باستخدام next_attempt_at (قفل بسيط)
        $lockSeconds = 120;
        $claimUntil = now()->addSeconds($lockSeconds);

        $claimed = DB::table('whatsapp_campaign_recipients')
            ->where('id', (int)$recipient->id)
            ->where('campaign_id', (int)$id)
            ->whereIn('status_code', [1, 3])
            ->where(function ($q) {
                $q->whereNull('next_attempt_at')
                  ->orWhere('next_attempt_at', '<=', now());
            })
            ->update([
                'next_attempt_at' => $claimUntil,
                'updated_at' => now(),
            ]);

        if ($claimed === 0) {
            return response()->json([
                'ok' => true,
                'action' => 'wait',
                'wait_seconds' => 1,
                'message' => 'محاولة أخرى',
                'html' => '<div class="text-warning">تم التقاط نفس المستلم في طلب آخر، انتظار 1 ثانية...</div>',
            ]);
        }

        $person = null;
        if (!empty($recipient->person_id)) {
            $person = \App\Person::find((int)$recipient->person_id);
        }

        $name = $person && trim((string)$person->name) !== '' ? trim((string)$person->name) : 'عميلنا الكريم';
        $settingsShared = \View::shared('settings');
        $businessName = '';
        if ($settingsShared) {
            $k = app()->getLocale() == 'ar' ? 'SiteName' : 'SiteName_en';
            $businessName = trim((string)($settingsShared[$k] ?? $settingsShared['SiteName'] ?? ''));
        }
        if ($businessName === '') {
            $k = app()->getLocale() == 'ar' ? 'SiteName' : 'SiteName_en';
            $businessName = trim((string) Setting::findByKey($k, ''));
        }
        if ($businessName === '') {
            $businessName = trim((string) Setting::findByKey('SiteName', ''));
        }
        if ($businessName === '') {
            $businessName = config('app.name', '');
        }

        $today = now()->format('d/m/Y');

        $text = (string) $campaign->body;
        $text = str_ireplace('{name}', $name, $text);
        $text = str_ireplace('{business_name}', $businessName, $text);
        $text = str_ireplace('{today}', $today, $text);
$to = (string) $recipient->to;

        try {
            $api = new WasenderApi();

            $hasAttachment = !empty($campaign->attachment_path);
            $attachmentUrl = null;
            $attachmentFileName = null;

            if ($hasAttachment) {
                $attachmentUrl = url(Storage::url($campaign->attachment_path));
                $attachmentFileName = $campaign->attachment_name ?: basename($campaign->attachment_path);
            }

            $res = $hasAttachment
                ? $api->sendDocument($to, $attachmentUrl, $attachmentFileName, $text)
                : $api->sendText($to, $text);

            $success = (isset($res['body']['success']) && $res['body']['success'] === true);

            $msgId = $res['body']['data']['msgId']
                ?? $res['body']['data']['key']['id']
                ?? $res['body']['data']['id']
                ?? null;

            $attemptsNow = (int)$recipient->attempts + 1;

            $httpCode = (int)($res['http_code'] ?? 0);

            // معالجة خاصة لـ HTTP 429 (Rate Limit): لا نعتبره فشل نهائي، بل تبريد وانتظار
            if (!$success && $httpCode === 429) {
                $cooldown = (int) Setting::findByKey('whatsapp_marketing_session_pause', '900');
                if ($cooldown < 30) $cooldown = 30;

                $nextAt = now()->addSeconds($cooldown);

                // تبريد عام للحملة حتى لا نستمر بإرسال أرقام أخرى ونأخذ 429 متكرر
                DB::table('whatsapp_campaigns')->where('id', (int)$id)->update([
                    'next_run_at' => $nextAt,
                    'updated_at' => now(),
                ]);

                // إعادة جدولة نفس الرقم كمعلّق (PENDING) بدل FAILED
                DB::table('whatsapp_campaign_recipients')->where('id', (int)$recipient->id)->update([
                    'status_code' => 1,
                    'status_label'=> 'PENDING',
                    'attempts'    => $attemptsNow,
                    'api_msg_id'  => $msgId,
                    'error'       => 'HTTP 429',
                    'next_attempt_at' => $nextAt,
                    'updated_at'  => now(),
                ]);

                // Log (WAIT) للمراجعة فقط
                DB::table('whatsapp_logs')->insert([
                    'context'       => 'marketing',
                    'model_type'    => 'App\\Person',
                    'model_id'      => $recipient->person_id,
                    'to'            => $to,
                    'message_type'  => $hasAttachment ? 'document' : 'text',
                    'text'          => $text,
                    'document_url'  => $hasAttachment ? $attachmentUrl : null,
                    'file_name'     => $hasAttachment ? $attachmentFileName : null,
                    'api_msg_id'    => $msgId,
                    'api_key_id'    => null,
                    'status_code'   => 1,
                    'status_label'  => 'WAIT',
                    'payload'       => json_encode($res['payload'] ?? [], JSON_UNESCAPED_UNICODE),
                    'response'      => json_encode($res['body'] ?? [], JSON_UNESCAPED_UNICODE),
                    'error'         => 'HTTP 429',
                    'created_by'    => auth()->id(),
                    'created_at'    => now(),
                    'updated_at'    => now(),
                ]);

                return response()->json([
                    'ok' => true,
                    'action' => 'wait',
                    'wait_seconds' => $cooldown,
                    'message' => 'HTTP 429',
                    'html' => '<div class="text-warning">تم الوصول لحد الإرسال (HTTP 429) — انتظار ' . $cooldown . ' ثانية...</div>',
                ]);
            }


            if ($success) {
                DB::table('whatsapp_campaign_recipients')->where('id', (int)$recipient->id)->update([
                    'status_code' => 2,
                    'status_label'=> 'SENT',
                    'attempts'    => $attemptsNow,
                    'sent_at'     => now(),
                    'api_msg_id'  => $msgId,
                    'error'       => null,
                    'next_attempt_at' => null,
                    'updated_at'  => now(),
                ]);
            } else {
                DB::table('whatsapp_campaign_recipients')->where('id', (int)$recipient->id)->update([
                    'status_code' => 3,
                    'status_label'=> 'FAILED',
                    'attempts'    => $attemptsNow,
                    'api_msg_id'  => $msgId,
                    'error'       => 'HTTP ' . ($res['http_code'] ?? ''),
                    'next_attempt_at' => now()->addSeconds(max(1, $retryDelay)),
                    'updated_at'  => now(),
                ]);
            }

            DB::table('whatsapp_logs')->insert([
                'context'       => 'marketing',
                'model_type'    => 'App\\Person',
                'model_id'      => $recipient->person_id,
                'to'            => $to,
                'message_type'  => $hasAttachment ? 'document' : 'text',
                'text'          => $text,
                'document_url'  => $hasAttachment ? $attachmentUrl : null,
                'file_name'     => $hasAttachment ? $attachmentFileName : null,
                'api_msg_id'    => $msgId,
                'api_key_id'    => null,
                'status_code'   => $success ? 2 : 0,
                'status_label'  => $success ? 'SENT' : 'FAILED',
                'payload'       => json_encode($res['payload'] ?? [], JSON_UNESCAPED_UNICODE),
                'response'      => json_encode($res['body'] ?? [], JSON_UNESCAPED_UNICODE),
                'error'         => $success ? null : ('HTTP ' . ($res['http_code'] ?? '')),
                'created_by'    => auth()->id(),
                'created_at'    => now(),
                'updated_at'    => now(),
            ]);

            return response()->json([
                'ok' => true,
                'action' => $success ? 'sent' : 'failed',
                'sent' => $success,
                'recipient_id' => $recipient->id,
                'person_id' => $recipient->person_id,
                'to' => $to,
                'msgId' => $msgId,
                'message' => $success ? 'تم الإرسال' : 'فشل الإرسال',
                'row' => $success ? [
                    'id' => $recipient->id,
                    'name' => $name,
                    'to' => $to,
                    'sent_at' => now()->toDateTimeString(),
                ] : [
                    'id' => $recipient->id,
                    'name' => $name,
                    'to' => $to,
                    'error' => 'HTTP ' . ($res['http_code'] ?? ''),
                    'attempts' => $attemptsNow,
                ],
            ]);

        } catch (\Exception $e) {
            $attemptsNow = (int)$recipient->attempts + 1;

            DB::table('whatsapp_campaign_recipients')->where('id', (int)$recipient->id)->update([
                'status_code' => 3,
                'status_label' => 'FAILED',
                'attempts' => $attemptsNow,
                'error' => $e->getMessage(),
                'next_attempt_at' => now()->addSeconds(max(1, $retryDelay)),
                'updated_at' => now(),
            ]);

            DB::table('whatsapp_logs')->insert([
                'context'       => 'marketing',
                'model_type'    => 'App\\Person',
                'model_id'      => $recipient->person_id,
                'to'            => $to,
                'message_type'  => 'text',
                'text'          => $text,
                'document_url'  => null,
                'file_name'     => null,
                'api_msg_id'    => null,
                'api_key_id'    => null,
                'status_code'   => 0,
                'status_label'  => 'FAILED',
                'payload'       => null,
                'response'      => null,
                'error'         => $e->getMessage(),
                'created_by'    => auth()->id(),
                'created_at'    => now(),
                'updated_at'    => now(),
            ]);

            return response()->json([
                'ok' => true,
                'action' => 'failed',
                'sent' => false,
                'message' => 'خطأ: ' . $e->getMessage(),
                'row' => [
                    'id' => $recipient->id,
                    'name' => $name,
                    'to' => $to,
                    'error' => $e->getMessage(),
                    'attempts' => $attemptsNow,
                ],
            ]);
        }
    }

    public function marketingCampaignStatus(Request $request, $id)
    {
        $this->ensureAccess();

        $campaign = DB::table('whatsapp_campaigns')->where('id', (int)$id)->first();
        if (!$campaign || $campaign->context !== 'marketing') {
            return redirect()->back()->with('error', 'الحملة غير موجودة');
        }

        $action = trim((string)$request->input('action'));

        
        // توافق مع الواجهة القديمة: ممكن يصلنا status بدل action
        if ($action === '') {
            $status = strtoupper(trim((string)$request->input('status')));
            if ($status === 'PAUSED') $action = 'pause';
            elseif ($status === 'RUNNING') $action = 'resume';
            elseif ($status === 'STOPPED') $action = 'stop';
        }

        if (!in_array($action, ['pause','resume','stop'], true)) {
            return redirect()->back()->with('error', 'أمر غير صحيح');
        }

if ($action === 'pause') {
            DB::table('whatsapp_campaigns')->where('id', (int)$id)->update([
                'status_code' => 3,
                'status_label' => 'PAUSED',
            'run_lock_token' => null,
            'run_lock_until' => null,
            'run_lock_user_id' => null,
                'updated_at' => now(),
            ]);
        } elseif ($action === 'resume') {
            // قفل عالمي: لا تسمح باستئناف/تشغيل حملة إذا توجد حملة أخرى RUNNING ومقفلة
            $other = DB::table('whatsapp_campaigns')
                ->where('context', 'marketing')
                ->where('status_label', 'RUNNING')
                ->whereNotNull('run_lock_until')
                ->where('run_lock_until', '>', now())
                ->where('id', '<>', (int)$id)
                ->orderBy('id', 'desc')
                ->first();

            if ($other) {
                return back()->with('error', 'يوجد حملة تسويق أخرى قيد التشغيل الآن (#'.$other->id.').');
            }


            DB::table('whatsapp_campaigns')->where('id', (int)$id)->update([
                'status_code' => 2,
                'status_label' => 'RUNNING',
                'updated_at' => now(),
            ]);
        } elseif ($action === 'stop') {
            DB::table('whatsapp_campaigns')->where('id', (int)$id)->update([
                'status_code' => 5,
                'status_label' => 'STOPPED',
            'run_lock_token' => null,
            'run_lock_until' => null,
            'run_lock_user_id' => null,
                'updated_at' => now(),
            ]);
        }

        if ($request->wantsJson()) {
            return response()->json(['ok' => true, 'message' => 'تم تحديث حالة الحملة']);
        }

        return redirect()->back()->with('success', 'تم تحديث حالة الحملة');
    }

    public function marketingResendUnsent(Request $request, $id)
    {
        $this->ensureAccess();

        $campaign = DB::table('whatsapp_campaigns')->where('id', (int)$id)->first();
        if (!$campaign || $campaign->context !== 'marketing') {
            return redirect()->back()->with('error', 'الحملة غير موجودة');
        }

        DB::table('whatsapp_campaign_recipients')
            ->where('campaign_id', (int)$id)
            ->whereIn('status_code', [1, 3])
            ->update([
                'status_code' => 1,
                'status_label' => 'PENDING',
                'next_attempt_at' => null,
                'updated_at' => now(),
            ]);

        DB::table('whatsapp_campaigns')->where('id', (int)$id)->update([
            'status_code' => 2,
            'status_label' => 'RUNNING',
            'updated_at' => now(),
        ]);

        if ($request->wantsJson()) {
            return response()->json(['ok' => true, 'message' => 'تم تجهيز المتبقي للإرسال']);
        }

        return redirect()->back()->with('success', 'تم تجهيز المتبقي للإرسال');
    }

    private function campaignStats($campaignId)
    {
        $total = (int) DB::table('whatsapp_campaign_recipients')->where('campaign_id', $campaignId)->count();
        $pending = (int) DB::table('whatsapp_campaign_recipients')->where('campaign_id', $campaignId)->where('status_code', 1)->count();
        $sent = (int) DB::table('whatsapp_campaign_recipients')->where('campaign_id', $campaignId)->where('status_code', 2)->count();
        $failed = (int) DB::table('whatsapp_campaign_recipients')->where('campaign_id', $campaignId)->where('status_code', 3)->count();
        $delivered = (int) DB::table('whatsapp_campaign_recipients')->where('campaign_id', $campaignId)->where('status_code', 4)->count();

        return compact('total', 'pending', 'sent', 'failed', 'delivered');
    }


    public function saveSettings(Request $request)
    {
        $this->ensureAccess();

        // 1) حفظ الإعدادات أولاً (دائمًا)
        $enabled     = $request->input('whatsapp_enabled', '0');
        $baseUrl     = trim((string)$request->input('whatsapp_base_url', ''));
        $apiKey      = trim((string)$request->input('whatsapp_api_key', ''));
        $secret      = trim((string)$request->input('whatsapp_webhook_secret', ''));

        // feature toggles
        $autoWelcome = $request->input('whatsapp_auto_welcome', '0');
        $autoInvoice = $request->input('whatsapp_auto_invoice', '0');
        $marketing   = $request->input('whatsapp_marketing_enabled', '0');

        Setting::updateOrCreate(['key' => 'whatsapp_enabled'],           ['name' => 'whatsapp_enabled', 'value' => $enabled]);
        Setting::updateOrCreate(['key' => 'whatsapp_base_url'],          ['name' => 'whatsapp_base_url', 'value' => $baseUrl]);
        Setting::updateOrCreate(['key' => 'whatsapp_api_key'],           ['name' => 'whatsapp_api_key', 'value' => $apiKey]);
        Setting::updateOrCreate(['key' => 'whatsapp_webhook_secret'],    ['name' => 'whatsapp_webhook_secret', 'value' => $secret]);

        // ✅ مهم: كنت مسجل المتغيرات لكن ما كنت تحفظها في settings
        Setting::updateOrCreate(['key' => 'whatsapp_auto_welcome'],      ['name' => 'whatsapp_auto_welcome', 'value' => $autoWelcome]);
        Setting::updateOrCreate(['key' => 'whatsapp_auto_invoice'],      ['name' => 'whatsapp_auto_invoice', 'value' => $autoInvoice]);
        Setting::updateOrCreate(['key' => 'whatsapp_marketing_enabled'], ['name' => 'whatsapp_marketing_enabled', 'value' => $marketing]);

        // ✅ إعدادات التسويق (بدون Cron)
        $marketingSettings = [
            'whatsapp_marketing_delay' => '1',
            'whatsapp_marketing_delay_jitter' => '1',
            'whatsapp_marketing_batch' => '10',
            'whatsapp_marketing_pause' => '10',
            'whatsapp_marketing_max_retries' => '2',
            'whatsapp_marketing_retry_delay' => '10',
            'whatsapp_marketing_timeout' => '30',
            'whatsapp_marketing_max_per_run' => '100',
            'whatsapp_marketing_session_pause' => '900',
            'whatsapp_marketing_min_gap_minutes' => '1440',
        ];

        foreach ($marketingSettings as $key => $default) {
            if ($request->has($key)) {
                $val = trim((string)$request->input($key, $default));
                if ($val === '' || !is_numeric($val)) {
                    $val = $default;
                }
                Setting::updateOrCreate(['key' => $key], ['name' => $key, 'value' => $val]);
            }
        }

        // لو الضغط كان "حفظ فقط"
        if (!$request->has('do_whatsapp_status') && !$request->has('do_whatsapp_test')) {
            $request->session()->flash('alert-success', 'تم حفظ إعدادات واتساب');
            return back();
        }

        // 2) تنفيذ الأكشن
        try {
            if ($enabled != '1') {
                $request->session()->flash('alert-danger', 'الواتساب غير مفعّل');
                return back()->withInput();
            }

            $api = new WasenderApi();

            // فحص الاتصال
            if ($request->has('do_whatsapp_status')) {
                $res = $api->getStatus();
                $statusText = isset($res['body']['status'])
                    ? $res['body']['status']
                    : json_encode($res['body'], JSON_UNESCAPED_UNICODE);

                $request->session()->flash('alert-success', 'حالة الاتصال: ' . $statusText);
                return back()->withInput();
            }

            // إرسال اختبار
            if ($request->has('do_whatsapp_test')) {
                $to   = trim((string)$request->input('whatsapp_test_to'));
                $text = trim((string)$request->input('whatsapp_test_text'));

                if ($to === '' || $text === '') {
                    $request->session()->flash('alert-danger', 'أدخل رقم المستلم + نص الرسالة');
                    return back()->withInput();
                }

                $res = $api->sendText($to, $text);

                $success = (isset($res['body']['success']) && $res['body']['success'] === true);
                $msgId   = $res['body']['data']['msgId'] ?? null;

                DB::table('whatsapp_logs')->insert([
                    'context'       => 'test',
                    'model_type'    => null,
                    'model_id'      => null,
                    'to'            => $to,
                    'message_type'  => 'text',
                    'text'          => $text,
                    'document_url'  => null,
                    'file_name'     => null,
                    'api_msg_id'    => $msgId,
                    'api_key_id'    => null,
                    'status_code'   => $success ? 2 : 0,
                    'status_label'  => $success ? 'SENT' : 'FAILED',
                    'payload'       => json_encode($res['payload'], JSON_UNESCAPED_UNICODE),
                    'response'      => json_encode($res['body'], JSON_UNESCAPED_UNICODE),
                    'error'         => $success ? null : ('HTTP ' . $res['http_code']),
                    'created_by'    => auth()->id(),
                    'created_at'    => now(),
                    'updated_at'    => now(),
                ]);

                $request->session()->flash(
                    $success ? 'alert-success' : 'alert-danger',
                    $success ? ('تم إرسال رسالة الاختبار. msgId: ' . $msgId) : 'فشل الإرسال، راجع whatsapp_logs'
                );

                return back()->withInput();
            }

        } catch (\Exception $e) {
            $request->session()->flash('alert-danger', 'خطأ واتساب: ' . $e->getMessage());
            return back()->withInput();
        }

        return back()->withInput();
    }

    public function templates(Request $request)
    {
        $this->ensureAccess();

        $q = DB::table('whatsapp_templates')->orderBy('id', 'desc');

        if ($request->filled('context')) {
            $q->where('context', trim($request->context));
        }

        if ($request->filled('active')) {
            $q->where('is_active', (int)$request->active);
        }

        $templates = $q->paginate(30)->appends($request->all());

        $edit = null;
        if ($request->filled('edit')) {
            $edit = DB::table('whatsapp_templates')->where('id', (int)$request->edit)->first();
        }

        return view('whatsapp.templates.index', compact('templates', 'edit'));
    }

    public function saveTemplate(Request $request)
    {
        $this->ensureAccess();

        $data = [
            'name'       => trim((string)$request->input('name')),
            'context'    => trim((string)$request->input('context', 'marketing')),
            'body'       => trim((string)$request->input('body')),
            'is_active'  => (int)$request->input('is_active', 1),
            'updated_at' => now(),
        ];

        if ($data['name'] === '' || $data['body'] === '') {
            $request->session()->flash('alert-danger', 'الاسم ونص الرسالة مطلوبين');
            return back()->withInput();
        }

        $id = (int)$request->input('id');

        if ($id > 0) {
            DB::table('whatsapp_templates')->where('id', $id)->update($data);
            $request->session()->flash('alert-success', 'تم تحديث القالب');
        } else {
            $data['created_by'] = auth()->id();
            $data['created_at'] = now();
            DB::table('whatsapp_templates')->insert($data);
            $request->session()->flash('alert-success', 'تم إضافة القالب');
        }

        return redirect()->route('whatsapp.templates');
    }

    public function deleteTemplate(Request $request, $id)
    {
        $this->ensureAccess();

        DB::table('whatsapp_templates')->where('id', (int)$id)->delete();
        $request->session()->flash('alert-success', 'تم حذف القالب');

        return redirect()->route('whatsapp.templates');
    }

    public function logs(Request $request)
    {
        $this->ensureAccess();

        $q = DB::table('whatsapp_logs')->orderBy('id', 'desc');

        if ($request->filled('to')) {
            $q->where('to', 'like', '%' . trim($request->to) . '%');
        }

        if ($request->filled('status')) {
            $q->where('status_label', trim($request->status));
        }

        if ($request->filled('context')) {
            $q->where('context', trim($request->context));
        }

        $logs = $q->paginate(50)->appends($request->all());

        return view('whatsapp.logs', compact('logs'));
    }

    /**
     * Wasender Webhook endpoint
     * URL: /api/whatsapp/webhook
     */
    /**
     * Webhook من Wasender لتحديث حالات الرسائل (DELIVERED/READ/FAILED...)
     * حماية عبر whatsapp_webhook_secret (يمكن إرساله كـ:
     * - X-Webhook-Signature / X-Wasender-Signature
     * - أو ?secret=... (للاختبار)
     * ويدعم HMAC SHA256 للـ body عند الحاجة.
     */
    public function wasenderWebhook(Request $request)
    {
        $secret = trim((string) Setting::findByKey('whatsapp_webhook_secret', ''));

        // ----- تحقق من التوقيع -----
        if ($secret !== '') {

            $sigHeader = trim((string) $request->header('X-Webhook-Signature'));
            $sigAlt    = trim((string) $request->header('X-Wasender-Signature'));
            $secretQuery  = trim((string) $request->query('secret', ''));
            $secretHeader = trim((string) $request->header('X-Webhook-Secret'));

            $bearer = '';
            $auth = (string) $request->header('Authorization', '');
            if (stripos($auth, 'Bearer ') === 0) {
                $bearer = trim(substr($auth, 7));
            }

            $incoming = $sigHeader !== '' ? $sigHeader
                      : ($sigAlt !== '' ? $sigAlt
                      : ($secretQuery !== '' ? $secretQuery
                      : ($secretHeader !== '' ? $secretHeader
                      : $bearer)));

            $rawBody = (string) $request->getContent();

            // 1) تطابق مباشر مع secret
            $ok = ($incoming !== '' && hash_equals($secret, $incoming));

            // 2) HMAC SHA256 (hex أو base64) على الـ body
            if (!$ok && $incoming !== '') {
                $sigClean = $incoming;
                $sigHex = $sigClean;

                if (stripos($sigHex, 'sha256=') === 0) {
                    $sigHex = substr($sigHex, 7);
                }

                $hmacHex = hash_hmac('sha256', $rawBody, $secret);

                if ($sigHex !== '' && ctype_xdigit($sigHex) && strlen($sigHex) === 64) {
                    $ok = hash_equals(strtolower($hmacHex), strtolower($sigHex));
                } else {
                    // base64 compare (بعض الأنظمة ترسل base64)
                    $hmacB64 = base64_encode(hex2bin($hmacHex));
                    $ok = hash_equals($hmacB64, $sigClean);
                }
            }

            if (!$ok) {
                return response()->json([
                    'error' => 'Invalid signature',
                    'hint'  => 'Send X-Webhook-Signature header (or ?secret=...) matching the configured webhook secret.',
                ], 401);
            }
        }
        $raw = (string) $request->getContent();
file_put_contents(storage_path('logs/wasender_webhook.log'), "[".now()."]\nHEADERS=".json_encode($request->headers->all(), JSON_UNESCAPED_UNICODE)."\nBODY=".$raw."\n\n", FILE_APPEND);


        $payload = $request->all();
        \Log::info('WASENDER_WEBHOOK', $payload);
        
        \Log::info('WASENDER_WEBHOOK_HEADERS', $request->headers->all());
\Log::info('WASENDER_WEBHOOK_PAYLOAD', $payload);


        // ----- استخراج msgId / keyId بشكل مرن -----
        $msgId = data_get($payload, 'msgId')
              ?: data_get($payload, 'data.msgId')
              ?: data_get($payload, 'data.key.id')
              ?: data_get($payload, 'data.keyId')
              ?: data_get($payload, 'message.msgId')
              ?: data_get($payload, 'message.id')
              ?: data_get($payload, 'id');

        // ----- استخراج status -----
        $status = data_get($payload, 'data.update.status');
        if ($status === null) $status = data_get($payload, 'data.status');
        if ($status === null) $status = data_get($payload, 'status');
        if ($status === null) $status = data_get($payload, 'event');
        if ($status === null) $status = data_get($payload, 'type');

        if ($msgId === null || $status === null) {
            return response()->json(['received' => true], 200);
        }

        // تطبيع الحالة
        $label = null;
        $code  = 0;

        if (is_numeric($status)) {
            $status = (int) $status;
            // 0 failed, 1 pending, 2 sent, 3 delivered, 4 read
            $labelMap = [
                0 => 'FAILED',
                1 => 'PENDING',
                2 => 'SENT',
                3 => 'DELIVERED',
                4 => 'READ',
            ];
            $label = $labelMap[$status] ?? null;
            $code  = $status;
        } else {
            $s = strtoupper(trim((string)$status));
            if (strpos($s, 'DELIVER') !== false) $label = 'DELIVERED';
            elseif (strpos($s, 'READ') !== false) $label = 'READ';
            elseif (strpos($s, 'FAIL') !== false) $label = 'FAILED';
            elseif (strpos($s, 'SENT') !== false) $label = 'SENT';
            else $label = null;
        }

        if ($label === null) {
            return response()->json(['received' => true], 200);
        }

        $now = now();

        // تحديث recipients بالـ msgId
        $recUpdate = [
            'status_label' => $label,
            'status_code'  => $code,
            'updated_at'   => $now,
        ];

        if (in_array($label, ['DELIVERED', 'READ'], true)) {
            $recUpdate['delivered_at'] = $now;
            $recUpdate['error'] = null;
        } elseif ($label === 'FAILED') {
            $recUpdate['error'] = 'Webhook: FAILED';
        }

        $updatedRecipients = DB::table('whatsapp_campaign_recipients')
            ->where('api_msg_id', (string)$msgId)
            ->update($recUpdate);

        // تحديث whatsapp_logs
        $logUpdate = [
            'status_label' => $label,
            'status_code'  => $code,
            'response'     => json_encode($payload, JSON_UNESCAPED_UNICODE),
            'updated_at'   => $now,
        ];

        if ($label === 'FAILED') $logUpdate['error'] = 'Webhook: FAILED';
        else $logUpdate['error'] = null;

        $updatedLogs = DB::table('whatsapp_logs')
            ->where('api_msg_id', (string)$msgId)
            ->update($logUpdate);

        // fallback: لو msgId ما طابق (اختلاف شكل key) نجرب تحديث آخر سجل لنفس الرقم خلال 48 ساعة
        if ($updatedRecipients === 0 || $updatedLogs === 0) {
            
            $to = data_get($payload, 'data.to')
               ?: data_get($payload, 'to')
               ?: data_get($payload, 'data.update.key.remoteJid')
               ?: data_get($payload, 'data.update.key.participant')
               ?: data_get($payload, 'data.key.remoteJid')
               ?: data_get($payload, 'data.key.participant');

            $to = trim((string)$to);

            // بعض الأنظمة ترسل JID مثل 9665xxxx@s.whatsapp.net
            $digits = preg_replace('/\D+/', '', $to);
            $candidates = array_values(array_unique(array_filter([
                $to,
                $digits,
                $digits !== '' ? ('+' . $digits) : null,
            ])));

if ($to !== '') {
                // recipients
                if ($updatedRecipients === 0) {
                    DB::table('whatsapp_campaign_recipients')
                        ->whereIn('to', $candidates)
                        ->whereIn('status_label', ['SENT', 'PENDING'])
                        ->whereNotNull('sent_at')
                        ->where('sent_at', '>=', now()->subDays(2))
                        ->orderBy('id', 'desc')
                        ->limit(1)
                        ->update($recUpdate);
                }

                // logs
                if ($updatedLogs === 0) {
                    DB::table('whatsapp_logs')
                        ->whereIn('to', $candidates)
                        ->whereIn('status_label', ['SENT', 'PENDING'])
                        ->where('created_at', '>=', now()->subDays(2))
                        ->orderBy('id', 'desc')
                        ->limit(1)
                        ->update($logUpdate);
                }
            }
        }

        return response()->json(['received' => true], 200);
    }




    
    
    public function marketingDeleteCampaigns(Request $request)
{
    if (!auth()->check() || !auth()->user()->can('index SettingController')) {
        return back()->with('error', 'ليس لديك صلاحية');
    }

    $ids = (array)$request->input('campaign_ids', []);
    $ids = array_filter(array_map('intval', $ids));
    if (count($ids) === 0) return back()->with('error', 'اختر حملة واحدة على الأقل للحذف');

    DB::table('whatsapp_campaign_recipients')->whereIn('campaign_id', $ids)->delete();
    DB::table('whatsapp_campaigns')->whereIn('id', $ids)->delete();

    return back()->with('success', 'تم حذف الحملات المحددة');
}



public function deleteWhatsappLogs(\Illuminate\Http\Request $request)
{
    // مدير فقط (بنفس صلاحية صفحة الإعدادات)
    if (!auth()->check() || !auth()->user()->can('index SettingController')) {
        return back()->with('error', 'ليس لديك صلاحية');
    }

    $ids = (array) $request->input('log_ids', []);
    $ids = array_filter(array_map('intval', $ids));

    if (count($ids) === 0) {
        return back()->with('error', 'اختر سجلات للحذف');
    }

    \DB::table('whatsapp_logs')->whereIn('id', $ids)->delete();

    return back()->with('success', 'تم حذف السجلات المحددة');
}
    
    
    
    
    
    
    
    
    
    
    
    

}