<?php

namespace App\Http\Controllers;

use App\Models\Tokens;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class TokensController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $searchQuotas = [];
        $cursor = '0';
        $pattern = 'search_quota:count:*';
        //dump("Keys from KEYS:", Redis::keys($pattern));
        do {
            $result = Redis::scan($cursor, 'MATCH', $pattern, 'COUNT', 10);
            $cursor = $result[0];  // Update cursor for the next iteration
            $keys = $result[1];

            if (!empty($keys)) {
                foreach ($keys as $key) {
                    $searchQuotas[$key] = Redis::get($key);
                }
            }
        } while ($cursor !== '0');
        dump("Keys from SCAN:", $searchQuotas);
        $tokens = Tokens::with('contract.client')->get();
        return view('tokens.tokens', [
            'tokens' => $tokens,
            'searchQuotas' => $searchQuotas
        ]);
    }
   /* public function index()
    {
        // Get all keys matching the pattern search_quota:count:*
        $pattern = 'search_quota:count:*';
        $keys = Redis::keys($pattern);
        // Initialize an array to store key-value pairs
        $searchQuotas = [];
        // Fetch values for each key
        foreach ($keys as $key) {
            // Remove any Redis prefix if present (depends on your Redis configuration)
            $cleanKey = str_replace(Redis::connection()->getName() . '::', '', $key);
            $value = Redis::get($key);
            $searchQuotas[$cleanKey] = $value;
        }
        // Fetch tokens data
        $tokens = Tokens::with('contract.client')->get();

        // Return view with both tokens and search quotas
        return view('tokens.tokens', [
            'tokens' => $tokens,
            'searchQuotas' => $searchQuotas
        ]);
    }*/
    /**
     * Display the specified resource.
     * show ($contract_id)
     */
    public function show ($contract_id)
    {
       // $token = Tokens::with('contract')->get();
        $token = Tokens::where('contract_id', $contract_id)->with('contract')->get();
        // Return the data as a JSON response
        return response()->json([
            'status' => 'success',
            'data' => $token,
        ], 200);
    }

    private  function updateTokens()
    {

    }

}
