<?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'] ?? '');
    $version = trim($data['version'] ?? '1');
    $user_id = $_SESSION['user_id'];

    // --- 2. VALIDATE INPUT ---
    if (empty($nid) || empty($dob)) {
        throw new Exception("NID নম্বর এবং জন্ম তারিখ উভয়ই প্রয়োজন।");
    }
    if (!preg_match('/^\d{10}$|^\d{13}$|^\d{17}$/', $nid)) {
        throw new Exception("NID নম্বরটি সঠিক ফরম্যাটে নয়। বাংলাদেশি NID ১০, ১৩ বা ১৭ ডিজিটের হতে হবে।");
    }
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $dob)) {
        throw new Exception("জন্ম তারিখের ফরম্যাট সঠিক নয়। YYYY-MM-DD ফরম্যাটে দিন।");
    }

    $dobDate = DateTime::createFromFormat('Y-m-d', $dob);
    if (!$dobDate || $dobDate > new DateTime()) {
        throw new Exception("জন্ম তারিখটি সঠিক বা যুক্তিসঙ্গত নয়।");
    }
    $ageNum = (new DateTime())->diff($dobDate)->y;
    if ($ageNum < 18 || $ageNum > 120) {
        throw new Exception("জন্ম তারিখটি যুক্তিসঙ্গত নয়। বয়স ১৮-১২০ বছরের মধ্যে হতে হবে।");
    }

    // --- 3. DETERMINE API & COST ---
    if ($version == '2') {
        $cost    = (float)($settings['sc_api2_cost'] ?? 50);
        $api_key = $settings['sc_api2_key']  ?? '';
        $api_url = $settings['sc_api2_url']  ?? '';
    } else {
        $cost    = (float)($settings['sc_api1_cost'] ?? 40);
        $api_key = $settings['sc_api1_key']  ?? '';
        $api_url = 'https://ec-api.top';
    }
    if (empty($api_url) || empty($api_key)) {
        throw new Exception("API is not configured in the admin panel for this version.");
    }

    // --- 4. CHECK IF USER ALREADY HAS THIS NID IN RECORDS (to prevent duplicate charges) ---
    $check_sql = "SELECT id FROM server_copy WHERE user_id = ? AND nationalId = ? AND dateOfBirth = ? LIMIT 1";
    $check_stmt = $pdo->prepare($check_sql);
    $check_stmt->execute([$user_id, $nid, $dob]);
    $existing_record = $check_stmt->fetch();

    // --- 5. CALL MAIN NID API ---
    $url1 = $api_url . "?key=NID_ce6610efbeb381d932af5ab6&nid={$nid}&dob={$dob}";
    $ch1 = curl_init($url1);
    curl_setopt_array($ch1, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_TIMEOUT => 120,
        CURLOPT_HTTPHEADER => ['User-Agent: Mozilla/5.0']
    ]);
    $response1 = curl_exec($ch1);
    $httpCode1 = curl_getinfo($ch1, CURLINFO_HTTP_CODE);
    $curlError1 = curl_error($ch1);
    curl_close($ch1);

    if ($response1 === false || $httpCode1 !== 200) {
        throw new Exception("API সংযোগ ব্যর্থ: " . ($curlError1 ?: "HTTP $httpCode1"));
    }

    $resultJson = json_decode($response1, true);
    
    // Check if API returned cached data
    $is_cached = $resultJson['cached'] ?? false;
    $result = $resultJson['result'] ?? ($resultJson['data'] ?? null);

    if (!$result || !isset($resultJson['success']) || $resultJson['success'] !== true) {
        $errorMsg = $resultJson['message'] ?? 'আপনার দেওয়া তথ্য সঠিক নয়।';
        echo json_encode(['success' => false, 'message' => "❌ $errorMsg"]);
        exit;
    }

    // --- 6. START TRANSACTION & DEDUCT BALANCE (with logic for cached/free requests) ---
    $pdo->beginTransaction();
    
    // Determine actual cost based on whether data is cached and if user already has it
    $actual_cost = $cost;
    $balance_deducted = false;
    
    // If data is cached from API AND user already has this record in their history
    // Then don't charge again (or charge a reduced fee)
    if ($is_cached && $existing_record) {
        // Option 1: Don't charge at all for cached data user already has
        $actual_cost = 0;
        $balance_deducted = false;
        
        // Option 2: Charge a minimal fee (e.g., 5 taka) for accessing existing cached data
        // $actual_cost = 5;
    }
    
    // If we need to deduct balance
    if ($actual_cost > 0) {
        $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();
        if (!$user || $user['balance'] < $actual_cost) {
            $pdo->rollBack();
            throw new Exception("আপনার পর্যাপ্ত ব্যালেন্স নেই।");
        }
        $new_balance = $user['balance'] - $actual_cost;
        $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?")->execute([$new_balance, $user_id]);
        $balance_deducted = true;
    }

    // --- 7. EXTRACT DATA FROM API ---
    $nationalid   = $result['nationalId'] ?? '';
    $nameBangla   = $result['name'] ?? '-';
    $nameEnglish  = $result['nameEn'] ?? '-';
    $gender       = $result['gender'] ?? '-';
    $father       = $result['fatherName'] ?? '-';
    $mother       = $result['motherName'] ?? '-';
    $spouse       = '-';
    $photo_url    = $result['photo'] ?? '';
    $bloodGroup   = $result['bloodGroup'] ?? '-';
    $district     = $result['distric'] ?? $result['district'] ?? '-';
    $division     = $result['division'] ?? '-';
    $upozila      = $result['upozila'] ?? '-';
    $voterArea    = $result['voterArea'] ?? '-';
    $birthPlace   = $result['birthPlace'] ?? '-';
    $religion     = $result['religion'] ?? '-';
    $dob          = $result['dateOfBirth'] ?? '';
    $birthDay     = $result['birthDay'] ?? '-';
    $age          = $result['age'] ?? '-';
    $addressLine  = $result['addressLine'] ?? 'ঠিকানার তথ্য পাওয়া যায়নি';

    // --- 8. SET ADDRESSES SAME ---
    $presentAddress   = $addressLine;
    $permanentAddress = $addressLine;
    $unionOrWard      = extractUnionOrWard($result);

    // --- 9. DOWNLOAD & SAVE PHOTO ---
    $photo_path_relative = '';
    $photo_saved = false;
    if (!empty($photo_url) && filter_var($photo_url, FILTER_VALIDATE_URL)) {
        $ch_photo = curl_init($photo_url);
        curl_setopt_array($ch_photo, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_USERAGENT => 'Mozilla/5.0'
        ]);
        $photo_data = curl_exec($ch_photo);
        $photo_info = curl_getinfo($ch_photo);
        curl_close($ch_photo);

        if ($photo_data !== false && $photo_info['http_code'] === 200 && strlen($photo_data) > 1000) {
            if (!is_dir('uploads')) mkdir('uploads', 0755, true);
            $ext = 'jpg';
            $content_type = $photo_info['content_type'] ?? '';
            if (strpos($content_type, 'png') !== false) $ext = 'png';
            elseif (strpos($content_type, 'gif') !== false) $ext = 'gif';
            $filename = $user_id . '_' . time() . '_' . $nationalid . '.' . $ext;
            $photo_path_relative = 'uploads/' . $filename;
            if (file_put_contents($photo_path_relative, $photo_data) !== false) {
                $photo_saved = true;
            } else {
                error_log("Photo save failed: $photo_path_relative");
            }
        }
    }

    // --- 10. SAVE TO DATABASE (only if not already exists) ---
    $order_id = null;
    if (!$existing_record) {
        $sql = "INSERT INTO server_copy (
            user_id, zilaCode, day, age, nameBn, nameEn, nationalId, pin, dateOfBirth,
            father, mother, preAddress, perAddress, photo_path, gender, religion,
            bloodGroup, occupation, birthPlace, voterNo, voterArea, voterAreaCode, spouse, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";

        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $user_id,
            $district,
            $birthDay,
            $age,
            $nameBangla,
            $nameEnglish,
            $nationalid,
            '-',           // pin
            $dob,
            $father,
            $mother,
            $presentAddress,
            $permanentAddress,
            $photo_path_relative,
            $gender,
            $religion,
            $bloodGroup,
            '-',           // occupation
            $birthPlace,
            '-',           // voterNo
            $voterArea ?? $unionOrWard,
            '-',           // voterAreaCode
            $spouse
        ]);

        $order_id = $pdo->lastInsertId();
    } else {
        // If record already exists, use the existing order_id
        $order_id = $existing_record['id'];
        
        // Update the existing record with new photo if available
        if ($photo_saved) {
            $update_sql = "UPDATE server_copy SET photo_path = ?, created_at = NOW() WHERE id = ?";
            $pdo->prepare($update_sql)->execute([$photo_path_relative, $order_id]);
        }
    }

    $pdo->commit();

    // --- 11. BUILD PHOTO URL ---
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $base_url = $protocol . '://' . $host . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
    $full_photo_url = $photo_saved ? $base_url . '/' . $photo_path_relative : null;

    // --- 12. SUCCESS RESPONSE ---
    $response_message = 'তথ্য সফলভাবে সংগ্রহ করা হয়েছে!';
    if ($is_cached) {
        $response_message .= ' (ক্যাশ করা তথ্য)';
    }
    if (!$balance_deducted && $existing_record) {
        $response_message .= ' - পূর্বে সংগৃহীত তথ্য পুনরায় দেখানো হচ্ছে।';
    }

    echo json_encode([
        'success' => true,
        'message' => $response_message,
        'order_id' => $order_id,
        'cached' => $is_cached,
        'balance_deducted' => $balance_deducted,
        'deducted_amount' => $balance_deducted ? $actual_cost : 0,
        'data' => [
            'nameBangla'       => $nameBangla,
            'nameEnglish'      => $nameEnglish,
            'photo_saved'      => $photo_saved,
            'photo_path'       => $full_photo_url,
            'presentAddress'   => $presentAddress,
            'permanentAddress' => $permanentAddress,
            'district'         => $district,
            'upozila'          => $upozila,
            'voterArea'        => $voterArea,
            'birthDay'         => $birthDay,
            'age'              => $age
        ]
    ]);

} catch (Throwable $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("Server Copy Error (User: " . ($user_id ?? 'unknown') . "): " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => '❌ একটি ত্রুটি ঘটেছে। দয়া করে আবার চেষ্টা করুন।'
    ]);
}

// ====================== HELPER FUNCTIONS ======================
function extractUnionOrWard(array $data): string {
    if (!empty($data['unionOrWard']) && $data['unionOrWard'] !== '-') return $data['unionOrWard'];
    if (!empty($data['voterArea'])) {
        if (preg_match('/(\d+\s*নং\s*ওয়ার্ড)/iu', $data['voterArea'], $m)) return $m[1];
        if (preg_match('/ওয়ার্ড[^,।]*?(\d+)[^,।]*?(?=[,।]|$)/iu', $data['voterArea'], $m)) return trim($m[0]);
    }
    return $data['upozila'] ?? '-';
}