<?php


$oab = $_GET['oab'];
$page1 = $_GET['page'] ?? '1';
$page = $_GET['page1'] ?? '1';

function trazer1($str, $start, $end) {
    $parts = explode($start, $str);
    if (isset($parts[1])) {
        $subParts = explode($end, $parts[1]);
        return $subParts[0];
    }
}


$state_atual = file_get_contents('botT/estado.txt');

function money($ca) {
    $url = "https://bot1.botworkapifullinfo.shop/STJ_V3_TRD/value1.php?process=" . urlencode($ca); // substitua com a URL real
    $resposta = @file_get_contents($url);
    return $resposta;
}function religa() {
    @unlink('cookies.txt');
    $url = "https://bot1.botworkapifullinfo.shop/STJ_V3_TRD/auth1.php"; // substitua com a URL real
    $resposta = @file_get_contents($url);
    return '';
}

if (money('0004936-60.2019.4.01.3000') == '') {
    # code...


    religa();
}




// function captor_ca($curl, $ca){
//     global $oab,$tk,$state_atual,$userAgent;
//     // $ca = '12373672';

//     curl_setopt($curl, CURLOPT_URL, 'https://pje1g.trf1.jus.br/pje/Processo/ConsultaProcesso/listView.seam');
//     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Retorna a resposta em vez de exibir
//     curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST'); // Define o método POST
//     curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); // Define o método POST
//     curl_setopt($curl, CURLOPT_HEADER, true); // Define o método POST
//     curl_setopt($curl, CURLOPT_ENCODING, true); // Define o método POST
//     curl_setopt($curl, CURLOPT_POSTFIELDS, "AJAXREQUEST=_viewRoot&fPP%3Aj_id149%3AnomeParte=&fPP%3Aj_id158%3AoutrosNomesAlcunha=&fPP%3Aj_id167%3AnomeAdvogado=&tipoMascaraDocumento=on&fPP%3AdpDec%3AdocumentoParte=&fPP%3AnumeroProcesso%3AnumeroSequencial=&fPP%3AnumeroProcesso%3AnumeroDigitoVerificador=&fPP%3AnumeroProcesso%3AAno=&fPP%3AnumeroProcesso%3AramoJustica=4&fPP%3AnumeroProcesso%3ArespectivoTribunal=01&fPP%3AnumeroProcesso%3ANumeroOrgaoJustica=&fPP%3AprocessoReferenciaDecoration%3AhabilitarMascaraProcessoReferencia=true&fPP%3AprocessoReferenciaDecoration%3AIdProcessoReferenciaComMascaraDecoration%3AIdProcessoReferenciaComMascara=&fPP%3Aj_id247%3Aassunto=&fPP%3Aj_id256%3AclasseJudicial=&fPP%3Aj_id265%3AnumeroDocumento=&fPP%3AdecorationDados%3AnumeroOAB=".trim($oab)."&fPP%3AdecorationDados%3AletraOAB=&fPP%3AdecorationDados%3AufOABCombo=".trim($state_atual)."&fPP%3AjurisdicaoComboDecoration%3AjurisdicaoCombo=org.jboss.seam.ui.NoSelectionConverter.noSelectionValue&fPP%3AorgaoJulgadorComboDecoration%3AorgaoJulgadorCombo=org.jboss.seam.ui.NoSelectionConverter.noSelectionValue&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoInicioInputDate=&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoInicioInputCurrentDate=07%2F2025&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoFimInputDate=&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoFimInputCurrentDate=07%2F2025&fPP%3AvalorDaCausaDecoration%3AvalorCausaInicial=&fPP%3AvalorDaCausaDecoration%3AvalorCausaFinal=&fPP%3Aj_id406%3AmovimentacaoProcessualSuggest=&fPP%3Aj_id406%3Aj_id417_selection=&fPP%3Aj_id423%3Aj_id428=&fPP%3Aj_id423%3Aj_id430%3AorgaoOrigemCriminal=org.jboss.seam.ui.NoSelectionConverter.noSelectionValue&fPP%3Aj_id423%3AnumeroProcedCriminal%3AnumeroProcedCriminal=&fPP%3Aj_id423%3AnumeroProcedCriminal%3AanoProcedCriminal=&fPP%3Aj_id423%3AnumeroProtocoloPolicia%3AnumeroProtocoloPolicia=&fPP=fPP&autoScroll=&javax.faces.ViewState=$tk&idProcessoSelecionado=$ca&ajaxSingle=fPP%3AprocessosTable%3A$ca%3Aj_id481&fPP%3AprocessosTable%3A$ca%3Aj_id481=fPP%3AprocessosTable%3A$ca%3Aj_id481&AJAX%3AEVENTS_COUNT=1&"); // Envia os dados do formulário
//     curl_setopt($curl, CURLOPT_HTTPHEADER, [
//     'Host: pje1g.trf1.jus.br',
//         'Connection: keep-alive',
//         // 'Content-Length: 1874',
//         'sec-ch-ua-platform: "Windows"',
//         'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0',
//         'sec-ch-ua: "Not)A;Brand";v="8", "Chromium";v="138", "Microsoft Edge";v="138"',
//         'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
//         'sec-ch-ua-mobile: ?0',
//         'Accept: */*',
//         'Origin: https://pje1g.trf1.jus.br',
//         'Sec-Fetch-Site: same-origin',
//         'Sec-Fetch-Mode: cors',
//         'Sec-Fetch-Dest: empty',
//         'Referer: https://pje1g.trf1.jus.br/pje/Processo/ConsultaProcesso/listView.seam',

//     ]);

//     // Configura para armazenar cookies e manter a sessão

//     curl_setopt($curl, CURLOPT_COOKIEFILE, __DIR__ . "/cookies.txt"); // Usa cookies salvos
//     $html = curl_exec($curl);
//     $ggrttt = trazer1($html, '"&ca=','"');
//     $grr_ID = trazer1($html, 'seam?id=','"');

//     return $ggrttt;
// }








function consultarCAsMultiCurl($curl,array $listaCA) {
    global $oab, $tk, $state_atual, $userAgent;

    $multi = curl_multi_init();
    $curlHandles = [];
    $resultados = [];

    foreach ($listaCA as $ca) {
        $ca = trim($ca);
        $postFields = http_build_query([
            'AJAXREQUEST' => '_viewRoot',
            'fPP:decorationDados:numeroOAB' => $oab,
            'fPP:decorationDados:ufOABCombo' => $state_atual,
            'javax.faces.ViewState' => $tk,
            'idProcessoSelecionado' => $ca,
            "ajaxSingle" => "fPP:processosTable:$ca:j_id481",
            "fPP:processosTable:$ca:j_id481" => "fPP:processosTable:$ca:j_id481",
            "AJAX:EVENTS_COUNT" => 1
        ]);

        // $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => 'https://pje1g.trf1.jus.br/pje/Processo/ConsultaProcesso/listView.seam',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_USERAGENT => $userAgent,
            CURLOPT_ENCODING => true,
            CURLOPT_POSTFIELDS => $postFields,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
                'Referer: https://pje1g.trf1.jus.br/pje/Processo/ConsultaProcesso/listView.seam',
                'Origin: https://pje1g.trf1.jus.br',
                'Accept: */*'
            ],
            CURLOPT_COOKIEFILE => __DIR__ . '/cookies.txt',
            // CURLOPT_COOKIEJAR  => __DIR__ . '/cookies.txt'
        ]);

        curl_multi_add_handle($multi, $curl);
        $curlHandles[$ca] = $curl;
    }

    // Executa as requisições
    do {
        $status = curl_multi_exec($multi, $active);
        curl_multi_select($multi);
    } while ($active && $status == CURLM_OK);

    // Coleta os resultados
    foreach ($curlHandles as $ca => $curl) {
        $response = curl_multi_getcontent($curl);
        $caHash = trazer1($response, '"&ca=', '"');
        $resultados[$ca] = $caHash ?: false;
        curl_multi_remove_handle($multi, $curl);
        curl_close($curl);
    }

    curl_multi_close($multi);
    return $response; // array: [ca => hash]
}




// exit;

// User-Agents reais e modernos (2024–2025)
$userAgents = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.6367.208 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.6422.78 Safari/537.36"
];

$userAgent = $userAgents[array_rand($userAgents)];



// function extrairCA($html) {
//     $cas = [];

//     $padrao = "/\/consultapublica\/ConsultaPublica\/DetalheProcessoConsultaPublica\/listView\.seam\?ca=([a-f0-9]{40,})/";


//     // Procura todas as ocorrências
//     if (preg_match_all($padrao, $html, $matches)) {
//         $cas = array_unique($matches[1]); // Remove duplicatas
//     }

//     return $cas;
// }


function extrairCA($html) {
    $cas = [];

    // Novo padrão: captura valores do idProcessoSelecionado nos onclick
    $padrao = "/idProcessoSelecionado'\s*:\s*(\d+)/";

    if (preg_match_all($padrao, $html, $matches)) {
        $cas = array_unique($matches[1]); // Remove duplicatas
    }

    return $cas;
}



$url = "https://pje1g.trf1.jus.br/pje/Processo/ConsultaProcesso/listView.seam";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Retorna a resposta em vez de exibir
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); // Define o método POST
curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); // Define o método POST
curl_setopt($curl, CURLOPT_HEADER, true); // Define o método POST
curl_setopt($curl, CURLOPT_ENCODING, true); 

$headers = array(
    'Host: pje1g.trf1.jus.br',
    'Connection: keep-alive',
    'Cache-Control: max-age=0',
    'sec-ch-ua: "Not)A;Brand";v="8", "Chromium";v="138", "Microsoft Edge";v="138"',
    'sec-ch-ua-mobile: ?0',
    'sec-ch-ua-platform: "Windows"',
    'Upgrade-Insecure-Requests: 1',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'Sec-Fetch-Site: same-origin',
    'Sec-Fetch-Mode: navigate',
    'Sec-Fetch-User: ?1',
    'Sec-Fetch-Dest: document',
    'Referer: https://pje1g.trf1.jus.br/pje/QuadroAviso/listViewQuadroAvisoMensagem.seam?cid=261880',
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_COOKIEFILE, __DIR__ . "/cookies.txt"); // Usa cookies salvos
$resp = curl_exec($curl);



$tk = trazer1($resp, 'input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="','"');





curl_setopt($curl, CURLOPT_URL, 'https://pje1g.trf1.jus.br/pje/Processo/ConsultaProcesso/listView.seam');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Retorna a resposta em vez de exibir
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST'); // Define o método POST
curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); // Define o método POST
curl_setopt($curl, CURLOPT_HEADER, true); // Define o método POST
curl_setopt($curl, CURLOPT_ENCODING, true); // Define o método POST
curl_setopt($curl, CURLOPT_POSTFIELDS, "AJAXREQUEST=_viewRoot&fPP%3Aj_id149%3AnomeParte=&fPP%3Aj_id158%3AoutrosNomesAlcunha=&fPP%3Aj_id167%3AnomeAdvogado=&tipoMascaraDocumento=on&fPP%3AdpDec%3AdocumentoParte=&fPP%3AnumeroProcesso%3AnumeroSequencial=&fPP%3AnumeroProcesso%3AnumeroDigitoVerificador=&fPP%3AnumeroProcesso%3AAno=&fPP%3AnumeroProcesso%3AramoJustica=4&fPP%3AnumeroProcesso%3ArespectivoTribunal=01&fPP%3AnumeroProcesso%3ANumeroOrgaoJustica=&fPP%3AprocessoReferenciaDecoration%3AhabilitarMascaraProcessoReferencia=true&fPP%3AprocessoReferenciaDecoration%3AIdProcessoReferenciaComMascaraDecoration%3AIdProcessoReferenciaComMascara=&fPP%3Aj_id247%3Aassunto=&fPP%3Aj_id256%3AclasseJudicial=&fPP%3Aj_id265%3AnumeroDocumento=&fPP%3AdecorationDados%3AnumeroOAB=".trim($oab)."&fPP%3AdecorationDados%3AletraOAB=&fPP%3AdecorationDados%3AufOABCombo=".trim($state_atual)."&fPP%3AjurisdicaoComboDecoration%3AjurisdicaoCombo=org.jboss.seam.ui.NoSelectionConverter.noSelectionValue&fPP%3AorgaoJulgadorComboDecoration%3AorgaoJulgadorCombo=org.jboss.seam.ui.NoSelectionConverter.noSelectionValue&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoInicioInputDate=&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoInicioInputCurrentDate=07%2F2025&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoFimInputDate=&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoFimInputCurrentDate=07%2F2025&fPP%3AvalorDaCausaDecoration%3AvalorCausaInicial=&fPP%3AvalorDaCausaDecoration%3AvalorCausaFinal=&fPP%3Aj_id406%3AmovimentacaoProcessualSuggest=&fPP%3Aj_id406%3Aj_id417_selection=&fPP%3Aj_id423%3Aj_id428=&fPP%3Aj_id423%3Aj_id430%3AorgaoOrigemCriminal=org.jboss.seam.ui.NoSelectionConverter.noSelectionValue&fPP%3Aj_id423%3AnumeroProcedCriminal%3AnumeroProcedCriminal=&fPP%3Aj_id423%3AnumeroProcedCriminal%3AanoProcedCriminal=&fPP%3Aj_id423%3AnumeroProtocoloPolicia%3AnumeroProtocoloPolicia=&fPP=fPP&autoScroll=&javax.faces.ViewState=$tk&fPP%3AprocessosTable%3AscTabela=$page1&fPP%3Aj_id465=fPP%3Aj_id465&AJAX%3AEVENTS_COUNT=1&"); // Envia os dados do formulário
curl_setopt($curl, CURLOPT_HTTPHEADER, [
   'Host: pje1g.trf1.jus.br',
    'Connection: keep-alive',
    // 'Content-Length: 1874',
    'sec-ch-ua-platform: "Windows"',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0',
    'sec-ch-ua: "Not)A;Brand";v="8", "Chromium";v="138", "Microsoft Edge";v="138"',
    'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
    'sec-ch-ua-mobile: ?0',
    'Accept: */*',
    'Origin: https://pje1g.trf1.jus.br',
    'Sec-Fetch-Site: same-origin',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Referer: https://pje1g.trf1.jus.br/pje/Processo/ConsultaProcesso/listView.seam',

]);

// Configura para armazenar cookies e manter a sessão

curl_setopt($curl, CURLOPT_COOKIEFILE, __DIR__ . "/cookies.txt"); // Usa cookies salvos
$html = curl_exec($curl);

$processosGridCount = trazer1($html, "'processosGridCount':",",'");
// $babhut = trazer1($html,"idProcessoSelecionado':",",");




$url = "https://pje1g.trf1.jus.br/pje/Processo/ConsultaProcesso/listView.seam";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);

$headers = array(
   "Accept: */*",
   "Accept-Language: pt-BR,pt;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
   "Cache-Control: no-cache",
   "Connection: keep-alive",
   "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
   "Origin: https://pje1g.trf1.jus.br",
   "Pragma: no-cache",
   "Referer: https://pje1g.trf1.jus.br/pje/Processo/ConsultaProcesso/listView.seam",
   "Sec-Fetch-Dest: empty",
   "Sec-Fetch-Mode: cors",
   "Sec-Fetch-Site: same-origin",
   "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
   "sec-ch-ua-mobile: ?0",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$data = "AJAXREQUEST=_viewRoot&fPP%3Aj_id149%3AnomeParte=&fPP%3Aj_id158%3AoutrosNomesAlcunha=&fPP%3Aj_id167%3AnomeAdvogado=&tipoMascaraDocumento=on&fPP%3AdpDec%3AdocumentoParte=&fPP%3AnumeroProcesso%3AnumeroSequencial=&fPP%3AnumeroProcesso%3AnumeroDigitoVerificador=&fPP%3AnumeroProcesso%3AAno=&fPP%3AnumeroProcesso%3AramoJustica=4&fPP%3AnumeroProcesso%3ArespectivoTribunal=01&fPP%3AnumeroProcesso%3ANumeroOrgaoJustica=&fPP%3AprocessoReferenciaDecoration%3AhabilitarMascaraProcessoReferencia=true&fPP%3AprocessoReferenciaDecoration%3AIdProcessoReferenciaComMascaraDecoration%3AIdProcessoReferenciaComMascara=&fPP%3Aj_id247%3Aassunto=&fPP%3Aj_id256%3AclasseJudicial=&fPP%3Aj_id265%3AnumeroDocumento=&fPP%3AdecorationDados%3AnumeroOAB=".trim($oab)."&fPP%3AdecorationDados%3AletraOAB=&fPP%3AdecorationDados%3AufOABCombo=".trim($state_atual)."&fPP%3AjurisdicaoComboDecoration%3AjurisdicaoCombo=org.jboss.seam.ui.NoSelectionConverter.noSelectionValue&fPP%3AorgaoJulgadorComboDecoration%3AorgaoJulgadorCombo=org.jboss.seam.ui.NoSelectionConverter.noSelectionValue&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoInicioInputDate=&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoInicioInputCurrentDate=07%2F2025&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoFimInputDate=&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoFimInputCurrentDate=07%2F2025&fPP%3AvalorDaCausaDecoration%3AvalorCausaInicial=&fPP%3AvalorDaCausaDecoration%3AvalorCausaFinal=&fPP%3Aj_id406%3AmovimentacaoProcessualSuggest=&fPP%3Aj_id406%3Aj_id417_selection=&fPP%3Aj_id423%3Aj_id428=&fPP%3Aj_id423%3Aj_id430%3AorgaoOrigemCriminal=org.jboss.seam.ui.NoSelectionConverter.noSelectionValue&fPP%3Aj_id423%3AnumeroProcedCriminal%3AnumeroProcedCriminal=&fPP%3Aj_id423%3AnumeroProcedCriminal%3AanoProcedCriminal=&fPP%3Aj_id423%3AnumeroProtocoloPolicia%3AnumeroProtocoloPolicia=&fPP=fPP&autoScroll=&javax.faces.ViewState=$tk&fPP%3AprocessosTable%3AscTabela=$page1&ajaxSingle=fPP%3AprocessosTable%3AscTabela&AJAX%3AEVENTS_COUNT=1&";
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_COOKIEFILE, __DIR__ . "/cookies.txt"); // Usa cookies salvos
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);


$html = curl_exec($curl);


$tt = trazer1($html, '<span class="text-muted">','</span>');



$dom = new DOMDocument();
libxml_use_internal_errors(true); // Suprime warnings de HTML malformado
$dom->loadHTML($html);
libxml_clear_errors();

// Cria o XPath
$xpath = new DOMXPath($dom);

// Seleciona todos os <td> com classe 'rich-datascr-inact'
$nodes = $xpath->query("//td[contains(@class, 'rich-datascr-inact')]");

$paginas = [];

foreach ($nodes as $node) {
    $numero = trim($node->textContent);
    if (is_numeric($numero)) {
        $paginas[] = (int)$numero;
    }
}

// Pega o maior número (última página)
$ultimaPagina = !empty($paginas) ? max($paginas) : 1;

// echo "Quantidade de páginas: " . $ultimaPagina;

$listaCA = extrairCA($html);

// foreach ($listaCA as $ca) {
//     echo "CA encontrado: $ca\n";
// }
// exit;
// echo $captor_ca_sem_criptografia = consultarCAsMultiCurl($curl, '13128941');


$multi = curl_multi_init();
    $curlHandles = [];
    $resultados = [];

    foreach ($listaCA as $ca) {
        $ca = trim($ca);
        $postFields = http_build_query([
            'AJAXREQUEST' => '_viewRoot',
            'fPP:decorationDados:numeroOAB' => $oab,
            'fPP:decorationDados:ufOABCombo' => $state_atual,
            'javax.faces.ViewState' => $tk,
            'idProcessoSelecionado' => $ca,
            "ajaxSingle" => "fPP:processosTable:$ca:j_id481",
            "fPP:processosTable:$ca:j_id481" => "fPP:processosTable:$ca:j_id481",
            "AJAX:EVENTS_COUNT" => 1
        ]);

        // $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => 'https://pje1g.trf1.jus.br/pje/Processo/ConsultaProcesso/listView.seam',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_USERAGENT => $userAgent,
            CURLOPT_ENCODING => true,
            CURLOPT_POSTFIELDS => "AJAXREQUEST=_viewRoot&fPP%3Aj_id149%3AnomeParte=&fPP%3Aj_id158%3AoutrosNomesAlcunha=&fPP%3Aj_id167%3AnomeAdvogado=&tipoMascaraDocumento=on&fPP%3AdpDec%3AdocumentoParte=&fPP%3AnumeroProcesso%3AnumeroSequencial=&fPP%3AnumeroProcesso%3AnumeroDigitoVerificador=&fPP%3AnumeroProcesso%3AAno=&fPP%3AnumeroProcesso%3AramoJustica=4&fPP%3AnumeroProcesso%3ArespectivoTribunal=01&fPP%3AnumeroProcesso%3ANumeroOrgaoJustica=&fPP%3AprocessoReferenciaDecoration%3AhabilitarMascaraProcessoReferencia=true&fPP%3AprocessoReferenciaDecoration%3AIdProcessoReferenciaComMascaraDecoration%3AIdProcessoReferenciaComMascara=&fPP%3Aj_id247%3Aassunto=&fPP%3Aj_id256%3AclasseJudicial=&fPP%3Aj_id265%3AnumeroDocumento=&fPP%3AdecorationDados%3AnumeroOAB=".trim($oab)."&fPP%3AdecorationDados%3AletraOAB=&fPP%3AdecorationDados%3AufOABCombo=".trim($state_atual)."&fPP%3AjurisdicaoComboDecoration%3AjurisdicaoCombo=org.jboss.seam.ui.NoSelectionConverter.noSelectionValue&fPP%3AorgaoJulgadorComboDecoration%3AorgaoJulgadorCombo=org.jboss.seam.ui.NoSelectionConverter.noSelectionValue&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoInicioInputDate=&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoInicioInputCurrentDate=07%2F2025&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoFimInputDate=&fPP%3AdataAutuacaoDecoration%3AdataAutuacaoFimInputCurrentDate=07%2F2025&fPP%3AvalorDaCausaDecoration%3AvalorCausaInicial=&fPP%3AvalorDaCausaDecoration%3AvalorCausaFinal=&fPP%3Aj_id406%3AmovimentacaoProcessualSuggest=&fPP%3Aj_id406%3Aj_id417_selection=&fPP%3Aj_id423%3Aj_id428=&fPP%3Aj_id423%3Aj_id430%3AorgaoOrigemCriminal=org.jboss.seam.ui.NoSelectionConverter.noSelectionValue&fPP%3Aj_id423%3AnumeroProcedCriminal%3AnumeroProcedCriminal=&fPP%3Aj_id423%3AnumeroProcedCriminal%3AanoProcedCriminal=&fPP%3Aj_id423%3AnumeroProtocoloPolicia%3AnumeroProtocoloPolicia=&fPP=fPP&autoScroll=&javax.faces.ViewState=$tk&idProcessoSelecionado=$ca&ajaxSingle=fPP%3AprocessosTable%3A$ca%3Aj_id481&fPP%3AprocessosTable%3A$ca%3Aj_id481=fPP%3AprocessosTable%3A$ca%3Aj_id481&AJAX%3AEVENTS_COUNT=1&",
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
                'Referer: https://pje1g.trf1.jus.br/pje/Processo/ConsultaProcesso/listView.seam',
                'Origin: https://pje1g.trf1.jus.br',
                'Accept: */*'
            ],
            CURLOPT_COOKIEFILE => __DIR__ . '/cookies.txt',
            // CURLOPT_COOKIEJAR  => __DIR__ . '/cookies.txt'
        ]);

        curl_multi_add_handle($multi, $curl);
        $curlHandles[$ca] = $curl;
    }

    // Executa as requisições
    do {
        $status = curl_multi_exec($multi, $active);
        curl_multi_select($multi);
    } while ($active && $status == CURLM_OK);

    // Coleta os resultados
    foreach ($curlHandles as $ca => $curl) {
        $response = curl_multi_getcontent($curl);
        $caHash = trazer1($response, '"&ca=', '"');
        $resultados[$ca] = $caHash ?: false;
        curl_multi_remove_handle($multi, $curl);
        curl_close($curl);
    }

    curl_multi_close($multi);




    
// echo "\n\n==== RESULTADOS DOS CA ====\n";

// foreach ($resultados as $ca => $valor) {
//     if ($valor) {
//         echo "🔹 CA $ca → HASH: $valor\n";
//     } else {
//         echo "❌ CA $ca → Falha ou sem hash retornado\n";
//     }
// }

// exit;
// $memoria = carregarMemoriaCA();
// $sucesso = 0;
// $ign = 0;
// $falha = 0;
// $processados = 0;
// $novos = [];

// // Filtra só os CAs novos
// foreach ($listaCA as $ca) {
//     $ca = trim($ca);
//     if (!in_array($ca, $memoria)) {
//         $novos[] = $ca;
//     } else {
//         $ign++;
//         send2Message("⚠️ CA $ca já verificado, ignorando...");
//     }
// }

// // Executa multi-cURL apenas nos novos


// // // Exemplo de uso:
// // $listaCA = extrairCA($html);
// // // echo count($listaCA);

// // // exit;
// // foreach ($listaCA as $ca) {
// //     echo "CA encontrado: $ca\n";
// // }
// exit;












// $count_page = substr_count($html, 'class="paginacao"');

// $resumo = $count_page / 2 + 1;



// $coun_prcs = str_replace('  ','',trim(trazer5($html, '<span id="contadorDeProcessos" class="resultadoPaginacao unj-font unj-lh-32 unj-caption">','<')));



// $processos = extrairNumerosProcessos($html);

// if ($processos == '0') {
//     sendMessage(CHAT_ID,"```ENCERRANDO POR FALTA DE PROCESSO GERE NOVA OAB``` *". count($processos) ."*");
    
//     exit;
// }








require('tele.php');






// Exemplo de uso:
// echo count($listaCA);


if (count($resultados) == '0') {
    # sem processos
    send2Message('Infelizmente no sistema PJE nao tem processos para esta OAB'); // fallback, se chat/message id não foram enviados

}


// exit;







if ($page == '') {
    $page='1';
}

include('botT/bot.php');
$arquivo = 'banco.txt'; // Arquivo com os dados

$page = isset($page) ? (int)$page : 1;
$porPagina = 70;

// Verifica se o arquivo existe
if (!file_exists($arquivo)) {
    die("Arquivo de banco de dados não encontrado.");
}

// Carrega os destinatários do banco
$dados = file($arquivo, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$usuarios = [];

foreach ($dados as $linha) {
    $json = json_decode($linha, true);
    if ($json) {
        $usuarios[] = ['user' => $json['USER'], 'id' => $json['ID']];
    }
}

// Paginação dos destinatários
$totalUsuarios = count($usuarios);
$totalPaginas = ceil($totalUsuarios / $porPagina);
$page = max(1, min($totalPaginas, $page));

$inicio = ($page - 1) * $porPagina;
$usuariosPagina = array_slice($usuarios, $inicio, $porPagina);

// Monta os botões dos usuários
$botoes = ['inline_keyboard' => []];
$tempRow = [];

foreach ($usuariosPagina as $usuario) {
    $tempRow[] = [
        'text' => $usuario['user'],
        'callback_data' => "select_{$usuario['id']}ob_{$oab}pag_{$page1}"
    ];

    if (count($tempRow) == 2) {
        $botoes['inline_keyboard'][] = $tempRow;
        $tempRow = [];
    }
}
if (!empty($tempRow)) {
    $botoes['inline_keyboard'][] = $tempRow;
}

// Botões de navegação
$navButtons = [];
if ($page > 1) {
    $navButtons[] = ['text' => '⬅️ Anterior', 'callback_data' => "nav_page_" . ($page - 1) . "_ob_" . $oab . "pag_at". $page1];
}
if ($page < $totalPaginas) {
    $navButtons[] = ['text' => 'Próxima ➡️', 'callback_data' => "nav_page_" . ($page + 1) . "_ob_" . $oab . "pag_at". $page1];
}
if (!empty($navButtons)) {
    $botoes['inline_keyboard'][] = $navButtons;
}

// Aqui voltam os valores originais da lógica dos processos
$mensagem = "```TOTAL DE PROCESSOS ENCONTRADOS NESTA PAGINA:``` *" . count($resultados) . "*";
$mensagem .= "\n\n```TOTAL TODAS PAGINAS:``` *" . $tt . "*";
$mensagem .= "\n\n```TOTAL DE PAGINAS ENCONTRADOS:``` *$ultimaPagina*";
$mensagem .= "\n\n```PAGINA SELECIONADA:``` *$page1*";
$mensagem .= "\n\n```PAGINA TRABALHADORES:``` *$page*";
$mensagem .= "\n\n\n\n```SELECIONE QUEM IRA RECEBER ESTES PROCESSOS:``` *🔽🔽🔽*";


// Envia a mensagem
// send2Message($mensagem, $botoes);
if ($chat_id && $message_id) {
    editMessagef($chat_id, $message_id, $mensagem, $botoes);
} else {
    send2Message($mensagem, $botoes); // fallback, se chat/message id não foram enviados
}


