<?php
require 'config.php';
require_login();
header('Content-Type: application/json');

$data = json_decode(file_get_contents('php://input'), true);

try {
    // --- 1. GATHER INPUT ---
    $nid     = trim($data['nid'] ?? '');
    $dob     = trim($data['dob'] ?? '');
    $user_id = $_SESSION['user_id'];

    // --- 2. VALIDATE INPUT ---
    if (empty($nid) || empty($dob)) {
        throw new Exception("NID নম্বর এবং জন্ম তারিখ উভয়ই প্রয়োজন।");
    }

    // --- 3. DETERMINE COST (Using version 1 logic from your snippet) ---
    $cost = (float)($settings['smartcard_cost'] ?? 40);

    // --- 4. START TRANSACTION & CHECK BALANCE ---
    $pdo->beginTransaction();

    $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();

    if (!$user || $user['balance'] < $cost) {
        throw new Exception("আপনার পর্যাপ্ত ব্যালেন্স নেই।");
    }

    $new_balance = $user['balance'] - $cost;
    $stmt = $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?");
    $stmt->execute([$new_balance, $user_id]);

    // --- 5. CALL THE NEW EXTERNAL API ---
    $api_url = "https://apis.x14m.xyz/non_xd/?nid={$nid}&dob={$dob}";

    $ch = curl_init($api_url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT         => 40,
        CURLOPT_USERAGENT      => 'Mozilla/5.0'
    ]);

    $response  = curl_exec($ch);
    $httpCode   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($response === false || $httpCode !== 200) {
        throw new Exception("API সংযোগ ব্যর্থ হয়েছে।");
    }

    $api_result = json_decode($response, true);

    // --- 6. PROCESS API RESPONSE ---
    if (!$api_result || !isset($api_result['success']) || $api_result['success'] !== true) {
        $pdo->rollBack();
        $message = $api_result['message'] ?? 'তথ্য পাওয়া যায়নি।';
        echo json_encode(['success' => false, 'message' => "❌ " . $message]);
        exit;
    }

    $res = $api_result['data'];

    // --- 7. HANDLE RELIGION LOGIC ---
    // If religion is empty, "Unknown", or not set, save "Not Found"
    $religion = $res['religion'] ?? '';
    if (empty($religion) || strtolower($religion) === 'unknown') {
        $religion = "Not Found";
    }

    // --- 8. DOWNLOAD AND SAVE PHOTO ---
    $photo_url = $res['photo'] ?? '';
    $photo_path_relative = '';
    $photo_saved = false;

    if (!empty($photo_url)) {
        $photo_data = @file_get_contents($photo_url);
        if ($photo_data) {
            if (!is_dir('uploads')) mkdir('uploads', 0755, true);
            $filename = $user_id . '_' . time() . '_' . $nid . '.jpg';
            $photo_path_relative = 'uploads/' . $filename;
            if (file_put_contents($photo_path_relative, $photo_data)) {
                $photo_saved = true;
            }
        }
    }

    // --- 9. SAVE TO DATABASE ---
    // Note: Address fields are removed as requested. 
    // We pass empty strings or N/A for columns that are required in your schema but missing in new API.
    $sql = "INSERT INTO server_copy (
        user_id, nameBn, nameEn, nationalId, dateOfBirth,
        father, mother, photo_path, gender, religion,
        bloodGroup, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $user_id,
        $res['name'] ?? 'N/A',
        $res['nameEn'] ?? 'N/A',
        $res['nationalId'] ?? $nid,
        $res['dateOfBirth'] ?? $dob,
        $res['fatherName'] ?? 'N/A',
        $res['motherName'] ?? 'N/A',
        $photo_path_relative,
        $res['gender'] ?? 'N/A',
        $religion,
        $res['bloodGroup'] ?? 'N/A'
    ]);

    $order_id = $pdo->lastInsertId();
    $pdo->commit();

    // --- 10. SUCCESS RESPONSE ---
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
    $base_url = $protocol . '://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');

    echo json_encode([
        'success' => true,
        'message' => 'তথ্য সফলভাবে সংগ্রহ করা হয়েছে!',
        'order_id' => $order_id,
        'data' => [
            'nameBangla'  => $res['name'] ?? 'N/A',
            'nameEnglish' => $res['nameEn'] ?? 'N/A',
            'photo_path'  => $photo_saved ? $base_url . '/' . $photo_path_relative : null
        ]
    ]);

} catch (Throwable $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("API Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => '❌ ত্রুটি: ' . $e->getMessage()
    ]);
}
?>