<?php
/**
 * Smart Auto-State API (getFarmerEkycDetailsV2)
 * Just send the uid_number, the script will automatically find the correct state.
 */

header('Content-Type: application/json; charset=utf-8');

// 1. Encryption & Decryption Class
class EsaCrypto {
    private $key = "etatsnoitacilppa23bewRCkcatsirga"; 
    private $iv  = "1224222432244424";

    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) return false;
        return openssl_decrypt($cipherRaw, "AES-256-CBC", $this->key, OPENSSL_RAW_DATA, $this->iv);
    }
}

// 2. Fetch UID from GET request
$uidno = $_GET['uid_number'] ?? '';

if (empty($uidno) || !preg_match('/^\d{12}$/', $uidno)) {
    echo json_encode(["status" => "failed", "code" => 400, "message" => "Please provide a valid 12-digit uid_number."]);
    exit();
}


$stateConfigs = [

    "andhra pradesh" => [
        "weburl" => "https://apfr.agristack.gov.in/farmer-registry-api-ap",
        "origin" => "https://apfr.agristack.gov.in"
    ],

    "assam" => [
        "weburl" => "https://asfr.agristack.gov.in/farmer-registry-api-as",
        "origin" => "https://asfr.agristack.gov.in"
    ],

    "bihar" => [
        "weburl" => "https://bhfr.agristack.gov.in/farmer-registry-api-bh",
        "origin" => "https://bhfr.agristack.gov.in"
    ],

    "chhattisgarh" => [
        "weburl" => "https://cgfr.agristack.gov.in/farmer-registry-api-cg",
        "origin" => "https://cgfr.agristack.gov.in"
    ],

    "gujarat" => [
        "weburl" => "https://gjfr.agristack.gov.in/farmer-registry-api-gj",
        "origin" => "https://gjfr.agristack.gov.in"
    ],

    "haryana" => [
        "weburl" => "https://hrfr.agristack.gov.in/farmer-registry-api-hr",
        "origin" => "https://hrfr.agristack.gov.in"
    ],

    "jharkhand" => [
        "weburl" => "https://jhfr.agristack.gov.in/farmer-registry-api-jh",
        "origin" => "https://jhfr.agristack.gov.in"
    ],

    "karnataka" => [
        "weburl" => "https://knfr.agristack.gov.in/farmer-registry-api-kn",
        "origin" => "https://knfr.agristack.gov.in"
    ],

    "madhya pradesh" => [
        "weburl" => "https://mpfr.agristack.gov.in/farmer-registry-api-mp",
        "origin" => "https://mpfr.agristack.gov.in"
    ],

    "maharashtra" => [
        "weburl" => "https://mhfr.agristack.gov.in/farmer-registry-api-mh",
        "origin" => "https://mhfr.agristack.gov.in"
    ],

    "odisha" => [
        "weburl" => "https://odfr.agristack.gov.in/farmer-registry-api-od",
        "origin" => "https://odfr.agristack.gov.in"
    ],

    "punjab" => [
        "weburl" => "https://pbfr.agristack.gov.in/farmer-registry-api-pb",
        "origin" => "https://pbfr.agristack.gov.in"
    ],

    "rajasthan" => [
        "weburl" => "https://rjfr.agristack.gov.in/farmer-registry-api-rj",
        "origin" => "https://rjfr.agristack.gov.in"
    ],

    "tamil nadu" => [
        "weburl" => "https://tnfr.agristack.gov.in/farmer-registry-api-tn",
        "origin" => "https://tnfr.agristack.gov.in"
    ],

    "telangana" => [
        "weburl" => "https://tlfr.agristack.gov.in/farmer-registry-api-tl",
        "origin" => "https://tlfr.agristack.gov.in"
    ],

    "uttar pradesh" => [
        "weburl" => "https://upfr.agristack.gov.in/farmer-registry-api-up",
        "origin" => "https://upfr.agristack.gov.in"
    ],

    "uttarakhand" => [
        "weburl" => "https://ukfr.agristack.gov.in/farmer-registry-api-uk",
        "origin" => "https://ukfr.agristack.gov.in"
    ]

];

$crypto = new EsaCrypto();
$encryptedPayload = $crypto->encrypt(json_encode(["farmerAadhaarHash" => $uidno]));

$lastApiMessage = "Record not found in any active state."; // Default fallback message

// 4. SMART LOOP - Checks each state one by one
foreach ($stateConfigs as $stateName => $config) {
    $webUrl = $config['weburl'];
    $origin = $config['origin'];

    $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_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $encryptedPayload);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 5-second timeout per state for speed
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: text/plain',
        'Origin: ' . $origin,
        'Referer: ' . $origin . '/',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode == 200 && $response) {
        $resJson = json_decode($response, true);
        
        // Save the latest message returned by the API
        if (isset($resJson['message']) && !empty($resJson['message'])) {
            $lastApiMessage = $resJson['message']; 
        }
        
        // If the code is 200 and data is not empty, process the payload
        if (isset($resJson['code']) && $resJson['code'] == "200" && !empty($resJson['data'])) {
            $decryptedData = $crypto->decrypt($resJson['data']);
            $farmer = json_decode($decryptedData, true);

            // If valid data is found and the name is not empty
            if ($farmer && !empty($farmer['aadhaarName'])) {
                date_default_timezone_set("Asia/Kolkata");
                $dobSeconds = ($farmer['dob'] ?? 0) / 1000;
                
                echo json_encode([
                    "status" => "success",
                    "code" => 200,
                    "found_in_state" => ucwords($stateName),
                    "data" => [
                        "aadhaar_number" => $uidno,
                        "name" => $farmer['aadhaarName'] ?? '',
                        "name_local" => $farmer['ekycLLAadhaarName'] ?? '',
                        "gender" => $farmer['gender']['genderDescEng'] ?? '',
                        "dob" => ($dobSeconds > 0) ? date("d/m/Y", $dobSeconds) : '',
                        "district" => $farmer['ekycDist'] ?? '',
                        "state" => $farmer['ekycState'] ?? '',
                        "full_address" => trim(($farmer['ekycCo'] ?? '') . ", " . ($farmer['ekycVtc'] ?? '') . ", " . ($farmer['ekycDist'] ?? '') . ", " . ($farmer['ekycState'] ?? '') . " - " . ($farmer['ekycLLPincode'] ?? ''), ", "),
                        "photo" => $farmer['ekycPhotoBaseStr'] ?? ''
                    ]
                ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                exit(); // Stop the script immediately once data is found
            }
        }
    }
    // If not found in this state, the loop moves to the next one
}

// 5. If no record is found in any state, output the actual API message
echo json_encode([
    "status" => "failed",
    "code" => 404,
    "message" => $lastApiMessage
], JSON_PRETTY_PRINT);
?>