<?php
// Smart Aadhaar Search & Print ID Card

$uid_number = $_POST['uid_number'] ?? '';
$cardData = null;
$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($uid_number)) {
    // 1. Call Your API
    $apiUrl = "https://smartbot.in.net/aadhar-validate/get_farmer_data.php?uid_number=" . urlencode($uid_number);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);
    //echo $response;
    if ($response) {
        $data = json_decode($response, true);
        if (isset($data['code']) && $data['code'] == 200 && isset($data['data'])) {
            $cardData = $data['data'];
        } else {
            $error = "Record not found or API failed for this Aadhaar number.";
        }
    } else {
        $error = "Failed to connect to API.";
    }
}

// 2. Process Data if Found
if ($cardData) {
    // Extract Variables Safely
    $stateName = $cardData['AadhaarDetails']['StateName'] ?? 'Andhra Pradesh';
    $nameEn = $cardData['FarmerDetails']['FarmerNameEn'] ?? '';
    $nameLocal = $cardData['FarmerDetails']['FarmerNameLocal'] ?? '';
    $gender = $cardData['FarmerDetails']['Gender'] ?? '';
    
    $dob = $cardData['FarmerDetails']['DateOfBirth'] ?? '';
    if (!empty($dob)) $dob = date('d/m/Y', strtotime($dob));
    
    $caste = $cardData['FarmerDetails']['CasteCategory'] ?? '';
    $area = $cardData['ResidentialDetails']['ResidentialType'] ?? 'Rural';
    $aadhaar = $cardData['AadhaarDetails']['AadhaarNumber'] ?? '';
    
    // Farmer ID Format
    $farmerIdRaw = $cardData['AadhaarDetails']['AadhaarNumber'] ?? ''; // Assuming Farmer ID maps to something, or fallback
    // Since API doesn't give a direct "Farmer ID", we generate a formatted 12 digit format if needed or use Aadhaar
    $farmerId = substr($aadhaar, 0, 4) . ' ' . substr($aadhaar, 4, 4) . ' ' . substr($aadhaar, 8, 4); 

    $photoBase64 = $cardData['ExtendedFields']['FarmerPhotograph'] ?? '';

    // Address Parsing
    $coName = $cardData['FarmerDetails']['IdentifierNameEn'] ?? '';
    $addressEn = $cardData['ResidentialDetails']['AddressEn'] ?? '';
    $village = $cardData['ResidentialDetails']['Village'] ?? '';
    $subDistrict = $cardData['ResidentialDetails']['SubDistrict'] ?? '';
    $district = $cardData['ResidentialDetails']['District'] ?? '';
    $pin = $cardData['ResidentialDetails']['PINCode'] ?? '';

    $fullAddress = "C/O: $coName, $addressEn, $village, $subDistrict, $district, $stateName - $pin";

    // Lands Data
    $lands = $cardData['LandDetailsOwned'] ?? [];

    // 3. State Specific Logic (Translations, Logos)
    $stateKey = strtolower(trim($stateName));
    
    $localLang = 'hi';
    $govtOfIndiaLocal = 'भारत सरकार';
    $ministryLocal = 'कृषि एवं किसान कल्याण मंत्रालय';
    $nameLocalLabel = 'नाम';
    $genderMapping = ['Male' => 'पुरुष / Male', 'Female' => 'महिला / Female'];
    $statelogo = "statelogo/ashok.png"; 
    $domainPrefix = "ap";

    if (strpos($stateKey, 'andhra') !== false || strpos($stateKey, 'telangana') !== false) {
        $govtOfIndiaLocal = 'భారత ప్రభుత్వం';
        $ministryLocal = 'వ్యవసాయ మరియు రైతు సంక్షేమ మంత్రిత్వ శాఖ';
        $nameLocalLabel = 'పేరు';
        $genderMapping = ['Male' => 'పురుషుడు / Male', 'Female' => 'స్త్రీ / Female'];
        $statelogo = (strpos($stateKey, 'andhra') !== false) ? "statelogo/andhrapradesh.png" : "statelogo/telangana.png";
        $domainPrefix = (strpos($stateKey, 'andhra') !== false) ? "ap" : "tl";
    } elseif (strpos($stateKey, 'gujarat') !== false) {
        $govtOfIndiaLocal = 'ભારત સરકાર';
        $ministryLocal = 'કૃષિ અને ખેડૂત કલ્યાણ મંત્રાલય';
        $nameLocalLabel = 'નામ';
        $genderMapping = ['Male' => 'પુરુષ / Male', 'Female' => 'સ્ત્રી / Female'];
        $statelogo = "statelogo/gujarat.png";
        $domainPrefix = "gj";
    } elseif (strpos($stateKey, 'maharashtra') !== false) {
        $govtOfIndiaLocal = 'भारत सरकार';
        $ministryLocal = 'कृषी व शेतकरी कल्याण मंत्रालय';
        $nameLocalLabel = 'नाव';
        $genderMapping = ['Male' => 'पुरुष / Male', 'Female' => 'महिला / Female'];
        $statelogo = "statelogo/maharashtra.png";
        $domainPrefix = "mh";
    } 
    
    $websiteUrl = "www." . $domainPrefix . "fr.agristack.gov.in";

    // 4. Generate QR Code
    $codeContents = '<?xml version="1.0"?>
<QDB AadhaarNo="'.$aadhaar.'" Name="'.$nameEn.'" Dob="'.$dob.'" Gender="'.$gender.'" C/O="'.$coName.'" Address="'.$addressEn.'" District="'.$district.'" State="'.$stateName.'" Pincode="'.$pin.'"/>';

    // Safe QR Generation (Uses your library if exists, else remote API)
    $qrImageSrc = "";
    $qrLibPath = '../library/phpqrcode/qrlib.php';
    if (file_exists($qrLibPath)) {
        include_once($qrLibPath);
        ob_start(); 
        QRcode::png($codeContents, null, QR_ECLEVEL_Q, 4, 1);
        $imageString = ob_get_contents(); 
        ob_end_clean(); 
        $qrImageSrc = 'data:image/png;base64,' . base64_encode($imageString);
    } else {
        $qrImageSrc = 'https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=' . urlencode($codeContents);
    }

    $approvalDate = date('d/m/Y'); 
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AgriStack Card Search</title>
    <style>
        @page { margin: 0; }
        body {
            background-color: #f3f4f6;
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        /* Search Form Styles */
        .search-container {
            background: white;
            padding: 20px 40px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            text-align: center;
        }
        .search-container h2 { margin-top: 0; color: #166534; }
        .search-input {
            padding: 12px; font-size: 16px; width: 300px;
            border: 2px solid #ccc; border-radius: 5px; outline: none;
        }
        .search-btn, .print-btn {
            background: #166534; color: white; border: none; padding: 12px 25px;
            font-size: 16px; cursor: pointer; border-radius: 5px; font-weight: bold; margin-left: 10px;
        }
        .print-btn { background: #d97706; margin-top: 20px; }
        .error { color: red; font-weight: bold; margin-top: 15px; }

        /* Card Styles */
        .card-wrapper { display: flex; flex-direction: column; gap: 20px; align-items: center; }
        
        .card {
            width: 850px;
            height: 540px;
            position: relative;
            background-size: 100% 100%;
            background-repeat: no-repeat;
            border: 1px solid #ccc;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.2);
            overflow: hidden;
            background-color: white;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        
        /* VERY IMPORTANT: Ensure 0.jpg and 2.jpg are in the same folder */
        .card.front { background-image: url('0.jpg'); }
        .card.back { background-image: url('2.jpg'); }

        .bold { font-weight: bold; }
        
        /* Front Card Elements */
        .f-top-local { position: absolute; top: 15px; width: 100%; text-align: center; color: #d97706; font-size: 26px; font-weight: bold; }
        .f-top-eng { position: absolute; top: 50px; width: 100%; text-align: center; color: #166534; font-size: 32px; font-weight: bold; }
        .f-state-logo { position: absolute; top: 20px; right: 35px; height: 75px; width: auto; background: white; border-radius: 50%; }
        
        .f-photo { position: absolute; top: 150px; left: 50px; width: 125px; height: 160px; border: 2px solid #555; padding: 3px; background: #fff; }
        .f-photo img { width: 100%; height: 100%; object-fit: cover; }
        
        .f-details { position: absolute; top: 150px; left: 210px; font-size: 20px; color: #000; border-collapse: collapse; }
        .f-details td { padding-bottom: 8px; vertical-align: top; }
        .f-details .label { width: 100px; font-weight: bold;}
        .f-details .colon { width: 25px; text-align: center; }
        
        .f-qr { position: absolute; top: 260px; right: 50px; width: 130px; height: 130px; border: 2px solid #555; padding: 4px; background: #fff; }
        .f-qr img { width: 100%; height: 100%; }

        .f-vertical-txt { position: absolute; top: 330px; left: -100px; transform: rotate(-90deg); font-size: 13px; color: #333; font-weight: bold; width: 270px; text-align: center; }
        
        .f-farmer-id { position: absolute; bottom: 85px; width: 100%; text-align: center; color: #166534; font-size: 32px; font-weight: bold; letter-spacing: 2px; }
        .f-footer { position: absolute; bottom: 25px; width: 100%; text-align: center; color: #000; font-size: 20px; font-weight: bold; }

        /* Back Card Elements */
        .b-address { position: absolute; top: 110px; left: 50px; right: 50px; font-size: 19px; line-height: 1.5; color: #000; }
        
        .b-table-container { position: absolute; top: 220px; left: 50px; width: 750px; }
        .land-table { width: 100%; border-collapse: collapse; text-align: center; border: 2px solid #000; background: transparent; }
        .land-table th, .land-table td { border: 1px solid #000; padding: 8px; font-size: 17px; color: #000; }
        .land-table th { font-weight: bold; background: rgba(255,255,255,0.5); }

        .b-footer-bar { position: absolute; bottom: 25px; width: 100%; display: flex; justify-content: center; gap: 100px; font-size: 20px; font-weight: bold; color: #000; }
        
        /* Print Styles */
        @media print {
            body { background: #fff; padding: 0; }
            .no-print { display: none !important; }
            .card { box-shadow: none; border: none; margin-bottom: 20px; page-break-inside: avoid; }
        }
    </style>
</head>
<body>

    <div class="search-container no-print">
        <h2>AgriStack Farmer ID Search</h2>
        <form method="POST">
            <input type="text" name="uid_number" class="search-input" placeholder="Enter 12-digit Aadhaar Number" required pattern="\d{12}" value="<?= htmlspecialchars($uid_number) ?>">
            <button type="submit" class="search-btn">Search & Generate</button>
        </form>
        <?php if ($error): ?>
            <div class="error"><?= $error ?></div>
        <?php endif; ?>
    </div>

    <?php if ($cardData): ?>
    <div class="card-wrapper">
        <button class="print-btn no-print" onclick="window.print()">🖨️ Print ID Card</button>

        <div class="card front">
            <div class="f-top-local"><?= $govtOfIndiaLocal ?></div>
            <div class="f-top-eng">Government of India</div>
            <img src="<?= $statelogo ?>" class="f-state-logo" alt="State Emblem" onerror="this.style.display='none'">

            <div class="f-vertical-txt">Approval Date: <?= $approvalDate ?></div>

            <div class="f-photo">
                <img src="data:image/jpeg;base64,<?= $photoBase64 ?>" alt="Farmer Photo" onerror="this.src='https://via.placeholder.com/125x160?text=Photo'">
            </div>

            <table class="f-details">
                <tr>
                    <td class="label"><?= $nameLocalLabel ?></td><td class="colon">:</td>
                    <td class="value bold"><?= $nameLocal ?></td>
                </tr>
                <tr>
                    <td class="label">Name</td><td class="colon">:</td>
                    <td class="value"><?= $nameEn ?></td>
                </tr>
                <tr>
                    <td class="label">Gender</td><td class="colon">:</td>
                    <td class="value"><?= $genderMapping[$gender] ?? $gender ?></td>
                </tr>
                <tr>
                    <td class="label">DOB</td><td class="colon">:</td>
                    <td class="value"><?= $dob ?></td>
                </tr>
                <tr>
                    <td class="label">Caste</td><td class="colon">:</td>
                    <td class="value"><?= $caste ?></td>
                </tr>
                <tr>
                    <td class="label">Area</td><td class="colon">:</td>
                    <td class="value"><?= $area ?></td>
                </tr>
                <tr>
                    <td class="label">Aadhaar</td><td class="colon">:</td>
                    <td class="value"><?= $aadhaar ?></td>
                </tr>
            </table>

            <div class="f-qr">
                <img src="<?= $qrImageSrc ?>" alt="QR Code">
            </div>

            <div class="f-farmer-id">Farmer ID : <?= $farmerId ?></div>
            <div class="f-footer"><?= ucwords($stateName) ?> Farmer Registry</div>
        </div>

        <div class="card back">
            <div class="f-top-local"><?= $ministryLocal ?></div>
            <div class="f-top-eng">Ministry of Agri & Farmers Welfare</div>

            <div class="f-vertical-txt" style="top: 270px;">Download Date: <?= date('d/m/Y') ?></div>

            <div class="b-address">
                <span class="bold">Address:</span><br>
                <?= $fullAddress ?>
            </div>

            <div class="b-table-container">
                <table class="land-table">
                    <thead>
                        <tr>
                            <th>Khata</th>
                            <th>Khasra</th>
                            <th>Area</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        // Limiting to 3 rows so it fits perfectly on the card layout
                        $displayLands = array_slice($lands, 0, 3);
                        foreach($displayLands as $land): ?>
                        <tr>
                            <td><?= htmlspecialchars($land['OwnerNumber'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($land['SurveyNumber'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($land['ExtentTotalArea'] ?? '-') ?></td>
                        </tr>
                        <?php endforeach; ?>
                        
                        <?php if(empty($displayLands)): ?>
                        <tr><td colspan="3">No Land Records Found</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div class="b-footer-bar">
                <span>&#9742; 1800-180-1551</span>
                <span>&#127760; <?= $websiteUrl ?></span>
            </div>
        </div>
    </div>
    <?php endif; ?>

<script>
    // Developer Tools Protection
    document.addEventListener('contextmenu', e => e.preventDefault());
    document.onkeydown = function (e) {
      if (
        e.keyCode === 123 || 
        (e.ctrlKey && e.shiftKey && (e.keyCode === 73 || e.keyCode === 74)) || 
        (e.ctrlKey && e.keyCode === 85) || 
        (e.ctrlKey && e.keyCode === 83) 
      ) {
        return false;
      }
    };
</script>
</body>
</html>