<?php
// get_farmer_data.php - Smart Single Endpoint File for Farmer Data (Multistate Support)

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

// 1. Check GET Method
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(["status" => "failed", "code" => 405, "message" => "Method Not Allowed.", "data" => false]);
    exit();
}

// 2. Fetch Parameter
$uidno = $_GET['uid_number'] ?? '';

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

// 4. Encode Aadhaar to Base64
$base64Aadhaar = base64_encode($uidno);

// 5. All State Configurations
$stateConfigs = [
    "maharashtra" => ["weburl" => "https://mhfr.agristack.gov.in/farmer-registry-api-mh", "origin" => "https://mhfr.agristack.gov.in"],
    "haryana" => ["weburl" => "https://hrfr.agristack.gov.in/farmer-registry-api-hr", "origin" => "https://hrfr.agristack.gov.in"],
    "bihar" => ["weburl" => "https://bhfr.agristack.gov.in/farmer-registry-api-bh", "origin" => "https://bhfr.agristack.gov.in"],
    "madhya pradesh" => ["weburl" => "https://mpfr.agristack.gov.in/farmer-registry-api-mp-web", "origin" => "https://mpfr.agristack.gov.in"],
    "chhattisgarh" => ["weburl" => "https://cgfr.agristack.gov.in/farmer-registry-api-cg", "origin" => "https://cgfr.agristack.gov.in"],
    "punjab" => ["weburl" => "https://pbfr.agristack.gov.in/farmer-registry-api-pb", "origin" => "https://pbfr.agristack.gov.in"],
    "assam" => ["weburl" => "https://asfr.agristack.gov.in/farmer-registry-api-as-mis", "origin" => "https://asfr.agristack.gov.in"],
    "mizoram" => ["weburl" => "https://mzdcs.agristack.gov.in/agristack_ag_mz/crop-survey-api-beta", "origin" => "https://mzdcs.agristack.gov.in"],
    "arunachal pradesh" => ["weburl" => "https://ardcs.agristack.gov.in/agristack_ag_ar/crop-survey-api", "origin" => "https://ardcs.agristack.gov.in"],
    "andhra pradesh" => ["weburl" => "https://apfr.agristack.gov.in/farmer-registry-api-ap", "origin" => "https://apfr.agristack.gov.in"],
    "telangana" => ["weburl" => "https://tlfr.agristack.gov.in/farmer-registry-api-tl", "origin" => "https://tlfr.agristack.gov.in"],
    "tripura" => ["weburl" => "https://trfr.agristack.gov.in/farmer-registry-api-tr", "origin" => "https://trfr.agristack.gov.in"],
    "uttarakhand" => ["weburl" => "https://ukfr.agristack.gov.in/farmer-registry-api-uk", "origin" => "https://ukfr.agristack.gov.in"],
    "jharkhand" => ["weburl" => "https://jhfr.agristack.gov.in/farmer-registry-api-jh", "origin" => "https://jhfr.agristack.gov.in"],
    "kerala" => ["weburl" => "https://klfr.agristack.gov.in/farmer-registry-api-kl", "origin" => "https://klfr.agristack.gov.in"],
    "rajasthan" => ["weburl" => "https://rjfr.agristack.gov.in/farmer-registry-api-rj", "origin" => "https://rjfr.agristack.gov.in"],
    "west bengal" => ["weburl" => "https://wbfr.agristack.gov.in/farmer-registry-api-wb", "origin" => "https://wbfr.agristack.gov.in"],
    "tamil nadu" => ["weburl" => "https://tnfr.agristack.gov.in/farmer-registry-api-tn", "origin" => "https://tnfr.agristack.gov.in"],
    "karnataka" => ["weburl" => "https://knfr.agristack.gov.in/farmer-registry-api-kn", "origin" => "https://knfr.agristack.gov.in"],
    "odisha" => ["weburl" => "https://odfr.agristack.gov.in/farmer-registry-api-od", "origin" => "https://odfr.agristack.gov.in"],
    "gujarat" => ["weburl" => "https://gjfr.agristack.gov.in/farmer-registry-api-gj", "origin" => "https://gjfr.agristack.gov.in"],
    "uttar pradesh" => ["weburl" => "https://upfr.agristack.gov.in/farmer-registry-api-up", "origin" => "https://upfr.agristack.gov.in"],
    "himachal pradesh" => ["weburl" => "https://hpfr.agristack.gov.in/farmer-registry-api-hp", "origin" => "https://hpfr.agristack.gov.in"]
];

// 6. Active States (Jin states ke token 'cron_txt_file' me hain)
$activeStates = ["gujarat", "andhra pradesh", "tamil nadu", "bihar"];

// 7. cURL Call Function with dynamic headers
function makeApiCall($url, $token, $host, $origin, $referer) {
    $headers = [
        'Accept: application/json, text/plain, */*',
        'Accept-Encoding: gzip, deflate, br, zstd',
        'Accept-Language: en-US,en;q=0.9',
        'Authorization: Bearer ' . $token,
        'Connection: keep-alive',
        'Host: ' . $host,
        'Origin: ' . $origin,
        'Referer: ' . $referer,
        '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 Chrome/117.0.0.0 Safari/537.36'
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_ENCODING, ''); 
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return ['code' => $httpCode, 'response' => json_decode($response, true)];
}

// 8. SMART LOOP - Har state me check karega
foreach ($activeStates as $stateKey) {
    $config = $stateConfigs[$stateKey];
    
    // Read token from cron_txt_file directory
    $fileName = 'token_' . str_replace(' ', '_', $stateKey) . '.txt';
    $tokenFile = __DIR__ . '/cron_txt_file/' . $fileName;

    if (!file_exists($tokenFile)) continue;
    $bearerToken = trim(file_get_contents($tokenFile));
    if (empty($bearerToken)) continue;

    $baseUrl = $config['weburl'] . "/agristack/v1/api";
    $host = parse_url($config['origin'], PHP_URL_HOST);
    $referer = $config['origin'] . "/";
    $url = $baseUrl . "/farmerRegistry/getFarmerDataByAadhaar?aadhaarNumber=" . $base64Aadhaar;

    $apiResult = makeApiCall($url, $bearerToken, $host, $config['origin'], $referer);
    $httpCode = $apiResult['code'];
    $mainRes = $apiResult['response'] ?? [];

    // Check if API call was successful and has data
    if ($httpCode == 200 && isset($mainRes['data']) && isset($mainRes['data']['farmerDetails'])) {
        
        $res = $mainRes['data'];
        $fd = $res['farmerDetails'] ?? [];
        
        // --- STRICT NAME CHECK ---
        $farmerNameEn = trim($fd['farmerNameEn'] ?? '');
        $farmerNameLocal = trim($fd['farmerNameLocal'] ?? '');
        
        // Agar real name milta hai tabhi aage process karenge
        if (!empty($farmerNameEn) || !empty($farmerNameLocal)) {
            
            $ext = $fd['farmerExtendedRegistry'] ?? [];
            $bank = $fd['farmerBankDetails'] ?? [];
            $lands = $res['farmerLandOwnerShips'] ?? [];

            // --- Format Occupation ---
            $occs = [];
            if (isset($res['finalOccupationList'])) {
                foreach ($res['finalOccupationList'] as $o) {
                    $occs[] = $o['farmerOccuptationType'] ?? '';
                }
            }

            // --- Format Land Details ---
            $land_arr = [];
            $totalLandAreaCalc = 0;
            
            foreach ($lands as $l) {
                $plot = $l['farmlandPlotRegistryId'] ?? [];
                $vill = $plot['villageLgdMaster'] ?? [];
                
                $area = $l['extentTotalAreaInHectare'] ?? 0;
                $totalLandAreaCalc += (float)$area;

                $land_arr[] = [
                    "State" => $vill['stateLgdCode']['stateName'] ?? '',
                    "District" => $vill['districtLgdCode']['districtName'] ?? '',
                    "SubDistrict" => $vill['subDistrictLgdCode']['subDistrictName'] ?? '',
                    "Village" => $vill['villageName'] ?? '',
                    "SurveyNumber" => $plot['surveyNumber'] ?? '',
                    "SubSurveyNumber" => $plot['subSurveyNumber'] ?? '',
                    "OwnerNumber" => $l['ownerNoAsPerRor'] ?? '',
                    "MainOwnerNumber" => $l['mainOwnerNoAsPerRor'] ?? '',
                    "OwnerName" => $l['ownerNamePerRor'] ?? '',
                    "IdentifierName" => $l['ownerIdentifierNamePerRor'] ?? 'Not Available',
                    "OwnerType" => $l['ownerTypeName'] ?? '',
                    "OwnerShareType" => $l['ownerShareTypeName'] ?? '',
                    "ExtentTotalArea" => number_format((float)$area, 6, '.', ''),
                    "ExtentTotalAreaFinal" => number_format((float)$area, 6, '.', ''),
                    "ExtentAssignedArea" => number_format((float)($l['extentAssignedAreaInHectare'] ?? 0), 6, '.', ''),
                    "ExtentAssignedAreaFinal" => number_format((float)($l['extentAssignedAreaInHectare'] ?? 0), 6, '.', ''),
                    "OwnerNameMatchScore" => "Name Match Score : " . ($l['farmerNameMatchScoreRor'] ?? ''),
                    "LandSource" => (!empty($l['isSfdbData']) ? 'SFDB' : ''),
                    "Verified" => (!empty($l['isVerified']) ? 'Yes' : 'No')
                ];
            }

            // --- Total Area Logic ---
            $totalLandArea = $fd['farmerTotalLandOwned'] ?? 0;
            if ($totalLandArea == 0 && $totalLandAreaCalc > 0) {
                $totalLandArea = $totalLandAreaCalc;
            }

            // --- FINAL MAPPED OUTPUT ---
            $formattedData = [
                "AadhaarDetails" => [
                    "AadhaarNumber" => $uidno,
                    "Verified" => $fd['aadharVerified'] ?? false,
                    "StateName" => ucwords($stateKey) // Yahan state ka naam add kar diya taaki pata chale kahan se data aaya
                ],
                "ContactDetails" => [
                    "MobileNumber" => $fd['farmerMobileNumber'] ?? '',
                    "MobileVerified" => $fd['isMobileVerified'] ?? false,
                    "EmailAddress" => "",
                    "EmailVerified" => $fd['isEmailVerified'] ?? false
                ],
                "FarmerDetails" => [
                    "FarmerNameEn" => $farmerNameEn,
                    "FarmerNameLocal" => $farmerNameLocal,
                    "Gender" => $fd['farmerGenederType']['genderDescEng'] ?? '',
                    "CasteCategory" => $fd['famerCasteCategory']['casteCategoryDescEng'] ?? '',
                    "DateOfBirth" => $fd['farmerDob'] ?? '',
                    "Age" => $fd['farmerAge'] ?? '',
                    "IdentifierType" => $fd['farmerIdentifierType']['identifierTypeDescEng'] ?? '',
                    "IdentifierNameEn" => $fd['farmerIdentifierNameEn'] ?? '',
                    "IdentifierNameLocal" => $fd['farmerIdentifierNameLocal'] ?? ''
                ],
                "ExtendedFields" => [
                    "FarmerPhotograph" => $ext['ferFarmerPhotograph'] ?? '',
                    "PANNumber" => $ext['panNumber'] ?? '',
                    "MinorityReligion" => $ext['minorityReligion'] ?? '',
                    "KCCNumber" => $ext['ferKisanKccNumber'] ?? '',
                    "KCCAmount" => "",
                    "KCCBankName" => "",
                    "SavingsBankName" => "",
                    "SavingsBranchCode" => $bank['fbd_branch_code'] ?? '',
                    "IFSCCode" => $bank['fbd_ifsc_code'] ?? '',
                    "BankAccountNumber" => $bank['fbd_account_number'] ?? '',
                    "FarmerDisabilities" => []
                ],
                "ResidentialDetails" => [
                    "ResidentialType" => $fd['farmerLocationType']['locationTypeDescEng'] ?? '',
                    "AddressEn" => $fd['farmerAddressEn'] ?? '',
                    "AddressLocal" => $fd['farmerAddressLocal'] ?? '',
                    "State" => $fd['villageLgdMaster']['stateLgdCode']['stateName'] ?? '',
                    "District" => $fd['villageLgdMaster']['districtLgdCode']['districtName'] ?? '',
                    "SubDistrict" => $fd['villageLgdMaster']['subDistrictLgdCode']['subDistrictName'] ?? '',
                    "Village" => $fd['villageLgdMaster']['villageName'] ?? '',
                    "PINCode" => $fd['farmerPinCode'] ?? ''
                ],
                "LandOwnershipDetails" => [
                    "FarmerType" => $fd['farmerType']['farmerTypeDescEng'] ?? '',
                    "OccupationDetails" => implode(" | ", $occs)
                ],
                "LandDetailsOwned" => $land_arr,
                "FarmerCategory" => [
                    "Category" => $fd['farmerCategory']['farmerCategoryDescEng'] ?? '',
                    "TotalLandAreaOwned" => number_format((float)$totalLandArea, 6, '.', ''),
                    "NumberOfLandsOwned" => $fd['farmerNumberOfLandOwned'] ?? ''
                ],
                "SocialRegistryDetails" => [
                    "LinkageType" => $fd['farmerSocialRegistryLinkageType'] ?? '',
                    "FamilyMemberId" => "",
                    "FamilyMemberResidentId" => ""
                ]
            ];

            // SUCCESS RESPONSE
            echo json_encode([
                "status" => "success",
                "code" => 200,
                "message" => "Farmer data retrieved successfully.",
                "data" => $formattedData
            ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            
            exit(); // Data mil gaya toh script yahin ruk jayegi
        }
    }
    // Agar nahi mila ya name khali nikla, toh loop continue karega naye state ke liye
}

// 9. FAIL RESPONSE (Agar poora loop chal gaya par kisi state me data nahi mila)
echo json_encode([
    "status" => "failed", 
    "code" => 400, 
    "message" => "Record not found in any active state or API failed.", 
    "data" => false
], JSON_PRETTY_PRINT);
exit();
?>