<?php
error_reporting(E_ALL);
ini_set('display_errors', 0); // ফ্রন্টএন্ডে ওয়ার্নিং হাইড করা
header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");

// কনফিগারেশন
$apiKey = 'a75f600bb30117fc323b477ce0c7dd81';        
$apiUrl = 'https://core.allserver.site/api/v2/sm/analyze';   

$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
$currentDomain = $protocol . $_SERVER['HTTP_HOST']; 

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (isset($_FILES['pdf']) && $_FILES['pdf']['error'] === UPLOAD_ERR_OK) {

        $tempDir = __DIR__ . '/temp_uploads';
        if (!file_exists($tempDir)) mkdir($tempDir, 0755, true);
        
        $localPdfPath = $tempDir . '/sm_' . time() . '_' . rand(1000,9999) . '.pdf';

        if (move_uploaded_file($_FILES['pdf']['tmp_name'], $localPdfPath)) {
            
            $cfile = new CURLFile(realpath($localPdfPath), 'application/pdf', $_FILES['pdf']['name']);

            $ch = curl_init();
            curl_setopt_array($ch, array(
                CURLOPT_URL => $apiUrl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => array('key' => $apiKey, 'pdf' => $cfile),
                CURLOPT_REFERER => $currentDomain,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_TIMEOUT => 120 
            ));

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

            if (file_exists($localPdfPath)) unlink($localPdfPath);

            if ($err) { echo json_encode(['success' => false, 'message' => 'cURL Error']); exit; }

            $data = json_decode($response, true);
            
            // সফল হওয়ার চেক
            $isSuccess = false;
            if ((isset($data['success']) && $data['success'] === true) || (isset($data['code']) && $data['code'] == 200)) {
                $isSuccess = true;
            }

            if ($isSuccess && !empty($data['data'])) {
                
                $apiData = $data['data'];
                
                // --- ইমেজ প্রসেসিং ---
                $photoDir = 'photo/';
                if (!file_exists($photoDir)) mkdir($photoDir, 0755, true);
                $baseUrl = $currentDomain . dirname($_SERVER['SCRIPT_NAME']) . '/';

                $userImgLink = $apiData['userIMG'] ?? '';
                $signImgLink = $apiData['signIMG'] ?? '';

                try {
                    if (!empty($userImgLink)) {
                        $c = @file_get_contents(str_replace(" ", "%20", $userImgLink));
                        if ($c) {
                            $n = 'user_sm_' . uniqid() . '.jpg';
                            file_put_contents($photoDir . $n, $c);
                            $userImgLink = $baseUrl . $photoDir . $n;
                        }
                    }
                    if (!empty($signImgLink)) {
                        $c = @file_get_contents(str_replace(" ", "%20", $signImgLink));
                        if ($c) {
                            $n = 'sign_sm_' . uniqid() . '.jpg';
                            file_put_contents($photoDir . $n, $c);
                            $signImgLink = $baseUrl . $photoDir . $n;
                        }
                    }
                } catch (Exception $e) {}

                // ======================================================
                // [FINAL MAPPING] আপনার JS কোড অনুযায়ী ডাটা সাজানো
                // JS: 'nid': data.nationalId
                // JS: 'dob': data.dateOfBirth
                // JS: 'fulAddress': data.address
                // ======================================================
                
                $mappedData = [
                    // JS 'nationalId' খুঁজছে, তাই Key হতে হবে 'nationalId'
                    'nationalId' => $apiData['nationalId'] ?? $apiData['nid'] ?? $apiData['pin'] ?? '',
                    
                    'pin' => $apiData['pin'] ?? '',
                    'nameBangla' => $apiData['nameBangla'] ?? '',
                    'nameEnglish' => $apiData['nameEnglish'] ?? '',
                    
                    // JS 'dateOfBirth' খুঁজছে, তাই Key হতে হবে 'dateOfBirth'
                    'dateOfBirth' => $apiData['dateOfBirth'] ?? $apiData['dob'] ?? '',
                    
                    'birthPlace' => $apiData['birthPlace'] ?? '',
                    'fatherName' => $apiData['fatherName'] ?? '',
                    'motherName' => $apiData['motherName'] ?? '',
                    'bloodGroup' => $apiData['bloodGroup'] ?? '',
                    'gender' => $apiData['gender'] ?? '',
                    
                    // JS 'address' খুঁজছে, তাই Key হতে হবে 'address'
                    'address' => $apiData['address'] ?? $apiData['fulAddress'] ?? '',

                    // ছবি
                    'userIMG' => $userImgLink,
                    'signIMG' => $signImgLink
                ];

                echo json_encode([
                    'success' => true,
                    'data' => $mappedData
                ], JSON_UNESCAPED_UNICODE);

            } else {
                $msg = $data['message'] ?? 'Data extraction failed';
                echo json_encode(['success' => false, 'message' => $msg]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Upload failed']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'No PDF']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid Request']);
}
?>