<?php

namespace App\Http\Controllers;

use App\Jobs\ProcessNotification;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class KNotificationController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth:admin']); 
    }

    /**
     * Dispatch a queued job for every KYC-verified user.
     */
    public function notifyAllVerified()
    {
        $count = 0;
        DB::transaction(function () use (&$count) {

            $users = User::where('kyc_status', 1)
                ->where('created_at', '>=', '2025-12-14')
                ->whereNull('ct_setup')
                ->lockForUpdate()
                ->orderBy('id')
                ->take(100)
                ->get();
        
            foreach ($users as $user) {
        
                $user->update([
                    'ct_setup' => now(),
                ]);
        
                ProcessNotification::dispatch($user)
                    ->delay(now()->addSeconds($count * 3600));
        
                $count++;
            }
        });

    
        return response()->json([
            'success' => true,
            'message' => "Queued Telegram notifications for {$count} KYC-verified users.",
            'total'   => $count,
        ]);
        
        
        
        DB::transaction(function () use (&$count) {

            $users = User::where('kyc_status', 1)
                ->where('created_at', '>=', '2025-12-14')
                ->whereNull('ct_setup')
                ->lockForUpdate()
                ->orderBy('id')
                ->take(10)
                ->get();
        
            foreach ($users as $user) {
        
                $user->update([
                    'ct_setup' => now(),
                ]);
        
                ProcessNotification::dispatch($user)
                    ->delay(now()->addSeconds($count * 60));
        
                $count++;
            }
        });

    }

}