#!/bin/bash

# Clear any existing proxy settings
unset http_proxy
unset https_proxy
export no_proxy=localhost,127.0.0.1

# Database connection details
servername="172.24.250.97"
username="vignesh"
password="12345678"
db="websocketphp"

# Connect to MySQL and retrieve all necessary fields in one query
query=$(mysql -u"$username" -p"$password" -h"$servername" -D"$db" -se "SELECT a1, a2, a11, a12, a13 FROM curll WHERE type = 'aadhar';")

# Read the values into separate variables
IFS=$'\t' read -r url aadhaarno header1 header2 header3 <<< "$query"

# Remove quotes from the values
url=$(echo "$url" | tr -d '"')
aadhaarno=$(echo "$aadhaarno" | tr -d '"')
header1=$(echo "$header1" | tr -d '"')
header2=$(echo "$header2" | tr -d '"')
header3=$(echo "$header3" | tr -d '"')

# Print the retrieved values for debugging
echo "Retrieved URL: $url"
echo "Aadhaar Number: $aadhaarno"
echo "Header 1: $header1"
echo "Header 2: $header2"
echo "Header 3: $header3"

# Construct the payload using the Aadhaar number from the database
payload="{\"aadhaarNumber\":\"$aadhaarno\"}"

# Print the payload for debugging
echo "Payload: $payload"

# Make the API request using curl and capture the response and HTTP status code
response=$(curl -s --write-out "HTTPSTATUS:%{http_code}" --location "$url" \
-H "Content-Type: $header1" \
-H "clientId: $header2" \
-H "secretKey: $header3" \
-d "$payload")

# Extract the HTTP status code
http_code="${response##*HTTPSTATUS:}"

# Extract the body from the response
response_body="${response%HTTPSTATUS:*}"

echo "response $response_body"
# Print the full response for debugging
echo "Full API Response: $response_body"

# Check if the request was successful
if [ "$http_code" -eq 200 ]; then
# Parse and display relevant information from the JSON response
age_range=$(echo "$response_body" | jq -r '.result.data.age_range')
state=$(echo "$response_body" | jq -r '.result.data.state')
gender=$(echo "$response_body" | jq -r '.result.data.gender')

# echo "Verification Successful:"
# echo "Age Range: $age_range"
# echo "State: $state"ne
# echo "Gender: $gender"
# Insert the data into the MySQL table
insert_query="INSERT INTO response (application,response) VALUES ('aadhar', '$response_body');"

# Execute the INSERT query
mysql -u"$username" -p"$password" -h"$servername" -D"$db" -e "$insert_query"

echo "Data inserted successfully into the database."
else
echo "Failed to make API request. HTTP Status Code: $http_code"
echo "Response: $response_body"
fi