<?php
session_start();
error_reporting(1);
include('../includes/config.php');
include('../includes/db.php');
if (!isset($_SESSION['alogin'])) {
    header('location:login.php');
    die();
}
if (isset($_POST['brno']) && !empty($_POST['brno']) && isset($_POST['dob']) && !empty($_POST['dob'])) {
    //assign var value
    $brno = $_POST['brno'];
    $dob = $_POST['dob'];

    //get card price balance
    $sql = "SELECT * FROM control WHERE id='1'";
    $resulttt = mysqli_query($link, $sql);
    if (mysqli_num_rows($resulttt) > 0) {
        $row = mysqli_fetch_assoc($resulttt);
        $cardCost = $row['birthCardCost'];
    }
    //get user balance
    $sql = "SELECT * FROM users WHERE email= '{$_SESSION['alogin']}' ";
    $resulttt = mysqli_query($link, $sql);
    if (mysqli_num_rows($resulttt) > 0) {
        $row = mysqli_fetch_assoc($resulttt);
        $userBalance = $row['balance'];
        
    }
    if ($cardCost <= $userBalance) {
        //request for info

        // Define the URL of your PHP script that handles the POST request
        $url = "https://api.biometricinfo.co/api/v2/birth.php?birth=$brno&dob=$dob";

        // Create an associative array with the data you want to send
        

        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $url);
        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute cURL session and store the response
        $response = curl_exec($ch);

        // Check for cURL errors
        if (curl_errno($ch)) {
            
            echo json_encode([
                "success"=>false,
                "msg"=> "সার্ভারে যুক্ত হওয়া যায়নি।আবার চেষ্টা করুন।"
            ],JSON_UNESCAPED_UNICODE);
        } else {
            //check for data found

            if(!empty(json_decode($response)->personname)){
                // Process the response from the server (if needed)
                $data = json_decode($response,true);
                // The key-value pair you want to add
                $newItem = array("success" => true);
                // Add the new item before 'ubrn'
                $result = array_merge(array_slice($data, 0, 1), $newItem, array_slice($data, 1));
                echo(json_encode($result,JSON_UNESCAPED_UNICODE));
                // SQL query to insert data into the table with object properties
                // $sqlIns = "INSERT INTO `cards` (`userID`, `name`, `nameEn`, `gender`, `dateOfBirth`, `father`, `mother`, `spouse`, `nationalId`, `pin`, `mobile`, `religion`, `photo`, `permanentAddress`, `presentAddress`, `permanentDistrict`, `permanentUpazila`, `presentDistrict`, `presentUpazila`) 
                //         VALUES (
                //             '{$_SESSION['alogin']}', 
                //             '{$data->data->name}', 
                //             '{$data->data->nameEn}', 
                //             '{$data->data->gender}', 
                //             '{$data->data->dateOfBirth}', 
                //             '{$data->data->father}', 
                //             '{$data->data->mother}', 
                //             '{$data->data->spouse}', 
                //             '{$data->data->nationalId}', 
                //             '{$data->data->pin}', 
                //             '{$data->data->mobile}', 
                //             '{$data->data->religion}', 
                //             '{$data->data->photo}', 
                //             '{$data->data->permanentAddress}', 
                //             '{$data->data->presentAddress}', 
                //             '{$data->data->permanentDistrict}', 
                //             '{$data->data->permanentUpazila}', 
                //             '{$data->data->presentDistrict}', 
                //             '{$data->data->presentUpazila}'
                //         )";
                
                // mysqli_query($link, $sqlIns );
               
                
                //debit balance
                $sqlxxx = "UPDATE users SET balance = balance - $cardCost WHERE email = '{$_SESSION['alogin']}'";
                if(!mysqli_query($link, $sqlxxx )){
                    echo json_encode([
                        "success"=>false,
                        "msg"=> "Data Query Problem"
                    ],JSON_UNESCAPED_UNICODE);
                }
            }elseif(empty(json_decode($response)->personname)){
                echo json_encode([
                    "success"=>false,
                    "msg"=> "তথ্য খুঁজে পাওয়া যায়নি!দয়া করে জন্মনিবন্ধন নাম্বার ও জন্ম তারিখ সঠিকভাবে দিন"
                ],JSON_UNESCAPED_UNICODE);
            }else{
                echo json_encode([
                    "success"=>false,
                    "msg"=> "কিছুটা সমস্যা হয়েছে।আবার চেষ্টা করুন।"
                ],JSON_UNESCAPED_UNICODE);
            }
        }
        // Close cURL session
        curl_close($ch);
    }else{
        echo json_encode([
            "success"=>false,
            "msg"=> "আপনার একাউন্টে পর্যাপ্ত ব্যালেন্স নেই।দয়া করে রিচার্জ করুন।"
        ],JSON_UNESCAPED_UNICODE);
    }
}else{
    echo json_encode([
        "success"=>false,
        "msg"=> "Invalid Request"
    ],JSON_UNESCAPED_UNICODE);
}