<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include('includes/config.php');
include('includes/db.php');

// Check if session is active
if (!isset($_SESSION['alogin'])) {
    header('location:login.php');
    die();
}

if (isset($_POST['nid']) && !empty($_POST['nid']) && isset($_POST['dob']) && !empty($_POST['dob'])) {
    $nid = $_POST['nid'];
    $dob = $_POST['dob'];

    // Database connection check
    if (!$link) {
        die("Database connection failed: " . mysqli_connect_error());
    }

    // Get card price balance
    $sql = "SELECT cc_server_unofficial_price FROM control WHERE id='1'";
    $resulttt = mysqli_query($link, $sql);
    if ($resulttt && mysqli_num_rows($resulttt) > 0) {
        $row = mysqli_fetch_assoc($resulttt);
        $cardCost = $row['cc_server_unofficial_price'];
    } else {
        $_SESSION['Error'] = "Could not retrieve card cost.";
        header("Location: Server_Copy.php");
        exit();
    }

    // Get user balance
    $sql = "SELECT balance FROM users WHERE email='{$_SESSION['alogin']}'";
    $resulttt = mysqli_query($link, $sql);
    if ($resulttt && mysqli_num_rows($resulttt) > 0) {
        $row = mysqli_fetch_assoc($resulttt);
        $userBalance = $row['balance'];
    } else {
        $_SESSION['Error'] = "Could not retrieve user balance.";
        header("Location: Server_Copy.php");
        exit();
    }

    // Check if user has sufficient balance
    if ($cardCost <= $userBalance) {
        $url = "https://apinid={$nid}&dob={$dob}";
        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $response = curl_exec($ch);

        // Check for cURL errors
        if ($response === false) {
            die("cURL error: " . curl_error($ch));
        }

        // Check for data found
        $data = json_decode($response, true);

        if (isset($data['data']['nationalId'])) {
            $nationalid = $data['data']['nationalId'];
            $name = $data['data']['name'] ?? 'N/A';
            $nameEn = $data['data']['nameEn'] ?? 'N/A';
            $gender = $data['data']['gender'] ?? 'N/A';
            $dob = $data['data']['dateOfBirth'] ?? 'N/A';
            $pin = $data['data']['pin'] ?? 'N/A';
            $father = $data['data']['father'] ?? 'N/A';
            $spouse = $data['data']['spouse'] ?? 'N/A';
            $mother = $data['data']['mother'] ?? 'N/A';
            $photo = $data['data']['photo'] ?? 'N/A';
            $occupation = $data['data']['occupation'] ?? 'N/A';
            $religion = $data['data']['religion'] ?? 'N/A';
            $bloodGroup = $data['data']['bloodGroup'] ?? 'N/A';
            $district = $data['data']['permanentAddress']['district'] ?? 'N/A';
            $voterAreaCode = $data['data']['voterAreaCode'] ?? 'N/A';
            $sl_no = $data['data']['voter_sl_no'] ?? 'N/A';
            $voter_no = $data['data']['voter_no'] ?? 'N/A';

            // Address data
            $presentAddress = $data['data']['presentAddress'] ?? [];
            $permanentAddress = $data['data']['permanentAddress'] ?? [];

            // Include the original index.html files
            $htmlCode = file_get_contents('SVC.html');
            if ($htmlCode === false) {
                die("Failed to retrieve HTML template.");
            }

            // Replace placeholders with actual data
            $htmlCode = str_replace('{{districtPlaceholder}}', $district, $htmlCode);
            $htmlCode = str_replace('{{nationalidPlaceholder}}', $nationalid, $htmlCode);
            $htmlCode = str_replace('{{namePlaceholder}}', $name, $htmlCode);
            $htmlCode = str_replace('{{nameEnPlaceholder}}', $nameEn, $htmlCode);
            $htmlCode = str_replace('{{genderPlaceholder}}', $gender, $htmlCode);
            $htmlCode = str_replace('{{dobPlaceholder}}', $dob, $htmlCode);
            $htmlCode = str_replace('{{pinPlaceholder}}', $pin, $htmlCode);
            $htmlCode = str_replace('{{fatherPlaceholder}}', $father, $htmlCode);
            $htmlCode = str_replace('{{spousePlaceholder}}', $spouse, $htmlCode);
            $htmlCode = str_replace('{{motherPlaceholder}}', $mother, $htmlCode);
            $htmlCode = str_replace('{{photoPlaceholder}}', $photo, $htmlCode);
            $htmlCode = str_replace('{{occupationPlaceholder}}', $occupation, $htmlCode);
            $htmlCode = str_replace('{{religionPlaceholder}}', $religion, $htmlCode);
            $htmlCode = str_replace('{{bloodGroupPlaceholder}}', $bloodGroup, $htmlCode);
            $htmlCode = str_replace('{{voterAreaCodePlaceholder}}', $voterAreaCode, $htmlCode);
            $htmlCode = str_replace('{{slNoPlaceholder}}', $sl_no, $htmlCode);
            $htmlCode = str_replace('{{voterNoPlaceholder}}', $voter_no, $htmlCode);

            // Replace address placeholders
            $htmlCode = str_replace('{{presentAddress}}', formatAddress($presentAddress), $htmlCode);
            $htmlCode = str_replace('{{permanentAddress}}', formatAddress($permanentAddress), $htmlCode);

            // Output the modified HTML code
            echo $htmlCode;

            // Update user balance
            $sqlxxx = "UPDATE users SET balance = balance - $cardCost WHERE email = '{$_SESSION['alogin']}'";
            if (!mysqli_query($link, $sqlxxx)) {
                $_SESSION['Error'] = "Data Query Problem";
                header("Location: Server_Copy.php");
                exit();
            }
        } else {
            $_SESSION['Error'] = "NID data not found!";
            header("Location: Server_Copy.php");
            exit();
        }
        // Close cURL session
        curl_close($ch);
    } else {
        $_SESSION['Error'] = "Insufficient balance. Please recharge.";
        header("Location: Server_Copy.php");
        exit();
    }
} else {
    $_SESSION['Error'] = "Invalid Request";
    header("Location: Server_Copy.php");
    exit();
}

// Helper function to format address
function formatAddress($address) {
    return 'বাসা/হোল্ডিংঃ ' . ($address['homeHolding'] ?? '') .
           ', গ্রাম/রাস্তাঃ ' . ($address['villageOrRoad'] ?? '') .
           ', মৌজা/মহল্লাঃ ' . ($address['mouzaMoholla'] ?? '') .
           ', ইউনিয়ন/ওয়ার্ডঃ ' . ($address['unionOrWard'] ?? '') .
           ', পোস্ট অফিসঃ ' . ($address['postOffice'] ?? '') .
           ', পোস্ট কোডঃ ' . ($address['postalCode'] ?? '') .
           ', উপজেলাঃ ' . ($address['upozila'] ?? '') .
           ', জেলাঃ ' . ($address['district'] ?? '') .
           ', অঞ্চলঃ ' . ($address['region'] ?? '') .
           ', বিভাগঃ ' . ($address['division'] ?? '') . '।';
}
?>
