<?php

namespace App\Http\Controllers\API;

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

class TokensAPI extends Controller
{

 /*
  * Get tokens give  a contract ID
  *
  * */
    public function show($contract_id)
    {
        //$token = Tokens::where('contract_id', $contract_id)->with('contract')->get();
        $consumer=Contract::where('rid',$contract_id)->with(['client:rid,name_sh,name_fl'])->select('rid','client_rid')->get();
        $consumerName = $consumer[0]['client']['name_sh'];

        $searchQuota = [];
        $cursor = '0';
        $pattern = 'search_quota:*:'.$consumerName;
        //dd($pattern);
        //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) {
                    $searchQuota[$key] = Redis::get($key);
                }
            }
        } while ($cursor !== '0');
        /*
        *  "search_quota:count:MIKELTD250" => "3"
            "search_quota:max:MIKELTD250" => "6"
        */

        // Return the data as a JSON response
        return response()->json([
            'status' => 'success',
            'data' => $searchQuota,
        ], 200);
    }
}
