<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\Contract;
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:*';
        //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');

        $counts = [];
        foreach ($searchQuotas as $key => $value) {
            if (str_contains($key, 'search_quota:count:')) {
                $clientName = str_replace('search_quota:count:', '', $key);
                $counts[$clientName] = $value;
            }
        }
// Update the Tokens table
        foreach ($counts as $clientName => $usedTokens) {
            $clients_found = Client::where('name_sh', $clientName)->first();
            if($clients_found){
                $contract = Contract::where('client_rid', $clients_found->rid)->first();

                if ($contract) {
                    $updated = Tokens::where('CONTRACT_ID', $contract->rid)->update(['USED_TOKENS' => $usedTokens]);
                }
            }
        }
        $tokens = Tokens::with('contract.client')->get();
        return view('tokens.tokens', [
            'tokens' => $tokens,
        ]);
    }
   /* 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()
    {

    }

}
