<?php
// ==========================================
// ADVANCED FATAL ERROR CATCHER 
// ==========================================
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

register_shutdown_function(function() {
    $error = error_get_last();
    if ($error && ($error['type'] === E_ERROR || $error['type'] === E_PARSE || $error['type'] === E_CORE_ERROR || $error['type'] === E_COMPILE_ERROR)) {
        http_response_code(500);
        echo json_encode(["code" => 500, "success" => false, "message" => "FATAL SERVER ERROR: " . $error['message'] . " in " . $error['file'] . " on line " . $error['line']]);
        exit;
    }
});

// ==========================================
// 1. Core Configuration & Database
// ==========================================
define('DB_HOST', 'localhost');
define('DB_USER', 'teamcybe_test000');
define('DB_PASS', 'teamcybe_test000');
define('DB_NAME', 'teamcybe_test000');
define('SITE_URL', 'http://team-cyber-x.my.id/api.php');

try {
    $pdo = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8mb4", DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die(json_encode(["code" => 500, "success" => false, "message" => "Database Connection Failed! " . $e->getMessage()]));
}

// ==========================================
// 3. API SYSTEM LOGIC 
// ==========================================
set_time_limit(300);
ini_set('max_execution_time', 300);
ignore_user_abort(true);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

function responseJson($code, $success, $message, $infoData = null, $photoUrl = null) {
    http_response_code($code);
    $response = ['code' => $code, 'success' => $success, 'message' => $message];
    if ($infoData) $response['info'] = ['data' => $infoData];
    if ($photoUrl) $response['photo_url'] = $photoUrl;
    echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}

$apiKey = $_REQUEST['api_key'] ?? '';
$nid = $_REQUEST['nid'] ?? '';
$dob = $_REQUEST['dob'] ?? '';

if (empty($apiKey) || empty($nid) || empty($dob)) {
    responseJson(400, false, "Missing parameters: api_key, nid, dob");
}

// Verify API Key
$stmt = $pdo->prepare("SELECT * FROM api_users WHERE api_key = ? LIMIT 1");
$stmt->execute([$apiKey]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) responseJson(401, false, "Invalid API Key");
if ($user['status'] !== 'active') responseJson(403, false, "API Key is banned.");
if ($user['request_count'] >= $user['request_limit']) responseJson(429, false, "Limit exceeded.");

// Check Cache
$stmt = $pdo->prepare("SELECT * FROM nid_records WHERE nationalId = ? AND dateOfBirth = ? LIMIT 1");
$stmt->execute([$nid, $dob]);
$cache = $stmt->fetch(PDO::FETCH_ASSOC);

if ($cache) {
    $pdo->prepare("UPDATE api_users SET request_count = request_count + 1 WHERE id = ?")->execute([$user['id']]);
    $cachedInfoData = [
        'name' => $cache['nameBn'], 'nameEn' => $cache['nameEn'], 'nationalId' => $cache['nationalId'],
        'pin' => $cache['pin'], 'dateOfBirth' => $cache['dateOfBirth'], 'fatherName' => $cache['fatherName'],
        'motherName' => $cache['motherName'], 'gender' => $cache['gender'], 'religion' => $cache['religion'],
        'address' => $cache['address']
    ];
    responseJson(200, true, "NID fetched successfully!", $cachedInfoData, SITE_URL . ltrim($cache['photo_path'], '/'));
}

// Fetch from Main API
$apiUrl = "https://darktoolshub.net/scopy/maihhn.php?nid={$nid}&dob={$dob}";
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $apiUrl,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_CONNECTTIMEOUT => 60,
    CURLOPT_TIMEOUT => 300,
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
]);
$res = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode != 200 || !$res) responseJson(502, false, "Main API Server Timeout.");

$apiData = json_decode($res, true);
if (isset($apiData['code']) && $apiData['code'] == 200 && $apiData['success']) {
    $info = $apiData['info']['data'] ?? [];
    $address = $info['address'] ?? '';
    
    // Advanced Image Fetcher (Bypasses allow_url_fopen restrictions)
    $uploadDir = __DIR__ . '/uploads/';
    if (!is_dir($uploadDir)) {
        if (!mkdir($uploadDir, 0755, true)) {
            responseJson(500, false, "Failed to create uploads directory. Check folder permissions.");
        }
    }
    
    $imgPath = 'uploads/' . $nid . '.jpg';
    $fullImgPath = __DIR__ . '/' . $imgPath;
    
    if (!empty($apiData['photo_url'])) {
        $chImg = curl_init($apiData['photo_url']);
        curl_setopt_array($chImg, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT => 30
        ]);
        $imgContent = curl_exec($chImg);
        curl_close($chImg);
        
        if ($imgContent) {
            $img = @imagecreatefromstring($imgContent);
            if ($img) { 
                imagejpeg($img, $fullImgPath, 50); 
                imagedestroy($img); 
            }
        }
    }

    $ins = $pdo->prepare("INSERT INTO nid_records 
        (nationalId, dateOfBirth, nameBn, nameEn, pin, fatherName, motherName, gender, religion, address, photo_path) 
        VALUES (?,?,?,?,?,?,?,?,?,?,?)
        ON DUPLICATE KEY UPDATE 
        nameBn = VALUES(nameBn), nameEn = VALUES(nameEn), pin = VALUES(pin), 
        fatherName = VALUES(fatherName), motherName = VALUES(motherName), 
        gender = VALUES(gender), religion = VALUES(religion), address = VALUES(address), photo_path = VALUES(photo_path)");
        
    $ins->execute([
        $info['nationalId'] ?? $nid, $info['dateOfBirth'] ?? $dob, $info['name'] ?? '', $info['nameEn'] ?? '', 
        $info['pin'] ?? '', $info['fatherName'] ?? '', $info['motherName'] ?? '', $info['gender'] ?? '', 
        $info['religion'] ?? '', $address, $imgPath
    ]);

    $pdo->prepare("UPDATE api_users SET request_count = request_count + 1 WHERE id = ?")->execute([$user['id']]);

    $fetchedInfoData = [
        'name' => $info['name'] ?? '', 'nameEn' => $info['nameEn'] ?? '', 'nationalId' => $info['nationalId'] ?? $nid,
        'pin' => $info['pin'] ?? '', 'dateOfBirth' => $info['dateOfBirth'] ?? $dob, 'fatherName' => $info['fatherName'] ?? '',
        'motherName' => $info['motherName'] ?? '', 'gender' => $info['gender'] ?? '', 'religion' => $info['religion'] ?? '',
        'address' => $address
    ];
    
    responseJson(200, true, "NID fetched successfully!", $fetchedInfoData, SITE_URL . $imgPath);
} else {
    responseJson(404, false, "Data not found.");
}
