<?php
// ============================================
// RATE LIMITING UTILITY (IP BASED - DAILY)
// ============================================
function checkAndRecordRateLimit($serviceName, $limit) {
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN_IP';
    $logFile = __DIR__ . '/farmer_limits_log.json';
    $today = date('Y-m-d');

    if (!file_exists($logFile)) {
        @file_put_contents($logFile, json_encode([]));
    }

    $fileContent = @file_get_contents($logFile);
    $data = json_decode($fileContent, true);
    if (!is_array($data)) $data = [];

    if (!isset($data[$ip])) $data[$ip] = [];

    if (!isset($data[$ip][$serviceName]) || $data[$ip][$serviceName]['date'] !== $today) {
        $data[$ip][$serviceName] = ['count' => 0, 'date' => $today];
    }

    if ($data[$ip][$serviceName]['count'] >= $limit) {
        return false; // Limit exceeded
    }

    $data[$ip][$serviceName]['count']++;
    @file_put_contents($logFile, json_encode($data, JSON_PRETTY_PRINT));

    return true;
}

// ============================================
// BACKEND PHP API HANDLERS
// ============================================
function callExternalApi($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200 || !$response) {
        return ['status' => 'error', 'message' => "API Error: HTTP $httpCode"];
    }
    return json_decode($response, true);
}

// Handle AJAX requests from frontend
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && isset($_POST['action'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'] ?? '';
    
    // --- BOX 1: FETCH FARMER DETAILS (LIMIT: 5) ---
    if ($action === 'fetch_farmer_details') {
        if (!checkAndRecordRateLimit('farmer_details', 5)) {
            echo json_encode(['success' => false, 'message' => 'Limit Exceeded: You have used your 5 free checks for today.']);
            exit;
        }

        $uidNumber = trim($_POST['uid_number'] ?? '');
        $stateName = trim($_POST['state_name'] ?? '');
        
        if (empty($uidNumber) || empty($stateName)) {
            echo json_encode(['success' => false, 'message' => 'Aadhaar Number and State are required.']); exit;
        }

        $url = "https://codemart.in.net/farmer-card/details.php?uid_number=" . urlencode($uidNumber) . "&state_name=" . urlencode($stateName);
        $result = callExternalApi($url);
        
        if ($result && (isset($result['code']) && $result['code'] == 200 || (isset($result['status']) && $result['status'] === 'success'))) {
            echo json_encode(['success' => true, 'data' => $result]);
        } else {
            echo json_encode(['success' => false, 'message' => $result['message'] ?? 'Farmer data not found.']);
        }
        exit;
    }
    
    // --- BOX 2: GENERATE FARMER PDF (LIMIT: 3) ---
    if ($action === 'download_farmer_pdf') {
        if (!checkAndRecordRateLimit('farmer_pdf', 3)) {
            echo json_encode(['success' => false, 'message' => 'Limit Exceeded: You have used your 3 free PDF downloads for today.']);
            exit;
        }

        $uidNumber = trim($_POST['uid_number'] ?? '');
        $stateName = trim($_POST['state_name'] ?? '');
        
        if (empty($uidNumber) || empty($stateName)) {
            echo json_encode(['success' => false, 'message' => 'Aadhaar Number and State are required.']); exit;
        }

        $url = "https://codemart.in.net/farmer-card/print_api.php?uid_number=" . urlencode($uidNumber) . "&state_name=" . urlencode($stateName);
        $result = callExternalApi($url);
        
        if ($result && isset($result['status']) && $result['status'] === 'success' && !empty($result['pdf_base64'])) {
            echo json_encode(['success' => true, 'message' => $result['message'], 'pdf_base64' => $result['pdf_base64']]);
        } else {
            echo json_encode(['success' => false, 'message' => $result['message'] ?? 'Failed to generate PDF.']);
        }
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>AgriStack | Farmer ID Services</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Inter', sans-serif; }
        body { background: linear-gradient(135deg, #2b5876 0%, #4e4376 100%); min-height: 100vh; padding: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        .header { background: white; border-radius: 20px; padding: 25px 30px; margin-bottom: 25px; box-shadow: 0 10px 40px rgba(0,0,0,0.1); text-align: center; }
        .header h1 { color: #333; font-size: 28px; margin-bottom: 5px; }
        .header h1 i { color: #2b5876; margin-right: 10px; }
        .header p { color: #666; font-size: 14px; font-weight: 500; }
        
        .multi-columns { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; }
        
        .box-container { background: white; border-radius: 20px; padding: 25px; box-shadow: 0 10px 40px rgba(0,0,0,0.1); display: flex; flex-direction: column; }
        .box-title { font-size: 19px; font-weight: 700; color: #333; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 3px solid #2b5876; display: flex; align-items: center; justify-content: space-between; }
        .box-title-left { display: flex; align-items: center; gap: 10px; }
        .box-title i { color: #2b5876; font-size: 22px; }
        
        .badge { background: #e2e8f0; color: #475569; font-size: 11px; padding: 4px 8px; border-radius: 12px; font-weight: 600; border: 1px solid #cbd5e1; }
        
        .form-group { display: flex; flex-direction: column; gap: 10px; margin-bottom: 15px; }
        .input-style { width: 100%; padding: 12px 15px; border: 2px solid #e0e0e0; border-radius: 12px; font-size: 15px; transition: all 0.3s; font-weight: 500; }
        .input-style:focus { outline: none; border-color: #2b5876; box-shadow: 0 0 0 3px rgba(43,88,118,0.1); }
        select.input-style { cursor: pointer; appearance: none; background: url('data:image/svg+xml;utf8,<svg fill="%23333" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"/><path d="M0 0h24v24H0z" fill="none"/></svg>') no-repeat right 10px center; background-size: 20px; background-color: #fff;}
        
        .btn { padding: 12px 20px; border: none; border-radius: 12px; font-size: 15px; font-weight: 600; cursor: pointer; transition: all 0.3s; display: inline-flex; align-items: center; justify-content: center; gap: 8px; white-space: nowrap; width: 100%; }
        .btn-primary { background: linear-gradient(135deg, #2b5876 0%, #4e4376 100%); color: white; }
        .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(43,88,118,0.4); }
        .btn-success { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; }
        .btn-success:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(17,153,142,0.4); }
        .btn:disabled { opacity: 0.6; cursor: not-allowed; transform: none; box-shadow: none; }
        
        .alert { padding: 12px 15px; border-radius: 10px; margin-bottom: 15px; display: none; align-items: center; gap: 10px; font-size: 13px; font-weight: 500; }
        .alert.show { display: flex; }
        .alert-success { background: #d4edda; color: #155724; border-left: 4px solid #28a745; }
        .alert-error { background: #f8d7da; color: #721c24; border-left: 4px solid #dc3545; }
        
        .details-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 10px; }
        .detail-item { background: #f8f9fa; padding: 10px 12px; border-radius: 8px; border: 1px solid #e2e8f0; }
        .detail-label { font-size: 10px; text-transform: uppercase; font-weight: 600; color: #2b5876; margin-bottom: 4px; }
        .detail-value { font-size: 12px; font-weight: 600; color: #333; word-break: break-word; }
        
        .empty-state { text-align: center; padding: 40px 20px; color: #999; background: #fcfcfc; border-radius: 12px; border: 2px dashed #eee; display:flex; flex-direction:column; justify-content:center; align-items:center; height:100%; min-height: 200px;}
        .empty-state i { font-size: 40px; margin-bottom: 15px; color: #ddd; }
        
        /* Farmer Profile Card Styles */
        .profile-card { display: flex; flex-direction: column; gap: 15px; background: #fff; border: 1px solid #e2e8f0; border-radius: 16px; padding: 18px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); }
        .profile-header { display: flex; gap: 15px; align-items: center; padding-bottom: 12px; border-bottom: 1px solid #eee; }
        .profile-img { width: 90px; height: 110px; object-fit: cover; border-radius: 8px; border: 3px solid #2b5876; padding: 2px; }
        .profile-main-info h3 { color: #1e293b; font-size: 18px; margin-bottom: 5px; }
        .profile-main-info p { color: #64748b; font-size: 12px; font-weight: 500; margin-bottom:3px; }
        
        .extra-data-section { margin-top: 5px; padding-top: 15px; border-top: 1px dashed #cbd5e1; }
        
        .pdf-viewer { margin-top: 15px; border-radius: 12px; overflow: hidden; border: 1px solid #ddd; background: #f8f9fa; display: none; }
        .pdf-viewer iframe { width: 100%; height: 400px; border: none; }
        
        .loader { display: inline-block; width: 16px; height: 16px; border: 2px solid #fff; border-radius: 50%; border-top-color: transparent; animation: spin 0.6s linear infinite; }
        @keyframes spin { to { transform: rotate(360deg); } }
        
        @media (max-width: 900px) { .multi-columns { grid-template-columns: 1fr; } .profile-header { flex-direction: column; text-align: center; } }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <h1><i class="fas fa-seedling"></i> AgriStack Farmer Services</h1>
        <p>Check Farmer Details & Download Official ID Card</p>
    </div>

    <div class="multi-columns">
        
        <div class="box-container">
            <div class="box-title">
                <div class="box-title-left"><i class="fas fa-address-card"></i><span>Farmer Details</span></div>
                <span class="badge">Max 5/Day</span>
            </div>
            
            <div class="form-group">
                <input type="text" id="detailsAadhaarInput" class="input-style" placeholder="12-Digit Aadhaar No" maxlength="12">
                <select id="detailsStateInput" class="input-style">
                    <option value="">-- Choose State --</option>
                    <option value="maharashtra">Maharashtra</option>
                    <option value="haryana">Haryana</option>
                    <option value="bihar">Bihar</option>
                    <option value="madhya pradesh">Madhya Pradesh</option>
                    <option value="chhattisgarh">Chhattisgarh</option>
                    <option value="punjab">Punjab</option>
                    <option value="assam">Assam</option>
                    <option value="mizoram">Mizoram</option>
                    <option value="arunachal pradesh">Arunachal Pradesh</option>
                    <option value="andhra pradesh">Andhra Pradesh</option>
                    <option value="telangana">Telangana</option>
                    <option value="tripura">Tripura</option>
                    <option value="uttarakhand">Uttarakhand</option>
                    <option value="jharkhand">Jharkhand</option>
                    <option value="kerala">Kerala</option>
                    <option value="rajasthan">Rajasthan</option>
                    <option value="west bengal">West Bengal</option>
                    <option value="tamil nadu">Tamil Nadu</option>
                    <option value="karnataka">Karnataka</option>
                    <option value="odisha">Odisha</option>
                    <option value="gujarat">Gujarat</option>
                    <option value="uttar pradesh">Uttar Pradesh</option>
                    <option value="himachal pradesh">Himachal Pradesh</option>
                </select>
                <button class="btn btn-primary" id="btnFetchDetails"><i class="fas fa-search"></i> Fetch Details</button>
            </div>
            
            <div id="detailsAlert"></div>
            
            <div id="detailsContent" style="flex: 1;">
                <div class="empty-state">
                    <i class="fas fa-tractor"></i>
                    <p>Enter Aadhaar & State to fetch Farmer records.</p>
                </div>
            </div>
        </div>

        <div class="box-container">
            <div class="box-title">
                <div class="box-title-left"><i class="fas fa-file-pdf"></i><span>Farmer ID PDF</span></div>
                <span class="badge">Max 3/Day</span>
            </div>
            
            <div class="form-group">
                <input type="text" id="pdfAadhaarInput" class="input-style" placeholder="12-Digit Aadhaar No" maxlength="12">
                <select id="pdfStateInput" class="input-style">
                    <option value="">-- Choose State --</option>
                    <option value="maharashtra">Maharashtra</option>
                    <option value="haryana">Haryana</option>
                    <option value="bihar">Bihar</option>
                    <option value="madhya pradesh">Madhya Pradesh</option>
                    <option value="chhattisgarh">Chhattisgarh</option>
                    <option value="punjab">Punjab</option>
                    <option value="assam">Assam</option>
                    <option value="mizoram">Mizoram</option>
                    <option value="arunachal pradesh">Arunachal Pradesh</option>
                    <option value="andhra pradesh">Andhra Pradesh</option>
                    <option value="telangana">Telangana</option>
                    <option value="tripura">Tripura</option>
                    <option value="uttarakhand">Uttarakhand</option>
                    <option value="jharkhand">Jharkhand</option>
                    <option value="kerala">Kerala</option>
                    <option value="rajasthan">Rajasthan</option>
                    <option value="west bengal">West Bengal</option>
                    <option value="tamil nadu">Tamil Nadu</option>
                    <option value="karnataka">Karnataka</option>
                    <option value="odisha">Odisha</option>
                    <option value="gujarat">Gujarat</option>
                    <option value="uttar pradesh">Uttar Pradesh</option>
                    <option value="himachal pradesh">Himachal Pradesh</option>
                </select>
                <button class="btn btn-primary" id="btnGeneratePdf"><i class="fas fa-cog"></i> Generate PDF</button>
            </div>
            
            <div id="pdfAlert"></div>
            
            <div class="pdf-viewer" id="pdfViewer">
                <iframe id="pdfFrame" title="Farmer ID PDF"></iframe>
                <div style="padding: 15px; text-align: center; background: #fff; border-top: 1px solid #eee;">
                    <button class="btn btn-success" id="downloadPdfBtn"><i class="fas fa-download"></i> Save PDF Device</button>
                </div>
            </div>
            
            <div id="pdfEmptyState" class="empty-state" style="flex: 1;">
                <i class="fas fa-print"></i>
                <p>Generate original Farmer ID Card PDF.</p>
            </div>
        </div>

    </div>
</div>

<script>
// ==========================================
// COMMON JS UTILS
// ==========================================
function setBtnLoading(btnId, isLoading, originalHtml) {
    const btn = document.getElementById(btnId);
    if (!btn) return;
    if (isLoading) { btn.disabled = true; btn.innerHTML = '<span class="loader"></span>'; } 
    else { btn.disabled = false; btn.innerHTML = originalHtml; }
}

function showAlert(containerId, message, type) {
    const container = document.getElementById(containerId);
    let icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
    container.innerHTML = `<div class="alert alert-${type} show"><i class="fas ${icon}"></i><span>${message}</span></div>`;
    setTimeout(() => { container.innerHTML = ''; }, 6000);
}

function escapeHtml(str) {
    if (str === null || str === undefined) return '-';
    return String(str).replace(/[&<>]/g, function(m) { return {'&': '&amp;', '<': '&lt;', '>': '&gt;'}[m]; });
}

async function fetchApi(data) {
    const formData = new FormData();
    for (let key in data) formData.append(key, data[key]);
    const response = await fetch(window.location.href, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: formData
    });
    return await response.json();
}

// ==========================================
// DYNAMIC PROFILE CARD GENERATOR (FARMER)
// ==========================================
function generateFarmerProfileCard(data) {
    // 1. Process Image
    let imageSrc = data.PhotoBase64 || 'https://via.placeholder.com/90x110?text=No+Photo';
    if (imageSrc && !imageSrc.startsWith('http') && !imageSrc.startsWith('data:image')) {
        imageSrc = 'data:image/jpeg;base64,' + imageSrc;
    }

    // 2. Identify Core Keys to show in Header
    const name = data.farmerName || data.aadhaarName || 'Unknown Farmer';
    const localName = data.aadhaarNameLocal ? `<p><i class="fas fa-language"></i> ${escapeHtml(data.aadhaarNameLocal)}</p>` : '';
    const farmerId = data.farmerid || data.farmerNumber || '-';
    
    // 3. Prevent duplicate keys being shown in the extra grid
    const excludeKeys = ['code', 'message', 'PhotoBase64', 'statelogo', 'originsite', 'farmerName', 'aadhaarNameLocal'];
    
    // 4. Generate dynamic extra details grid
    let gridContent = '';
    
    for (let key in data) {
        if (!excludeKeys.includes(key) && data[key] !== null && typeof data[key] !== 'object' && data[key] !== '') {
            // Format key text (e.g. "approvalStatus" -> "Approval Status")
            let label = key.replace(/([A-Z])/g, ' $1').replace(/^./, function(str){ return str.toUpperCase(); });
            
            // Special coloring for Status
            let valStyle = '';
            if (key.toLowerCase().includes('status') && data[key].toString().toLowerCase() === 'approved') {
                valStyle = 'color: #28a745;';
            }
            
            gridContent += `
                <div class="detail-item">
                    <div class="detail-label">${escapeHtml(label)}</div>
                    <div class="detail-value" style="${valStyle}">${escapeHtml(data[key])}</div>
                </div>
            `;
        }
    }

    // 5. Return Complete Layout
    return `
        <div class="profile-card">
            <div class="profile-header">
                <img src="${imageSrc}" alt="Farmer Photo" class="profile-img">
                <div class="profile-main-info">
                    <h3>${escapeHtml(name)}</h3>
                    ${localName}
                    <p style="color:#2b5876; font-weight:700;"><i class="fas fa-id-badge"></i> ID: ${escapeHtml(farmerId)}</p>
                </div>
            </div>
            <div class="extra-data-section">
                <div class="detail-label" style="margin-bottom: 10px;"><i class="fas fa-list-ul"></i> Full Farmer Records</div>
                <div class="details-grid">${gridContent}</div>
            </div>
        </div>
    `;
}

// ==========================================
// BOX 1: FETCH DETAILS LOGIC
// ==========================================
document.getElementById('btnFetchDetails').addEventListener('click', async () => {
    const aadhaar = document.getElementById('detailsAadhaarInput').value.trim();
    const state = document.getElementById('detailsStateInput').value;
    
    if (aadhaar.length !== 12) return showAlert('detailsAlert', 'Enter a valid 12-digit Aadhaar number.', 'error');
    if (!state) return showAlert('detailsAlert', 'Please select a state.', 'error');
    
    setBtnLoading('btnFetchDetails', true, '');
    document.getElementById('detailsAlert').innerHTML = '';
    document.getElementById('detailsContent').innerHTML = `<div class="empty-state"><span class="loader" style="border-color:#2b5876; border-top-color:transparent; width:30px; height:30px; border-width:3px;"></span><p style="margin-top:15px;">Fetching Farmer Database...</p></div>`;
    
    try {
        const result = await fetchApi({ action: 'fetch_farmer_details', uid_number: aadhaar, state_name: state });
        if (result.success && result.data) {
            showAlert('detailsAlert', 'Farmer data fetched successfully!', 'success');
            document.getElementById('detailsContent').innerHTML = generateFarmerProfileCard(result.data);
        } else {
            showAlert('detailsAlert', result.message || 'Error fetching data.', 'error');
            document.getElementById('detailsContent').innerHTML = `<div class="empty-state"><i class="fas fa-exclamation-triangle" style="color:#dc3545;"></i><p>Farmer not found or API error.</p></div>`;
        }
    } catch (e) { 
        showAlert('detailsAlert', 'Network error. Try again.', 'error'); 
        document.getElementById('detailsContent').innerHTML = '';
    } 
    finally { setBtnLoading('btnFetchDetails', false, '<i class="fas fa-search"></i> Fetch Details'); }
});

// ==========================================
// BOX 2: GENERATE PDF LOGIC
// ==========================================
document.getElementById('btnGeneratePdf').addEventListener('click', async () => {
    const aadhaar = document.getElementById('pdfAadhaarInput').value.trim();
    const state = document.getElementById('pdfStateInput').value;
    
    if (aadhaar.length !== 12) return showAlert('pdfAlert', 'Enter a valid 12-digit Aadhaar number.', 'error');
    if (!state) return showAlert('pdfAlert', 'Please select a state.', 'error');
    
    setBtnLoading('btnGeneratePdf', true, '');
    document.getElementById('pdfAlert').innerHTML = '';
    document.getElementById('pdfViewer').style.display = 'none';
    document.getElementById('pdfEmptyState').style.display = 'flex';
    document.getElementById('pdfEmptyState').innerHTML = `<span class="loader" style="border-color:#2b5876; border-top-color:transparent; width:30px; height:30px; border-width:3px;"></span><p style="margin-top:15px;">Generating High-Quality PDF...</p>`;
    
    try {
        const result = await fetchApi({ action: 'download_farmer_pdf', uid_number: aadhaar, state_name: state });
        if (result.success && result.pdf_base64) {
            showAlert('pdfAlert', 'PDF Generated Successfully!', 'success');
            
            // Format base64 properly for iframe
            let pdfDataUri = result.pdf_base64;
            if (!pdfDataUri.startsWith('data:application/pdf')) {
                pdfDataUri = 'data:application/pdf;base64,' + pdfDataUri;
            }
            
            document.getElementById('pdfEmptyState').style.display = 'none';
            document.getElementById('pdfFrame').src = pdfDataUri;
            document.getElementById('pdfViewer').style.display = 'block';
            
            // Set download button logic
            document.getElementById('downloadPdfBtn').onclick = () => {
                const a = document.createElement('a'); 
                a.href = pdfDataUri; 
                a.download = `Farmer_ID_${aadhaar}.pdf`;
                document.body.appendChild(a); 
                a.click(); 
                document.body.removeChild(a);
            };
        } else { 
            showAlert('pdfAlert', result.message || 'Failed to generate PDF.', 'error'); 
            document.getElementById('pdfEmptyState').innerHTML = `<i class="fas fa-times-circle" style="color:#dc3545;"></i><p>Generation Failed.</p>`;
        }
    } catch (e) { 
        showAlert('pdfAlert', 'Network error. Try again.', 'error'); 
        document.getElementById('pdfEmptyState').innerHTML = `<i class="fas fa-wifi"></i><p>Network Error.</p>`;
    } 
    finally { setBtnLoading('btnGeneratePdf', false, '<i class="fas fa-cog"></i> Generate PDF'); }
});
</script>
</body>
</html>