<?php
// Set headers for JSON response and handle CORS
header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");

// Require your existing PdfController
require_once 'PdfController.php';

// Helper function: Convert exactly from your HTML pixels to TCPDF millimeters
function px2mm($px) {
    return $px * 0.264583333; // Standard 96 DPI conversion
}

// === 1. EsaCrypto Class for Decryption ===
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");
        }
        return openssl_decrypt($cipherRaw, "AES-256-CBC", $this->key, OPENSSL_RAW_DATA, $this->iv);
    }
}

// Helper function to format the address
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;
}

// Helper function to output JSON error with pretty print and exit
function outputError($message) {
    echo json_encode([
        "status" => "error",
        "message" => $message
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    exit();
}

// === 2. Validate Inputs & Form Data ===
if (!isset($_GET['uid_number']) || !isset($_GET['state_name'])) {
    outputError("Missing uid_number or state_name parameters");
}

$uidno = preg_replace('/[^0-9]+/', '', $_GET['uid_number']);
$statename = strtolower(preg_replace('/[^a-zA-Z0-9-& \/]+/', '', $_GET['state_name']));

if (empty($uidno) || empty($statename)) {
    outputError("Invalid input parameters provided");
}

// Extra form data
$castename = $_GET['caste'] ?? '';
$areatype = $_GET['area'] ?? '';
$landkhata = $_GET['khata'] ?? '';
$landkhasra = $_GET['khasra'] ?? '';
$landarea = $_GET['landarea'] ?? '';

// === 3. State Mapping ===
$statelogo = "statelogo/ashok.png"; 
$weburl = "";
$origin = "";
$defaultLang = "hi";

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

if (isset($stateConfigs[$statename])) {
    $weburl = $stateConfigs[$statename][0];
    $origin = $stateConfigs[$statename][1];
    $statelogo = "statelogo/" . $stateConfigs[$statename][2];
    $defaultLang = $stateConfigs[$statename][3];
} else {
    outputError("Service is not available for this state");
}

$locallanguage = $_GET['language'] ?? $defaultLang;

// 🔥 DYNAMIC FONT SELECTION (Fixed by you!) 🔥
$docFont = 'freeserif'; // Default font for other languages
if ($locallanguage === 'ta') {
    // Kyunki aapki file 'tamil.ttf' hai, toh TCPDF me iska naam 'tamil' hoga
    $docFont = 'tamil'; 
}

// === 4. Fetch Agristack Data ===
$key = "etatsnoitacilppa23bewRCkcatsirga"; 
$iv  = "1224222432244424";                
$esa = new EsaCrypto($key, $iv);

$dataPayload = ["farmerAadhaarHash" => $uidno];
$encrypted = $esa->encrypt(json_encode($dataPayload));

$curlHeaders = [
    'accept: application/json, text/plain, */*',
    'content-type: application/json',
    'origin: '.$origin,
    'referer: '.$weburl,
    'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
];

// Check Approval Status
$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, $curlHeaders);
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'] === "Not Registered" || $responsejson['data']['farmerNumber'] == false) {
    outputError("Farmer is Not Registered or Pending Approval");
}

$farmerId = $responsejson['data']['centralId'];
$verifiedOn = $responsejson['data']['verifiedOn'] ?? time();

// Get EKYC Details
$curlHeadersEkyc = [
    'accept: application/json, text/plain, */*',
    'content-type: text/plain',
    'origin: '.$origin,
    'referer: '.$weburl,
    'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
];

$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, $curlHeadersEkyc);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encrypted);
$responseEkyc = curl_exec($ch);
curl_close($ch);

$myjsonde = json_decode($responseEkyc, true);

if (!isset($myjsonde['code']) || $myjsonde['code'] != "200") {
    outputError("Failed to fetch EKYC details: " . ($myjsonde['message'] ?? 'Unknown Error'));
}

$decrypted = $esa->decrypt($myjsonde['data']);
$farmerData = json_decode($decrypted, true);

// Format Information
date_default_timezone_set("Asia/Kolkata");
$sec = $farmerData['dob'] / 1000;
$formattedDob = date("d/m/Y", $sec);
$address = makeAddress([$farmerData['ekycLLCo'] ?? $farmerData['ekycCo'] ?? '', $farmerData['ekycLLVtc'] ?? $farmerData['ekycVtc'] ?? '', $farmerData['ekycLLDist'] ?? $farmerData['ekycDist'] ?? '', $farmerData['ekycLLState'] ?? $farmerData['ekycState'] ?? ''], 'ekycLLPincode', $farmerData);
$genderDesc = $farmerData['gender']['genderDescEng'] ?? '';
$genderShort = (strtolower($genderDesc) === 'male') ? 'M' : ((strtolower($genderDesc) === 'female') ? 'F' : 'T');

// Manual Gender Translation Logic
$genderTrans = '';
if ($genderShort == 'M') {
    $genderOpts = ['hi'=>'पुरुष/Male', 'kn'=>'ಪುರುಷ/Male', 'bn'=>'পুরুষ/Male', 'pa'=>'ਮਰਦ/Male', 'gu'=>'પુરુષ/Male', 'te'=>'పురుషుడు/Male', 'or'=>'ପୁରୁଷ/Male', 'mr'=>'पुरुष/Male', 'en'=>'Male', 'ta'=>'ஆண்/Male', 'ml'=>'ആൺ/Male'];
    $genderTrans = $genderOpts[$locallanguage] ?? 'Male';
} else if ($genderShort == 'F') {
    $genderOpts = ['hi'=>'महिला/Female', 'kn'=>'ಹೆಣ್ಣು/Female', 'bn'=>'মহিলা/Female', 'pa'=>'ਔਰਤ/Female', 'gu'=>'સ્ત્રી/Female', 'te'=>'స్త్రీ/Female', 'or'=>'ମହିଳା/Female', 'mr'=>'महिला/Female', 'en'=>'Female', 'ta'=>'பெண்/Female', 'ml'=>'പെൺ/Female'];
    $genderTrans = $genderOpts[$locallanguage] ?? 'Female';
} else {
    $genderTrans = $genderDesc;
}

$aadhaarNumberPlain = base64_decode($farmerData['aadhaarNumberBase64'] ?? '');
$careofname = $farmerData['ekycLLCo'] ?? $farmerData['ekycCo'] ?? '';
$distt = $farmerData['ekycLLDist'] ?? $farmerData['ekycDist'] ?? '';
$stateStr = $farmerData['ekycLLState'] ?? $farmerData['ekycState'] ?? '';
$pincode = $farmerData['ekycLLPincode'] ?? '';
$originsite = preg_replace('#^https?://#', '', $origin);

// === 5. PDF Generation via TCPDF/PdfController ===
try {
    $pageW = px2mm(893);
    $pageH = px2mm(1262);

    $pdf = new PdfController('P', 'mm', [$pageW, $pageH], true, 'UTF-8', false);
    
    $pdf->SetMargins(0, 0, 0);
    $pdf->SetAutoPageBreak(FALSE, 0);
    $pdf->AddPage('P', [$pageW, $pageH]);

    if (file_exists('farmerbgnews.png')) {
        $pdf->addImage(0, 0, 'farmerbgnews.png', ['width' => $pageW, 'height' => $pageH]);
    } else if (file_exists('farmerbgnews.jpg')) {
        $pdf->addImage(0, 0, 'farmerbgnews.jpg', ['width' => $pageW, 'height' => $pageH]);
    }

    if (file_exists($statelogo)) {
        $pdf->addImage(px2mm(759), px2mm(47), $statelogo, ['width' => px2mm(38), 'height' => px2mm(41)]);
    }

    if (!empty($farmerData['ekycPhotoBaseStr'])) {
        $imgData = base64_decode($farmerData['ekycPhotoBaseStr']);
        $pdf->addImage(px2mm(88), px2mm(108), '@' . $imgData, ['width' => px2mm(82.6), 'height' => px2mm(103)]);
    }

    $xmlData = '<?xml version="1.0"?>
<QDB farmerId="'.$farmerId.'" AadhaarNo="'.$aadhaarNumberPlain.'" Name="'.($farmerData['aadhaarName'] ?? '').'" Dob="'.$formattedDob.'" Gender="'.$genderShort.'" C/O="'.$careofname.'" Address="'.$address.'" District="'.$distt.'" State="'.$stateStr.'" Pincode="'.$pincode.'"/>';
    
    $targetWidthMm = px2mm(68);
    $fixedSize = $targetWidthMm / 2.83465;
    
    $pdf->addQrCode(px2mm(346), px2mm(161), $xmlData, ['size' => $fixedSize]); 

    // --- WRITE TEXT ---

    $govtLocals = ['hi' => 'भारत सरकार', 'en' => 'Government of India', 'bn' => 'ভারত সরকার', 'pa' => 'ਭਾਰਤ ਸਰਕਾਰ', 'gu' => 'ભારત સરકાર', 'mr' => 'भारत सरकार', 'kn' => 'ಭಾರತ ಸರ್ಕಾರ', 'te' => 'భారత ప్రభుత్వం', 'ta' => 'இந்திய அரசு', 'ml' => 'ഇന്ത്യ സർക്കാർ', 'or' => 'ଭାରତ ସରକାର'];
    $pdf->addText(px2mm(214), px2mm(52), $govtLocals[$locallanguage] ?? 'Government of India', ['font' => $docFont, 'size' => 8, 'style' => 'B', 'color' => [255, 164, 0]]);
    $pdf->addText(px2mm(178), px2mm(70), "Government of India", ['font' => 'freeserif', 'size' => 12, 'style' => 'B', 'color' => [0, 127, 0]]);

    $ministryText = ['hi' => 'कृषि एवं किसान कल्याण मंत्रालय', 'en' => 'Ministry of Agriculture & Farmers Welfare', 'bn' => 'কৃষি ও কৃষক কল্যাণ মন্ত্রক', 'pa' => 'ਖੇਤੀਬਾੜੀ ਅਤੇ ਕਿਸਾਨ કલਿਆਣ ਮੰਤਰਾਲਾ', 'gu' => 'કૃષિ અને ખેડૂત કલ્યાણ મંત્રાલય', 'mr' => 'कृषी व शेतकरी कल्याण मंत्रालय', 'kn' => 'ಕೃಷಿ ಮತ್ತು ರೈತ ಕಲ್ಯಾಣ ಸಚಿವಾಲಯ', 'te' => 'వ్యవసాయ మరియు రైతు సంక్షేమ మంత్రిత్వ శాఖ', 'ta' => 'வேளாண்மை மற்றும் விவசாயிகள் நல அமைச்சகம்', 'ml' => 'കൃഷിയും കർഷക ക്ഷേമവും മന്ത്രാലയം', 'or' => 'କୃଷି ଓ କୃଷକ କଲ୍ୟାଣ ମନ୍ତ୍ରଣାଳୟ'];
    $pdf->addText(px2mm(536), px2mm(55), $ministryText[$locallanguage] ?? 'Ministry of Agriculture & Farmers Welfare', ['font' => $docFont, 'size' => 6, 'style' => 'B', 'color' => [255, 164, 0]]);
    $pdf->addText(px2mm(534), px2mm(73), "Ministry of Agri & Farmers Welfare", ['font' => 'freeserif', 'size' => 9, 'style' => 'B', 'color' => [0, 127, 0]]);

    $nameLocals = ['hi'=>'नाम', 'en'=>'Name', 'bn'=>'নাম', 'pa'=>'ਨਾਮ', 'gu'=>'નામ', 'mr'=>'नाव', 'kn'=>'ಹೆಸರು', 'te'=>'పేరు', 'ta'=>'பெயர்', 'ml'=>'പേര്', 'or'=>'ନାମ'];
    $pdf->addText(px2mm(186), px2mm(106), $nameLocals[$locallanguage] ?? 'Name', ['font' => $docFont, 'size' => 7.5, 'style' => 'B']);
    $pdf->addText(px2mm(186), px2mm(120), "Name", ['font' => 'freeserif', 'size' => 7.5, 'style' => 'B']);
    $pdf->addText(px2mm(186), px2mm(133), "Gender", ['font' => 'freeserif', 'size' => 7.5, 'style' => 'B']);
    $pdf->addText(px2mm(186), px2mm(146), "DOB", ['font' => 'freeserif', 'size' => 7.5, 'style' => 'B']);
    $pdf->addText(px2mm(186), px2mm(159), "Caste", ['font' => 'freeserif', 'size' => 7.5, 'style' => 'B']);
    $pdf->addText(px2mm(186), px2mm(173), "Area", ['font' => 'freeserif', 'size' => 7.5, 'style' => 'B']);
    $pdf->addText(px2mm(186), px2mm(186), "Aadhaar", ['font' => 'freeserif', 'size' => 7.5, 'style' => 'B']);

    // Left Column Values
    // Yahan Name, Gender aur address Local waale me aayega isliye inme $docFont set hai
    $pdf->addText(px2mm(248), px2mm(106), $farmerData['ekycLLAadhaarName'] ?? ($farmerData['aadhaarName'] ?? ''), ['font' => $docFont, 'size' => 6, 'style' => 'B']);
    $pdf->addText(px2mm(248), px2mm(120), $farmerData['aadhaarName'] ?? '', ['font' => 'freeserif', 'size' => 6, 'style' => 'B']);
    $pdf->addText(px2mm(248), px2mm(133), $genderTrans, ['font' => $docFont, 'size' => 6, 'style' => 'B']);
    $pdf->addText(px2mm(248), px2mm(146), $formattedDob, ['font' => 'freeserif', 'size' => 6, 'style' => 'B']);
    $pdf->addText(px2mm(248), px2mm(159), $castename, ['font' => 'freeserif', 'size' => 6, 'style' => 'B']);
    $pdf->addText(px2mm(248), px2mm(173), $areatype, ['font' => 'freeserif', 'size' => 6, 'style' => 'B']);
    $pdf->addText(px2mm(248), px2mm(186), $aadhaarNumberPlain, ['font' => 'freeserif', 'size' => 6, 'style' => 'B']);

    // Farmer ID Green
    $pdf->addText(px2mm(154), px2mm(219), "Farmer ID : " . $farmerId, ['font' => 'freeserif', 'size' => 10.5, 'style' => 'B', 'color' => [0, 127, 0]]);
    $pdf->addText(px2mm(169), px2mm(253), $stateStr . " Farmer Registry", ['font' => $docFont, 'size' => 9, 'style' => 'B']);

    $pdf->addText(px2mm(77), px2mm(255), "Approval Date: " . date("d/m/Y", strtotime($verifiedOn)), ['font' => 'freeserif', 'size' => 5, 'style' => 'B', 'rotation' => 90]);
    $pdf->addText(px2mm(455), px2mm(255), "Download Date : " . date("d/m/Y", time()), ['font' => 'freeserif', 'size' => 5, 'style' => 'B', 'rotation' => 90]);

    // Right Column Info (Address bhi dynamically $docFont uthayega)
    $pdf->addText(px2mm(466), px2mm(99), "Address:", ['font' => 'freeserif', 'size' => 6, 'style' => 'B']);
    $pdf->addText(px2mm(466), px2mm(111), $address, ['font' => $docFont, 'size' => 6, 'style' => 'B', 'maxwidth' => px2mm(260)]);

    $pdf->addText(px2mm(504), px2mm(147), "Khata", ['font' => 'freeserif', 'size' => 6, 'style' => 'B']);
    $pdf->addText(px2mm(608), px2mm(147), "Khasra", ['font' => 'freeserif', 'size' => 6, 'style' => 'B']);
    $pdf->addText(px2mm(719), px2mm(147), "Area", ['font' => 'freeserif', 'size' => 6, 'style' => 'B']);

    $pdf->addText(px2mm(516), px2mm(161), $landkhata, ['font' => 'freeserif', 'size' => 6, 'style' => 'B']);
    $pdf->addText(px2mm(617), px2mm(161), $landkhasra, ['font' => 'freeserif', 'size' => 6, 'style' => 'B']);
    $pdf->addText(px2mm(691), px2mm(161), $landarea, ['font' => 'freeserif', 'size' => 6, 'style' => 'B']);

    // Footer Links
    $pdf->addText(px2mm(506), px2mm(254), "1800-180-1551", ['font' => 'freeserif', 'size' => 7.5, 'style' => 'B']);
    $pdf->addText(px2mm(648), px2mm(254), "www." . $originsite, ['font' => 'freeserif', 'size' => 7.5, 'style' => 'B']);

    // === 6. Output Base64 JSON ===
    $pdfString = $pdf->Output('', 'S');
    $base64Pdf = base64_encode($pdfString);

    $responsePayload = [
        "status" => "success",
        "message" => "PDF Generated Successfully",
        "txn_id" => "TXN" . strtoupper(uniqid()),
        "pdf_base64" => $base64Pdf
    ];

    echo json_encode($responsePayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    outputError("PDF Generation Failed: " . $e->getMessage());
}
?>