<?php
/**
 * Smart NID API Developer Console
 * Theme: Laravel Breeze (Clean White/Blue)
 * Purpose: Test Smart Card PDF Parsing
 */

error_reporting(0);

// ==========================================
// BACKEND: API PROXY
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['act']) && $_POST['act'] === 'test_api') {
    header('Content-Type: application/json');

    $apiUrl = $_POST['api_url'] ?? '';
    $apiKey = $_POST['api_key'] ?? '';

    if (empty($apiUrl) || empty($apiKey)) {
        echo json_encode(['status' => 'error', 'message' => 'API URL or Key Missing']); exit;
    }

    if (isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] === 0) {
        
        $cFile = new CURLFile($_FILES['pdf_file']['tmp_name'], $_FILES['pdf_file']['type'], $_FILES['pdf_file']['name']);
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => [
                'key' => $apiKey, 
                'pdf' => $cFile
            ],
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT => 90,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
        ]);

        $response = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);

        if ($err) echo json_encode(['status' => 'error', 'message' => 'cURL Error: ' . $err]);
        else echo $response;
    } else {
        echo json_encode(['status' => 'error', 'message' => 'File Upload Failed']);
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Smart NID Dev Console</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">

    <style>
        body { background-color: #f3f4f6; font-family: 'Nunito', sans-serif; color: #1f2937; }
        
        /* Card & Panels */
        .card { background-color: #ffffff; border-radius: 0.5rem; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1); border: 1px solid #e5e7eb; }
        
        /* Form Elements */
        label { font-size: 0.7rem; font-weight: 700; color: #4b5563; text-transform: uppercase; margin-bottom: 0.25rem; display: block; letter-spacing: 0.05em; }
        .input-laravel { width: 100%; border-color: #d1d5db; background-color: #fff; border-radius: 0.375rem; padding: 0.5rem; font-size: 0.875rem; transition: 0.2s; border-width: 1px; color: #1f2937; }
        .input-laravel:focus { border-color: #4f46e5; outline: none; ring: 2px solid #e0e7ff; }
        .input-laravel[readonly] { background-color: #f9fafb; color: #6b7280; cursor: default; }
        
        /* Highlight Specific Fields */
        .highlight { background-color: #eff6ff !important; border-color: #bfdbfe !important; color: #1d4ed8 !important; font-weight: 700; }

        /* Tabs */
        .tab-btn { padding: 0.75rem 1rem; font-size: 0.875rem; font-weight: 600; color: #6b7280; border-bottom: 2px solid transparent; transition: 0.2s; }
        .tab-btn:hover { color: #111827; }
        .tab-btn.active { color: #4f46e5; border-bottom-color: #4f46e5; }
    </style>
</head>
<body class="py-8 px-4">

    <div class="max-w-7xl mx-auto mb-6 flex items-center gap-3">
        <div class="bg-indigo-600 text-white p-2.5 rounded-lg shadow-sm">
            <i class="fas fa-id-card-clip text-xl"></i>
        </div>
        <div>
            <h1 class="text-2xl font-bold text-gray-800">Smart NID Console</h1>
            <p class="text-xs text-gray-500 font-semibold uppercase tracking-wider">Developer Testing Tool</p>
        </div>
    </div>

    <div class="max-w-7xl mx-auto grid grid-cols-1 lg:grid-cols-12 gap-6">
        
        <div class="lg:col-span-3 space-y-5">
            
            <div class="card p-5">
                <h3 class="text-xs font-bold text-gray-400 uppercase tracking-wider mb-4 border-b pb-2">API Configuration</h3>
                <div class="space-y-4">
                    <div>
                        <label>Target URL</label>
                        <input type="text" id="apiUrl" class="input-laravel font-mono text-xs" value="https://api.allserver.site/api/v2/sm/analyze">
                    </div>
                    <div>
                        <label>Secret Key</label>
                        <input type="password" id="apiKey" class="input-laravel font-mono text-xs" value="2f300cb400988eaa6b795d1b03076e4f">
                    </div>
                </div>
            </div>

            <div class="card p-5">
                <h3 class="text-xs font-bold text-gray-400 uppercase tracking-wider mb-4 border-b pb-2">Request Body</h3>
                
                <div class="mb-4">
                    <label class="mb-2">Upload PDF</label>
                    <input type="file" id="pdfFile" accept="application/pdf" class="block w-full text-xs text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-semibold file:bg-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100 transition cursor-pointer">
                </div>

                <button id="btnSend" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 rounded shadow-sm transition flex items-center justify-center gap-2 text-sm">
                    <i class="fas fa-bolt"></i> Test API
                </button>
            </div>
        </div>

        <div class="lg:col-span-9">
            <div class="card min-h-[600px] flex flex-col overflow-hidden">
                
                <div class="flex border-b border-gray-200 bg-gray-50 px-4">
                    <button class="tab-btn active" onclick="switchTab('visual')"><i class="fas fa-eye mr-2"></i>Smart Form</button>
                    <button class="tab-btn" onclick="switchTab('json')"><i class="fas fa-code mr-2"></i>Raw JSON</button>
                </div>

                <div class="relative flex-grow p-6 bg-white">
                    
                    <div id="loader" class="hidden absolute inset-0 bg-white/95 z-20 flex flex-col items-center justify-center">
                        <div class="animate-spin rounded-full h-10 w-10 border-b-2 border-indigo-600 mb-3"></div>
                        <span class="text-xs font-bold text-indigo-600 animate-pulse">EXTRACTING DATA...</span>
                    </div>

                    <div id="emptyState" class="absolute inset-0 flex flex-col items-center justify-center text-gray-300">
                        <i class="fas fa-fingerprint text-6xl mb-4 text-gray-100"></i>
                        <p class="text-sm font-medium text-gray-400">Waiting for API Request...</p>
                    </div>

                    <div id="tabVisual" class="hidden h-full">
                        <div class="flex flex-col md:flex-row gap-6">
                            
                            <div class="w-full md:w-52 flex-shrink-0 space-y-4">
                                <div class="border rounded-lg p-3 text-center bg-gray-50">
                                    <div class="aspect-[3/4] bg-white border border-gray-200 rounded overflow-hidden mb-2 relative flex items-center justify-center">
                                        <img id="visPhoto" class="w-full h-full object-cover hidden">
                                        <i id="iconPhoto" class="fas fa-user text-3xl text-gray-200"></i>
                                    </div>
                                    <span class="text-[10px] font-bold text-gray-400 uppercase">User Photo</span>
                                </div>
                                <div class="border rounded-lg p-3 text-center bg-gray-50">
                                    <div class="h-14 bg-white border border-gray-200 rounded overflow-hidden mb-2 flex items-center justify-center">
                                        <img id="visSign" class="max-h-full max-w-full object-contain hidden">
                                        <i id="iconSign" class="fas fa-signature text-xl text-gray-200"></i>
                                    </div>
                                    <span class="text-[10px] font-bold text-gray-400 uppercase">Signature</span>
                                </div>
                            </div>

                            <div class="flex-grow grid grid-cols-1 md:grid-cols-2 gap-4 content-start">
                                
                                <div class="md:col-span-2 pb-1 border-b border-gray-100 mb-1">
                                    <h4 class="text-[10px] font-bold text-indigo-500 uppercase">Smart ID Info</h4>
                                </div>

                                <div><label>Smart NID No</label><input id="visNid" class="input-laravel highlight" readonly></div>
                                <div><label>Smart PIN</label><input id="visPin" class="input-laravel" readonly></div>
                                
                                <div><label>Name (Bangla)</label><input id="visBn" class="input-laravel" readonly></div>
                                <div><label>Name (English)</label><input id="visEn" class="input-laravel" readonly></div>
                                
                                <div><label>Date of Birth</label><input id="visDob" class="input-laravel" readonly></div>
                                <div><label>Place of Birth</label><input id="visPlace" class="input-laravel" readonly></div>
                                
                                <div><label>Gender</label><input id="visGender" class="input-laravel" readonly></div>
                                <div><label>Blood Group</label><input id="visBlood" class="input-laravel" readonly></div>

                                <div class="md:col-span-2 pb-1 border-b border-gray-100 mb-1 mt-2">
                                    <h4 class="text-[10px] font-bold text-indigo-500 uppercase">Guardian Info</h4>
                                </div>

                                <div><label>Father's Name</label><input id="visFather" class="input-laravel" readonly></div>
                                <div><label>Mother's Name</label><input id="visMother" class="input-laravel" readonly></div>

                                <div class="md:col-span-2">
                                    <label>Full Address</label>
                                    <textarea id="visAddr" rows="2" class="input-laravel" readonly></textarea>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div id="tabJson" class="hidden h-full overflow-auto rounded border border-gray-100 bg-gray-900">
                        <pre id="jsonOutput" class="text-xs font-mono text-green-400 p-4 whitespace-pre-wrap"></pre>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        // Tab Switcher
        function switchTab(t) {
            $('.tab-btn').removeClass('active');
            $(`button[onclick="switchTab('${t}')"]`).addClass('active');
            if(t==='visual') {
                $('#tabVisual').removeClass('hidden'); $('#tabJson').addClass('hidden');
            } else {
                $('#tabVisual').addClass('hidden'); $('#tabJson').removeClass('hidden');
            }
        }

        // Action Handler
        $('#btnSend').click(function() {
            const url = $('#apiUrl').val().trim();
            const key = $('#apiKey').val().trim();
            const file = $('#pdfFile')[0].files[0];

            if(!url || !key || !file) {
                return Swal.fire({
                    icon: 'warning',
                    title: 'Required Fields',
                    text: 'Please check API URL, Key and File.',
                    confirmButtonColor: '#4f46e5'
                });
            }

            $('#loader').removeClass('hidden');
            $('#emptyState').addClass('hidden');

            let fd = new FormData();
            fd.append('act', 'test_api');
            fd.append('api_url', url);
            fd.append('api_key', key);
            fd.append('pdf_file', file);

            $.ajax({
                url: '', type: 'POST', data: fd,
                contentType: false, processData: false,
                success: function(res) {
                    $('#loader').addClass('hidden');
                    $('#jsonOutput').text(JSON.stringify(res, null, 4));

                    if(res.success === true || res.code === 200) {
                        const d = res.data;

                        // Smart Card Mapping (Based on typical Smart NID API)
                        $('#visNid').val(d.nationalId || d.nid || d.pin);
                        $('#visPin').val(d.pin);
                        $('#visBn').val(d.nameBangla);
                        $('#visEn').val(d.nameEnglish);
                        $('#visDob').val(d.dateOfBirth || d.dob);
                        $('#visPlace').val(d.birthPlace);
                        $('#visGender').val(d.gender);
                        $('#visBlood').val(d.bloodGroup);
                        $('#visFather').val(d.fatherName);
                        $('#visMother').val(d.motherName);
                        $('#visAddr').val(d.address || d.fulAddress);

                        // Images
                        if(d.userIMG) { $('#visPhoto').attr('src', d.userIMG).removeClass('hidden'); $('#iconPhoto').addClass('hidden'); }
                        if(d.signIMG) { $('#visSign').attr('src', d.signIMG).removeClass('hidden'); $('#iconSign').addClass('hidden'); }

                        switchTab('visual');
                        Swal.fire({
                            icon: 'success', title: 'Data Extracted', 
                            toast: true, position: 'top-end', 
                            showConfirmButton: false, timer: 2000
                        });
                    } else {
                        switchTab('json');
                        Swal.fire({ icon: 'error', title: 'API Error', text: res.message });
                    }
                },
                error: function(e) {
                    $('#loader').addClass('hidden');
                    Swal.fire('Network Error', e.statusText, 'error');
                }
            });
        });
    </script>
</body>
</html>