<?php
 $phoneno = preg_replace('/[^0-9a-zA-Z\/-]+/m','',$_REQUEST['phone']); 
 $otp = preg_replace('/[^0-9a-zA-Z\/-]+/m','',$_REQUEST['otp']); 
  $epicno = preg_replace('/[^0-9a-zA-Z\/-]+/m','',$_REQUEST['epic']);  
  $stateCd = preg_replace('/[^0-9a-zA-Z\/-]+/m','',$_REQUEST['stateCd']);


$tokenFilePath = dirname(__DIR__) . '/tokens.txt';

if (file_exists($tokenFilePath)) {
    $tokensData = json_decode(file_get_contents($tokenFilePath), true);
    
    $access_token = $tokensData['access_token'] ?? '';
    $atkn_bnd = $tokensData['atkn_bnd'] ?? '';
    $rtkn_bnd = $tokensData['rtkn_bnd'] ?? '';
    
    if (empty($access_token)) {
        die('{"status":"failed", "message":"Access token is empty in tokens.txt"}');
    }
} else {
    die('{"status":"failed", "message":"tokens.txt file not found at ' . $tokenFilePath . '"}');
}


if (file_exists(dirname(__DIR__) . '/config.php')) {
    require_once(dirname(__DIR__) . '/config.php');
}
// ---------------------------------------------------------
   
   
   if (class_exists('Imagick')) {
} else {
    echo '{"message":"Imagick NOT Allowed"}'; 
    exit();
}
   
if($_REQUEST['epic']==true&&$_REQUEST['action']=="viewmob"){  
$jsonpost = '{"epicNumber":"'.$epicno.'","isActive":"Y"}';
$contentLength = strlen($jsonpost); // Get content length
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gateway-voters.eci.gov.in/api/v1/elastic/get-by-epic-for-form');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'Content-Length: '.$contentLength,
    'Authorization: Bearer '.$access_token,
    'Platform-Type: ECIWEB',
    'Atkn_bnd: '.$atkn_bnd,
    'Rtkn_bnd: '.$rtkn_bnd,
    'Applicationname: VSP',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Currentrole: citizen',
    'Channelidobo: VSP',
    'Content-Type: application/json',
    'Accept: */*',
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Site: same-site',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=4',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonpost);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$responsegetepicno = curl_exec($ch);
curl_close($ch);
//echo $responsegetepicno;
$responsegetepicnojsosn = json_decode($responsegetepicno,true);
$applicantDate = date("Y-m-d",time());
 $acNumber = $responsegetepicnojsosn[0]['content']['acNumber'];
 $stateCd = ($responsegetepicnojsosn[0]['content']['stateCd']?$responsegetepicnojsosn[0]['content']['stateCd']:$_REQUEST['stateCd']);
 if($stateCd==true){
$jsonpost = '{"stateCd":"'.$stateCd.'","searchType":"EPIC_NO","epicRefNo":"'.$epicno.'"}';
$contentLength = strlen($jsonpost); // Get content length     
   $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gateway-voters.eci.gov.in/api/v1/e-epic/get-epic-detail');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'Content-Length: '.$contentLength,
    'Sec-Ch-Ua-Platform: "Windows"',
    'Authorization: Bearer '.$access_token,
    'Platform-Type: ECIWEB',
    'Atkn_bnd: '.$atkn_bnd,
    'Rtkn_bnd: '.$rtkn_bnd,
    'Sec-Ch-Ua: "Google Chrome";v="143", "Chromium";v="143", "Not A(Brand";v="24"',
    'Sec-Ch-Ua-Mobile: ?0',
    'Applicationname: VSP',
   'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Currentrole: citizen',
    'Channelidobo: VSP',
    'Content-Type: application/json;',
    'Accept: */*',
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Site: same-site',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=1, i',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonpost);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$response = curl_exec($ch);
curl_close($ch);
$jsonData = [
        "response" => json_decode($response),
        "stateCd" => $stateCd,
    ];

    echo json_encode($jsonData, JSON_UNESCAPED_UNICODE);
    
}else{
    echo '{"status":"invalid_epic_no"}';
}
}else if($_REQUEST['statecode']&&$_REQUEST['action']=="viewaadhar"){ 
 $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gateway-voters.eci.gov.in/api/v1/nvsp/draftFormDetails?userId=undefined&currentStatus=Draft');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Accept: */*',
    'Accept-Language: en-US,en;q=0.5',
    'Accept-Encoding: gzip, deflate, br',
    'Applicationname: VSP',
    'Atkn_bnd: '.$atkn_bnd,
    'Authorization: Bearer '.$access_token,
    'Channelidobo: VSP',
    'Content-Type: application/json',
    'Currentrole: citizen',
    'Rtkn_bnd: '.$rtkn_bnd,
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Dest: empty',
    'Sec-Fetch-Mode: cors',
    'State: '.$_REQUEST['statecode'],
    'Sec-Fetch-Site: same-site',
    'Priority: u=0',
    'Te: trailers',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 $response = curl_exec($ch);
curl_close($ch);

}else if($_REQUEST['phone']==true&&$_REQUEST['epic']==true&&$_REQUEST['otp']==true&&$_REQUEST['action']=="verify"){  
$jsonpost = '{"epicNumber":"'.$epicno.'","isActive":"Y"}';
$contentLength = strlen($jsonpost); // Get content length
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gateway-voters.eci.gov.in/api/v1/elastic/get-by-epic-for-form');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'Content-Length: '.$contentLength,
    'Authorization: Bearer '.$access_token,
    'Platform-Type: ECIWEB',
    'Atkn_bnd: '.$atkn_bnd,
    'Rtkn_bnd: '.$rtkn_bnd,
    'Applicationname: VSP',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Currentrole: citizen',
    'Channelidobo: VSP',
    'Content-Type: application/json',
    'Accept: */*',
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Site: same-site',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=4',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonpost);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  $responsegetepicno = curl_exec($ch);
curl_close($ch);
$responsegetepicnojsosn = json_decode($responsegetepicno,true);
$applicantDate = date("Y-m-d",time());
 $acNumber = $responsegetepicnojsosn[0]['content']['acNumber'];
 $stateCd = $responsegetepicnojsosn[0]['content']['stateCd'];
  $epicNumber = $responsegetepicnojsosn[0]['content']['epicNumber'];
   $partNumber = $responsegetepicnojsosn[0]['content']['partNumber'];
    $partSerialNumber = $responsegetepicnojsosn[0]['content']['partSerialNumber'];
     $districtCd = $responsegetepicnojsosn[0]['content']['districtCd'];
      $firstName = $responsegetepicnojsosn[0]['content']['applicantFirstName'];
     $lastName = $responsegetepicnojsosn[0]['content']['applicantLastName'];
     $applicantFirstNameL1 = $responsegetepicnojsosn[0]['content']['applicantFirstNameL1'];
     $applicantLastNameL1 = $responsegetepicnojsosn[0]['content']['applicantLastNameL1'];
     $age = $responsegetepicnojsosn[0]['content']['age']; 
     $relationName = $responsegetepicnojsosn[0]['content']['relationName']; 
     $photogragh = $responsegetepicnojsosn[0]['content']['photo']; 
     $formSubmissionPlace = strtolower($responsegetepicnojsosn[0]['content']['districtValue']); 
     $gender = $responsegetepicnojsosn[0]['content']['gender']; 
     $sectionNo = $responsegetepicnojsosn[0]['content']['sectionNo'];
     $applicantName = ucwords(strtolower($responsegetepicnojsosn[0]['content']['fullName']));
     $relativeNameRegional = $responsegetepicnojsosn[0]['content']['relationNameL1'];
     $relativeSurnameRegional = $responsegetepicnojsosn[0]['content']['relationLNameL1'];
     $stateCd = $responsegetepicnojsosn[0]['content']['stateCd'];
if($acNumber==true&&$stateCd==true){

$assemplycodepdf = $responsegetepicnojsosn[0]['content']['acNumber'];
$assemplynamepdf = $responsegetepicnojsosn[0]['content']['asmblyName'];
$placenamepdf = $responsegetepicnojsosn[0]['content']['asmblyName'];
$mobilenopdf = $phoneno;
$epicnamepdf = $responsegetepicnojsosn[0]['content']['fullName'];
$epicnopdf = $responsegetepicnojsosn[0]['content']['epicNumber'];
$statecodepdf = $responsegetepicnojsosn[0]['content']['stateCd'];
$referenceNumber = $_REQUEST['referenceno'];
$refnopdf = $referenceNumber;
$datetimepdf = date("d-m-Y",time());
// Output file path
$filename = 'Form8_'.$referenceNumber.'.pdf';
$pdfFile = __DIR__ . '/' . $filename;


if($assemplycodepdf&&$assemplynamepdf&&$refnopdf&&$epicnopdf&&$epicnamepdf&&$placenamepdf){
// Two image paths
$image1 = __DIR__ . '/editepicfile1.png';
$image2 = __DIR__ . '/editepicfile2.png';

// Check both images exist
if (!file_exists($image1) || !file_exists($image2)) {
    die("One or both image files not found!");
}

// Create Imagick object and read both images
$image = new Imagick();
$image->readImage($image1);
$image->readImage($image2);

// Optional: Add text on each page
$draw = new ImagickDraw();
$draw->setFont(__DIR__ . '/ARIALNB.TTF'); // Bold font file
$draw->setFontSize(46);
$draw->setFillColor('black');

// Page 1
$image->setIteratorIndex(0);
$image->annotateImage($draw, 480, 97, 0, $refnopdf);
$image->annotateImage($draw, 2960, 95, 0, $datetimepdf);


$image->annotateImage($draw, 1500, 1045, 0, $assemplycodepdf);
$image->annotateImage($draw, 2010, 1045, 0, $assemplynamepdf);
$image->annotateImage($draw, 460, 1375, 0, $epicnamepdf);
$image->annotateImage($draw, 390, 1510, 0, $epicnopdf);
// Page 2
$image->setIteratorIndex(1);
$image->annotateImage($draw, 330, 1150, 0, $mobilenopdf);
$image->annotateImage($draw, 210, 3427, 0, $datetimepdf);
$image->annotateImage($draw, 220, 3527, 0, $placenamepdf);
$image->annotateImage($draw, 530, 4227, 0, $refnopdf);
$image->annotateImage($draw, 2080, 4227, 0, $datetimepdf);
$image->annotateImage($draw, 870, 4357, 0, $epicnamepdf);
// Set format to PDF
$image->setImageFormat('pdf');

// Write multi-page PDF
$image->writeImages($pdfFile, true); 

// Cleanup
$image->clear();
$image->destroy();
}
if(file_exists($pdfFile)){
 
$pdfcontents = file_get_contents($pdfFile);  
$postdata = [
    'file' => new CURLStringFile($pdfcontents, 'Form8_'.$referenceNumber.'.pdf', 'application/pdf'),
    'fileType' => 'application/pdf',
    'fileName' => $referenceNumber,
    'stateCode' => $statecodepdf,
    'acNo' => $assemplycodepdf,
    'type' => 'FORM',
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gateway-voters.eci.gov.in/api/v1/document/uploadFile');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'Sec-Ch-Ua-Platform: "Windows"',
    'Authorization: Bearer '.$access_token,
    'Platform-Type: ECIWEB',
    'Atkn_bnd: '.$atkn_bnd,
    'Rtkn_bnd: '.$rtkn_bnd,
    'Sec-Ch-Ua: "Google Chrome";v="143", "Chromium";v="143", "Not A(Brand";v="24"',
    'Sec-Ch-Ua-Mobile: ?0',
    'Applicationname: VSP',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Accept: application/json, text/plain, */*',
    'Channelidobo: VSP',
    'Content-Type: multipart/form-data; boundary=----WebKitFormBoundary0AmFf6vTVnCQPI4h',
    'Currentrole: citizen',
    'Appname: VSP',
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Site: same-site',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=1, i',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 $responseecipdf = curl_exec($ch);
curl_close($ch);
unlink($pdfFile);

$responseecipdfjson = json_decode($responseecipdf,true);
if($responseecipdfjson['statusCode']=="200"&&$responseecipdfjson['refId']==true){
$data = [
    "applicationFor" => "aplOther",
    "epicNumber" => $epicNumber,
    "shiftingOfResidence" => "N",
    "entriesCorrectionInEroll" => "Y",
    "replacementOfEpic" => "N",
    "markingOfPwd" => "N",
    "partNumber" => (int) $partNumber,
    "serialNumber" => (int) $partSerialNumber,
    "stateCd" => $stateCd,
    "districtCd" => $districtCd,
    "assemblyNo" => (int) $acNumber,
    "firstName" => $firstName,
    "lastName" => $lastName,
    "firstNameL1" => $applicantFirstNameL1,
    "lastNameL1" => $applicantLastNameL1,
    "age" => (int) $age,
    "relativeName" => $relationName,
    "relationType" => "OTHR",
    "mobileNumber" => $phoneno,
    "photogragh" => $photogragh,
    "correctionOfName" => "N",
    "correctionOfAddress" => "N",
    "correctionOfDob" => "N",
    "correctionOfAge" => "N",
    "correctionOfGender" => "N",
    "correctionOfRelative" => "N",
    "correctionOfRelation" => "N",
    "correctionOfPhotograpgh" => "N",  // Fixed Typo
    "formSubmissionPlace" => $formSubmissionPlace,
    "applicantDate" => $applicantDate,
    "formSubmissionDate" => $applicantDate,
    "formSubmissionMode" => "ONLINE",
    "formSubmissionChannel" => "NVSP",
    "referenceNumber" => $referenceNumber,
    "isDraft" => "N",
    "gender" => $gender,
    "correctionOfMobile" => "Y",
    "sectionNo" => (int) $sectionNo,
    "epicOfFamilyMember" => $epicNumber,
    "applicantName" => $applicantName,
    "disabilityVI" => "N",
    "disabilitySH" => "N",
    "disabilityLM" => "N",
    "relativeNameRegional" => $relativeNameRegional,
    "relativeSurnameRegional" => $relativeSurnameRegional,
    "isReinitiate" => "N",
    "form8Id" => 0,
    "otp" => $otp,
    "submittedByMobile" => $submittedByMobile,
    "submittedByName" => $firstName,
    "esignUrl" => $responseecipdfjson['refId']
];

// Remove Empty and Null Values but Keep `0` and `false`
$data = array_filter($data, function ($value) {
    return $value !== null && $value !== "";
});

// Convert to JSON
$jsonpost = json_encode($data, JSON_UNESCAPED_UNICODE);
$contentLength = strlen($jsonpost);
// Initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gateway-voters.eci.gov.in/api/v1/form8/submitForm8');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'Content-Length: '.$contentLength,
    'Sec-Ch-Ua-Platform: "Windows"',
    'Authorization: Bearer '.$access_token,
    'Platform-Type: ECIWEB',
    'Atkn_bnd: '.$atkn_bnd,
    'Rtkn_bnd: '.$rtkn_bnd,
    'Sec-Ch-Ua: "Google Chrome";v="143", "Chromium";v="143", "Not A(Brand";v="24"',
    'Sec-Ch-Ua-Mobile: ?0',
    'Applicationname: VSP',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Currentrole: citizen',
    'Channelidobo: VSP',
    'Content-Type: application/json',
    'State: '.$stateCd,
    'Accept: */*',
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Site: same-site',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=1, i',
    'Connection: keep-alive',
]);
// Set JSON Post Fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonpost);

// Ignore SSL Issues (Use only in development)
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 $response = curl_exec($ch);
curl_close($ch);  
$responsejson = json_decode($response,true);
if (preg_match('/form 8 is submitted successfully/i', $response)) {
    $jsonData = [
        "status" => "done",
        "response" => $responsejson,
        "stateCd" => $statecodepdf,
        "acNo" => $assemplycodepdf,
        "signerName" => $epicnamepdf
    ];

    echo json_encode($jsonData, JSON_UNESCAPED_UNICODE);
} elseif (preg_match('/OTP expired/i', $response)) {
    echo json_encode(["status" => "failed", "message" => "OTP expired"], JSON_UNESCAPED_UNICODE);
} elseif (preg_match('/OTP doesnt match/i', $response)) {
    echo json_encode(["status" => "failed", "message" => "OTP do not match"], JSON_UNESCAPED_UNICODE);
} else if(!empty($responsephonejson['message'])){
echo json_encode(["status" => "failed", "message" => $responsejson['message']], JSON_UNESCAPED_UNICODE);
} else {
    echo json_encode(["hint" => "submitForm8"], JSON_UNESCAPED_UNICODE);
}
}else{
    echo '{"hint":"pdf not upload eci"}';
}
}else{
    echo '{"hint":"pdf not generate local server"}';
}

}else{
    echo '{"status":"invalid_epic_no"}';
}
}else if($_REQUEST['phone']==true&&$_REQUEST['epic']==true&&$_REQUEST['action']=="send"){ 
 
$jsonpost = '{"epicNumber":"'.$epicno.'","isActive":"Y"}';
$contentLength = strlen($jsonpost); // Get content length
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gateway-voters.eci.gov.in/api/v1/elastic/get-by-epic-for-form');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'Content-Length: '.$contentLength,
    'Authorization: Bearer '.$access_token,
    'Platform-Type: ECIWEB',
    'Atkn_bnd: '.$atkn_bnd,
    'Rtkn_bnd: '.$rtkn_bnd,
    'Applicationname: VSP',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Currentrole: citizen',
    'Channelidobo: VSP',
    'Content-Type: application/json',
    'Accept: */*',
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Site: same-site',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=4',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonpost);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  $responsegetepicno = curl_exec($ch);
curl_close($ch);
$responsegetepicnojsosn = json_decode($responsegetepicno,true);

 $acNumber = $responsegetepicnojsosn[0]['content']['acNumber'];
 $stateCd = $responsegetepicnojsosn[0]['content']['stateCd'];
if($acNumber==true&&$stateCd==true){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gateway-voters.eci.gov.in/api/v1/form6a/getFormRefNumber?assemblyNo='.$acNumber.'&stateCd='.$stateCd.'&formType=8&sourceOfApplication=O&form8ShiOutWitCorRepMar=C');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'Sec-Ch-Ua-Platform: "Windows"',
    'Authorization: Bearer '.$access_token,
    'Platform-Type: ECIWEB',
    'Atkn_bnd: '.$atkn_bnd,
    'Rtkn_bnd: '.$rtkn_bnd,
    'Sec-Ch-Ua: "Google Chrome";v="143", "Chromium";v="143", "Not A(Brand";v="24"',
    'Sec-Ch-Ua-Mobile: ?0',
    'Applicationname: VSP',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Accept: application/json',
    'Channelidobo: VSP',
    'Currentrole: citizen',
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Site: same-site',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=1, i',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 $responserefId = curl_exec($ch);
curl_close($ch);
$responserefIdjson = json_decode($responserefId,true);    
    
$referenceNumber  = $responserefIdjson['refId'];  
if($responserefIdjson['refId']==true&&$responserefIdjson['message']=="Form 8 Reference is generated sucessfully"){
  
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gateway-voters.eci.gov.in/api/v1/captcha-service/generateCaptcha/F8');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:136.0) Gecko/20100101 Firefox/136.0',
    'Accept: */*',
    'Accept-Language: en-US,en;q=0.5',
    'Accept-Encoding: gzip, deflate, br',
    'Applicationname: VSP',
    'Appname: VSP',
    'Atkn_bnd: '.$atkn_bnd,
    'Channelidobo: VSP',
    'Rtkn_bnd: '.$rtkn_bnd,
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Dest: empty',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Site: same-site',
    'Priority: u=4',
    'Te: trailers',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 $responsecapget = curl_exec($ch);
curl_close($ch);
$responsecapget = json_decode($responsecapget,true);
if($responsecapget['captcha']==true&&$responsecapget['id']==true){
    $captcha = 'data:image/jpeg;base64,'.$responsecapget['captcha'];
    $captchaId = $responsecapget['id'];
require_once('captchatototext.php');
                
               
$responsecaptchajson = solveCaptcha($captcha, $apiKey);
$captchaText = $responsecaptchajson['response']['text'] ?? $responsecaptchajson['text'] ?? '';
                
if(!empty($captchaText)){
$jsonpost = '{"captchaSID":"'.$captchaId.'","captchaText":"'.$captchaText.'","mobileNumber":"'.$phoneno.'","eventId":"F8"}';
$contentLength = strlen($jsonpost); // Get content length            
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gateway-voters.eci.gov.in/api/v1/form6/otp/send');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'Content-Length: '.$contentLength,
    'Sec-Ch-Ua-Platform: "Windows"',
    'Authorization: Bearer '.$access_token,
    'Platform-Type: ECIWEB',
    'Atkn_bnd: '.$atkn_bnd,
    'Rtkn_bnd: '.$rtkn_bnd,
    'Sec-Ch-Ua: "Google Chrome";v="143", "Chromium";v="143", "Not A(Brand";v="24"',
    'Sec-Ch-Ua-Mobile: ?0',
    'Applicationname: VSP',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Accept: application/vnd.form6.app.v2+json',
    'Channelidobo: VSP',
    'Content-Type: application/json',
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Site: same-site',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=1, i',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonpost);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 $responsephone = curl_exec($ch);
curl_close($ch);
$responsephonejson = json_decode($responsephone,true);
if(preg_match('/OTP sent/mi',$responsephonejson['message'])){
    echo '{"status":"sending","refid":"'.$referenceNumber.'","stateCd":"'.$stateCd.'"}';
}else if(preg_match('/seconds before resending new otp/mi',$responsephonejson['message'])){
echo '{"status":"sending","refid":"'.$referenceNumber.'","stateCd":"'.$stateCd.'"}';
}else if(!empty($responsephonejson['message'])){
echo json_encode(["status" => "failed", "message" => $responsephonejson['message']], JSON_UNESCAPED_UNICODE);
}else{
    echo '{"hint":"otp/send"}';
} 
}else{
    echo '{"hint":"captchatotext"}';
}
}else{
    echo '{"hint":"generateCaptcha"}';
}
}else{
    echo '{"hint":"getFormRefNumber"}';
}
}else{
    echo '{"status":"invalid_epic_no"}';
}
}else if($_REQUEST['aadharno']==true&&$_REQUEST['tokenbase64']==true&&$_REQUEST['action']=="aadharotpsend"){ 

$tokenbase64 = json_decode(base64_decode($_REQUEST['tokenbase64'],true));
$statecode = $tokenbase64->stateCd;
$tokenbase64_second = $tokenbase64->response; 
$aadharholder = $_REQUEST['aadharholder']?$_REQUEST['aadharholder']:$tokenbase64->signerName;
  $postdata = '{"refId":"'.$tokenbase64_second->refId.'","docUrl":"'.$tokenbase64_second->esignUrl.'","stateCd":"'.$tokenbase64->stateCd.'","acNo":"'.$tokenbase64->acNo.'","signerName":"'.$aadharholder.'","isResURLFlag":"F8"}';    
$contentLength = strlen($postdata);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gateway-voters.eci.gov.in/api/v1/aadhaar-esign/initiate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'Sec-Ch-Ua-Platform: "Windows"',
    'Authorization: Bearer '.$access_token,
    'Platform-Type: ECIWEB',
    'Atkn_bnd: '.$atkn_bnd,
    'Rtkn_bnd: '.$rtkn_bnd,
    'Sec-Ch-Ua: "Google Chrome";v="143", "Chromium";v="143", "Not A(Brand";v="24"',
    'Sec-Ch-Ua-Mobile: ?0',
    'Applicationname: VSP',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Currentrole: citizen',
    'Channelidobo: VSP',
    'Content-Type: application/json;',
    'Accept: */*',
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Site: same-site',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=1, i',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 $responseuid = curl_exec($ch);
curl_close($ch);
$responseuidjson = json_decode($responseuid,true);
 $signedXml = $responseuidjson['signedXml'];
 $transactionId = $responseuidjson['transactionId'];
if($signedXml==true&&$transactionId==true){
 $postdata = 'eSignRequest='.urlencode(base64_decode($signedXml)).'&aspTxnID='.$transactionId.'&Content-Type=application/xml';    

$conlen = strlen($postdata);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $responseuidjson['cdacUrl']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // connect timeout
curl_setopt($ch, CURLOPT_TIMEOUT, 30);        // total timeout
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:136.0) Gecko/20100101 Firefox/136.0',
    'Accept: */*',
    'Accept-Language: en-US,en;q=0.5',
    'Accept-Encoding: gzip, deflate, br',
    'Applicationname: VSP',
    'Channelidobo: VSP',
    'Appname: VSP',
    'Content-Type: application/x-www-form-urlencoded',
    'Referer: https://esignservice.cdac.in/',
    'Currentrole: citizen',
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Dest: empty',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Site: same-site',
    'Priority: u=0',
    'Te: trailers',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 $response = curl_exec($ch);
 if (curl_errno($ch)) {
$html = '
<html>
<head>
</head>
<body onload="autoSubmit();">

<form id="esignForm" method="post" action="'.$responseuidjson['cdacUrl'].'" >
    <textarea style="display:none;" name="eSignRequest">'.base64_decode($signedXml).'</textarea>
    <input type="hidden" name="aspTxnID" value="'.$transactionId.'">
    <input type="hidden" name="Content-Type" value="application/xml">
</form>
<script type="text/javascript">
    function autoSubmit() {
        setTimeout(function () {
            document.getElementById("esignForm").submit();
        }, 100);
    }

    // backup trigger
    document.addEventListener("DOMContentLoaded", function () {
        autoSubmit();
    });
</script>
</body>
</html>';

$htmlBase64 = base64_encode($html);
    echo json_encode([
    "message"       => "Are You Sure You used Indian Server",
    "newtabbae64"   => $htmlBase64
]);
exit;
}
curl_close($ch);

// ðŸ”¹ JSESSIONID match karna
preg_match('/set-cookie:\s*JSESSIONID=([^;]+)/i', $response, $matchSession);
 $jsessionid = $matchSession[1] ?? '';

preg_match('/set-cookie:\s*SERVERID=([^;]+)/i', $response, $matchSERVERID);
 $SERVERIDid = $matchSERVERID[1] ?? '';

//  Location URL match karna
preg_match('/location:\s*([^\s]+)/i', $response, $matchLocation);
 $location = $matchLocation[1] ?? '';
$parts = parse_url($location);

parse_str($parts['query'] ?? '', $query);

 $clientId = $query['clientId'] ?? null;

if($jsessionid==true&&$clientId==true&&$SERVERIDid==true){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://esignservice.cdac.in/esign2.1/otp?clientId='.$clientId);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // connect timeout
curl_setopt($ch, CURLOPT_TIMEOUT, 30);        // total timeout
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: esignservice.cdac.in',
    'Cache-Control: max-age=0',
    'Upgrade-Insecure-Requests: 1',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    '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: cross-site',
    'Sec-Fetch-Mode: navigate',
    'Sec-Fetch-User: ?1',
    'Sec-Fetch-Dest: document',
    'Sec-Ch-Ua: "Google Chrome";v="143", "Chromium";v="143", "Not A(Brand";v="24"',
    'Sec-Ch-Ua-Mobile: ?0',
    'Sec-Ch-Ua-Platform: "Windows"',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=0, i',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_COOKIE, 'JSESSIONID='.$jsessionid.'; SERVERID='.$SERVERIDid);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 $response = curl_exec($ch);
 if (curl_errno($ch)) {
    echo '{"message":"Are You Sure You used Indian Server"}'; 
    exit();
}
curl_close($ch);

preg_match('/<textarea[^>]*id=["\']pubkey["\'][^>]*>(.*?)<\/textarea>/is', $response, $match);
 $rawKey = trim($match[1] ?? '');
$publicKey = "-----BEGIN PUBLIC KEY-----\n" .
             chunk_split($rawKey, 64, "\n") .
             "-----END PUBLIC KEY-----";
$parts = parse_url($location);
parse_str($parts['query'] ?? '', $query);
$clientId = $query['clientId'] ?? '';
// ---------- Inputs ----------
$vidId    = $_REQUEST['aadharno'];   
if($vidId){
// ---------- Encrypt UID ----------
openssl_public_encrypt($vidId, $encUid, $publicKey, OPENSSL_PKCS1_PADDING);
$encUidBase64 = base64_encode($encUid);
 $uidJson = json_encode([
    "uid" => $encUidBase64,
    "authInformation" => "",
    "clientId" => $clientId
], JSON_UNESCAPED_SLASHES);
}

if($rawKey==true){
    $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://esignservice.cdac.in/esign2.1/getOtp');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: esignservice.cdac.in',
    'Content-Length: '.strlen($uidJson),
    'Sec-Ch-Ua-Platform: "Windows"',
    'X-Requested-With: XMLHttpRequest',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
    'Accept: */*',
    'Sec-Ch-Ua: "Google Chrome";v="141", "Not?A_Brand";v="8", "Chromium";v="141"',
    'Content-Type: application/json',
    'Sec-Ch-Ua-Mobile: ?0',
    'Origin: https://esignservice.cdac.in',
    'Sec-Fetch-Site: same-origin',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Referer: '.$location,
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=1, i',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_COOKIE, 'JSESSIONID='.$jsessionid.'; SERVERID='.$SERVERIDid);
curl_setopt($ch, CURLOPT_POSTFIELDS, $uidJson);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 $response = curl_exec($ch);
curl_close($ch);
$jsonres = json_decode($response,true);
if($jsonres['responseXml']=="NA"&&$jsonres['responseUrl']==true&&$jsonres['info']==true){
   $jsonData = [
        "status" => "sending",
        "response" => json_decode($response,true),
        "publicKey" => base64_encode($publicKey),
        "clientId" => $clientId,
        "jsessionid" => $jsessionid,
        "SERVERID" => $SERVERIDid,
        "statecode" => $statecode,
        "vidId" => $vidId
    ];  
    echo json_encode($jsonData, JSON_UNESCAPED_UNICODE);
}else{
    echo '{"hint":"esign2.1/getOtp"}';
}

}else{
    echo '{"hint":"esign2.1/otp?clientId"}';
} 
}else{
    echo '{"message":"Maximum OTP Attempts Reached, Now Wait 1 Hour almost or used another aadhar or new entry fill"}';
}
}else{
    echo '{"hint":"aadhaar-esign/initiate"}';
}
}else if($_REQUEST['otp']==true&&$_REQUEST['tokenbase64']==true&&$_REQUEST['action']=="aadharotpverify"){ 
    
 $tokenbase64 = json_decode(base64_decode($_REQUEST['tokenbase64']),true);
 $publicKey = base64_decode($tokenbase64['publicKey']);
$vidId = $tokenbase64['vidId'];
$otpVal   = $_REQUEST['otp'];  
$clientId = $tokenbase64['clientId'];
if($otpVal){
// ---------- Encrypt Auth Information ----------
$plainAuth = $otpVal . "@@" . $vidId . "@@" . "Y" . "@@" . "OTP";
openssl_public_encrypt($plainAuth, $encAuth, $publicKey, OPENSSL_PKCS1_PADDING);
$encAuthBase64 = base64_encode($encAuth);
 $authJson = json_encode([
    "uid" => "",
    "authInformation" => $encAuthBase64,
    "clientId" => $clientId
], JSON_UNESCAPED_SLASHES);
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://esignservice.cdac.in/esign2.1/authSubmit');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: esignservice.cdac.in',
    'Content-Length: '.strlen($authJson),
    'Sec-Ch-Ua-Platform: "Windows"',
    'X-Requested-With: XMLHttpRequest',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
    'Accept: */*',
    'Sec-Ch-Ua: "Google Chrome";v="141", "Not?A_Brand";v="8", "Chromium";v="141"',
    'Content-Type: application/json',
    'Sec-Ch-Ua-Mobile: ?0',
    'Origin: https://esignservice.cdac.in',
    'Sec-Fetch-Site: same-origin',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Referer: '.$location,
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=1, i',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_COOKIE, 'JSESSIONID='.$tokenbase64['jsessionid'].'; SERVERID='.$tokenbase64['SERVERID']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $authJson);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 $responseotp = curl_exec($ch);
curl_close($ch);

$responseuidjson = json_decode($responseotp,true);
 $signedXml = $responseuidjson['responseXml'];
 $responseUrl = $responseuidjson['responseUrl'];

if($responseuidjson['status']=="0"&&$signedXml=="K-100"){
echo '{"message":"Invalid OTP Please enter New OTP"}';
exit();
} 
if($signedXml!=="NA"&&$responseUrl==true&&preg_match('/signed_pdf/mi',$responseUrl)){
 $postdata = 'eSignResponse='.urlencode($signedXml).'&espTxnID='.$clientId;
$contentLength = strlen($postdata);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gateway-voters.eci.gov.in/api/v1/aadhaar-esign/signed_pdf');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); 
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'Content-Length: '.$contentLength,
    'Sec-Ch-Ua-Platform: "Windows"',
    'Platform-Type: ECIWEB',
    'Sec-Ch-Ua: "Google Chrome";v="143", "Chromium";v="143", "Not A(Brand";v="24"',
    'Sec-Ch-Ua-Mobile: ?0',
    'Applicationname: VSP',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Accept: application/vnd.form6.app.v2+json',
    'Channelidobo: VSP',
    'Content-Type: application/x-www-form-urlencoded',
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Site: same-site',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=1, i',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 $response = curl_exec($ch);
curl_close($ch);
//  Location URL match karna
preg_match('/location:\s*([^\s]+)/i', $response, $matchLocation);
 $location = $matchLocation[1] ?? '';

// Query string nikalna
$parts = parse_url($location);

// Query string ko parse karke array banana
parse_str($parts['query'] ?? '', $query);

// refId nikalna
$refId = $query['refId'] ?? '';

if($refId==true){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://gateway-voters.eci.gov.in/api/v1/nvsp/validate/referenceNumber/'.$refId);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: gateway-voters.eci.gov.in',
    'Sec-Ch-Ua-Platform: "Windows"',
    'Authorization: Bearer '.$access_token,
    'Platform-Type: ECIWEB',
    'Atkn_bnd: '.$atkn_bnd,
    'Rtkn_bnd: '.$rtkn_bnd,
    'Sec-Ch-Ua: "Google Chrome";v="143", "Chromium";v="143", "Not A(Brand";v="24"',
    'Sec-Ch-Ua-Mobile: ?0',
    'Applicationname: VSP',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Currentrole: citizen',
    'Channelidobo: VSP',
    'Content-Type: application/json',
    'State: '.$tokenbase64['statecode'],
    'Accept: */*',
    'Origin: https://voters.eci.gov.in',
    'Sec-Fetch-Site: same-site',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: en-US,en;q=0.9',
    'Priority: u=1, i',
    'Connection: keep-alive',
]);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

 $response = curl_exec($ch);
curl_close($ch);

if(preg_match('/Success/mi',$response)){
echo $response;
}else if(preg_match('/No such record found/mi',$response)){
echo '{"message":"Aadhar Data Not Match According EPIC"}';
}else{
    echo '{"hint":"validate/referenceNumber"}';
} 
}else{
    echo '{"hint":"aadhaar-esign/signed_pdf"}';
}
}else if($responseuidjson['status']=="0"){
echo '{"message":"Invalid OTP Please enter New OTP"}';
}else if(preg_match('/sessionExpiredReq/mi',$responseotp)){
echo '{"message":"Invalid OTP Please enter New OTP"}';
}else{
   echo '{"message":"Invalid OTP Please enter New OTP"}';
}
}