<?php
header( 'Access-Control-Allow-Origin:*' );

	error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
error_reporting( E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING );

date_default_timezone_set( "Asia/Karachi" );
$added_date_time = date( "Y-m-d H:i:s" );


$db_host = "jansnew.cgc8qcjgyunt.eu-central-1.rds.amazonaws.com";
$db_name = 'purchase_prod';
$db_username = 'jansadminpanel';
$db_password = 'Wabxmwg_XyecX8@';

//$conn = mysqli_connect("jansnew.cgc8qcjgyunt.eu-central-1.rds.amazonaws.com", "ahmedjpn", "testpass", "purchase_prod");
//$conn = mysqli_connect("localhost", "root", "", "janbiddingdata");


 $active_table = "auction_data";

//$active_table = "test_ahmed_auction_data";

//dynamic country list


function getRealPOST() {

	$pattern = '/(][)/';
	$replacement = '';
	$vars = new stdClass();
	$pairs = explode( "&", file_get_contents( "php://input" ) );
	foreach ( $pairs as $pair ) {
		$values = array();
		$nv = explode( "=", $pair );
		$name = urldecode( $nv[ 0 ] );

		$name = str_replace( array( '[', ']' ), '', $name );
		//		preg_replace($pattern, $replacement, $name);
		//echo $name." ";

		$value = urldecode( $nv[ 1 ] );
		//echo $value . "\n";

		if ( property_exists( $vars, $name ) ) {
			$vars->$name .= $value . ",";
		} else {
			$vars->$name = "";
			$vars->$name .= $value . ",";
		}

	}



	foreach ( $vars as $key => $val ) {
		$ar = array();
		$ar = explode( ",", $val );
		$vars->$key = $ar;
	}
	//print_r($vars);
	return $vars;

}

$mydata = getRealPOST();

//echo count($mydata) . "\n";


 $action = $mydata->action[ 0 ];
 /////////////////////////////////
    if($action != 'sayuri') {
        if (isset($_POST['send_site'])) {
            if ($_POST['send_site'] == 'iauc') {
                if ($_POST['security_token'] != '777') {

                    $msg['cenas'] = "E_expired";
                    $msg['msg_e'] = "Your License to Use This Extnesion Has Expired";
                    echo json_encode($msg);
                    return false;

                }
            }
        } else {
            // $msg['cenas'] = "E_expired";
            echo "Your License to Use This Extnesion Has Expired";
            return false;
        }
    }
/// //////////////////////////////
switch ( $action ) {

	case "insert":
		insert_data( $mydata, $added_date_time );
		break;
	case "update":
		update_data( $mydata );
		break;
	case "delete_existing_bids":
		delete_existing_bids($mydata);
	    break;	

    ///////////////////////////////
	/////////not found in iauc/////	
	case "delete":
		delete_data( $mydata );
		break;
	/////////not found in iauc/////	
	case "load":
		load_data( $mydata );
		break;
	/////////not found in iauc/////		
	case "bidders":
		bidder_data( $mydata );
		break;
    ///////not found in iauc///////
	case "user_bids_data":
		user_bids_data( $mydata );
		break;
    ///////not found in iauc///////	
	case "update_bid":
		user_bids_data( $mydata );
		break;


	//*************************//
	
}


/////////////////////////////

function load_data( $mydata ) {
	global $active_table;

	$conn = mysqli_connect($GLOBALS['db_host'], $GLOBALS['db_username'], $GLOBALS['db_password'], $GLOBALS['db_name'] );
	//
	mysqli_set_charset( $conn, "utf8mb4" );

	$aucnumlotnum = $mydata->aucnumlotnum[ 0 ];
	$username = $mydata->username[ 0 ];
	$password = $mydata->password[ 0 ];
	$car_detail_url = $mydata->car_detail_url[ 0 ];
	//"SELECT ur.id FROM users_roles ur INNER JOIN roles_countries rc ON rc.role_id = ur.role_id WHERE ur.user_id = '$user_id' AND rc.country_id = '$jans_country'"
		
		$jans_auction_date = $mydata->jans_auction_date[ 0 ];
		/////
		$jans_auction_date = DateTime::createFromFormat( 'd/m/Y', $jans_auction_date );
		$jans_auction_date = $jans_auction_date->format( 'Y-m-d' );
		////
		/*
		"SELECT ad.id, ad.lot_no, ad.bid_price, ad.company_name, ad.detail_link, ad.remarks, ufx.login_id 
		FROM $active_table AS ad, users_for_ext AS ufx 
		WHERE ufx.user_id =ad.added_by 
		AND ad.lot_no ='$aucnumlotnum' 
		AND ad.auction_date='$jans_auction_date'"
		*/
	
		//user roles not contain 2
		$result = mysqli_query( $conn, "SELECT ad.id, ad.lot_no, ad.bid_price, ad.company_name, ad.detail_link, ad.remarks, hl.hr_name, ufx.login_id
		FROM $active_table  AS ad 
		RIGHT JOIN roles_countries rc 
		ON ad.purchase_country=rc.country_id 
		RIGHT JOIN users_roles ur 
		ON rc.role_id=ur.role_id 
		RIGHT JOIN users_for_ext uf 
		ON ur.user_id=uf.user_id 
		RIGHT JOIN hr_level_detail hl 
		ON ad.purchase_country=hl.id 
		RIGHT JOIN users_for_ext ufx
		ON ufx.user_id = ad.added_by
		WHERE uf.login_id = '$username' 
		AND ur.deleted_at IS NULL
		AND ad.deleted_at IS NULL
		AND ad.lot_no='$aucnumlotnum' 
		AND ad.auction_date='$jans_auction_date' 
		AND ad.detail_link LIKE '%$car_detail_url%'
		GROUP BY ufx.login_id
		ORDER BY IF(ad.bid_price>500, ad.bid_price/10000, ad.bid_price) * 1 DESC
		" );



		if ( mysqli_num_rows( $result ) > 0 ) {

			while ( $row = mysqli_fetch_assoc( $result ) ) {
				echo $row[ "lot_no" ] . ",," . $row[ "company_name" ] . ",," . $row[ "detail_link" ] . ",," . $row[ "bid_price" ] . ",," . $row[ "remarks" ] . ",," . $row[ "hr_name" ] . ",," . $row[ "id" ] . ",," . $row[ "login_id" ] . ";";
			}
		} else {
			echo 'no data';
		}
		
	

}

function bidder_data( $mydata ) {

	$conn = mysqli_connect($GLOBALS['db_host'], $GLOBALS['db_username'], $GLOBALS['db_password'], $GLOBALS['db_name'] );
	
	mysqli_set_charset( $conn, "utf8mb4" );
	
	//username and password
	$username = $mydata->username[ 0 ];
	$password = $mydata->password[ 0 ];


	//"SELECT ur.id FROM users_roles ur INNER JOIN roles_countries rc ON rc.role_id = ur.role_id WHERE ur.user_id = '$user_id' AND rc.country_id = '$jans_country'"

	$result = mysqli_query( $conn, "SELECT * FROM users_for_ext where login_id = '$username' AND password = '$password'" );

	if ( mysqli_num_rows( $result ) > 0 ) {





		while ( $row = mysqli_fetch_assoc( $result ) ) {
			$user_id = $row[ 'user_id' ];
		}
		
		//date
		$jans_auction_date = $mydata->jans_auction_date[ 0 ];

		/////

		$jans_auction_date = DateTime::createFromFormat( 'd/m/Y', $jans_auction_date );
		$jans_auction_date = $jans_auction_date->format( 'Y-m-d' );
		////

		/*
		"SELECT ad.id, ad.lot_no, ad.bid_price, ad.company_name, ad.detail_link, ad.remarks, ufx.login_id 
		FROM $active_table  AS ad, users_for_ext AS ufx 
		WHERE ufx.user_id =ad.added_by 
		AND ad.lot_no ='$aucnumlotnum' 
		AND ad.auction_date='$jans_auction_date'"
		*/
		$result = mysqli_query( $conn, "SELECT * FROM $active_table  WHERE auction_date = '$jans_auction_date' AND deleted_at IS NULL " );
		if ( mysqli_num_rows( $result ) > 0 ) {
			while ( $row = mysqli_fetch_assoc( $result ) ) {
				echo $row[ "id" ] . ",,".$row[ "company_name" ] . ",," .$row[ "detail_link" ] . ",," .$row[ "lot_no" ] . ",," .$row[ "year" ] . ",," .$row[ "car_name" ] . ",," .$row["grade"] . ",," .	$row[ "type" ] . ",," .$row[ "cc" ] . ",," .$row[ "inspect" ] . ",," .$row[ "mileage" ] .",," .$row[ "color" ] . ",," .$row[ "shift" ] . ",," .$row[ "ac" ] . ",," .$row["condition" ] . ",," .$row[ "ext_grade" ] . ",," .$row[ "int_grade" ] . ",," .$row[ "start_price" ] . ",," .$row[ "bid_price" ] . ",," .$row[ "chassis_code" ] . ",," .$row["remarks" ] . ",," .$row["extension" ] . ",," .	$row[ "purchase_country" ] . ",," .$row[ "auction_sheet" ] . ",," .	$row[ "front_image"] . ",," .$row[ "rear_image" ] . ",," .	$row[ "added_by" ] . ",," .	$row[ "deleted_by" ] . ";;";
			}
		} else {
			echo 'no data';
		}
	} else {
		echo 'Sorry, username OR pwd is incorrect ' . $username;
	}

}



function update_data( $mydata ) {
global $active_table;


	$id = $mydata->id[ 0 ];
	$jans_bid_price = $mydata->jans_bid_price[ 0 ];
	$remarks = $mydata->remarks[ 0 ];
	$username = $mydata->username[ 0 ];
	$password = $mydata->password[ 0 ];
	$jans_country = $mydata->jans_country[ 0 ];

	$conn = mysqli_connect($GLOBALS['db_host'], $GLOBALS['db_username'], $GLOBALS['db_password'], $GLOBALS['db_name'] );
	mysqli_set_charset( $conn, "utf8mb4" );

	$result = mysqli_query( $conn, "SELECT * FROM users_for_ext where login_id = '$username' AND password = '$password'" );

	if ( mysqli_num_rows( $result ) > 0 ) {
		while ( $row = mysqli_fetch_assoc( $result ) ) {
			$user_id = $row[ 'user_id' ];
		}

		/*	SELECT ad.id, uf.login_id,ad.added_by,uf.user_id,ur.role_id,rc.role_id,rc.country_id,ad.purchase_country FROM $active_table  AS ad, roles_countries AS rc,users_roles AS ur, users_for_ext AS uf WHERE ad.id='$id' AND uf.login_id='$user_id' AND ad.added_by=uf.user_id AND ur.role_id=rc.role_id AND rc.country_id=ad.purchase_country
		 */
		$result = mysqli_query( $conn, "SELECT ad.id, ad.added_by,ur.role_id,rc.role_id,rc.country_id,ad.purchase_country 
		FROM $active_table  AS ad, users_roles AS ur, roles_countries AS rc 
		WHERE rc.country_id=ad.purchase_country 
		AND ur.user_id='$user_id' 
		AND ur.role_id=rc.role_id AND ad.id='$id'" );

		if ( mysqli_num_rows( $result ) > 0 ) {
			
			$browser = $_SERVER['HTTP_USER_AGENT'];
            $ip = $_SERVER['REMOTE_ADDR'];
			$u_date = date('Y-m-d H:i:s');
			/////
			$get_sql = "SELECT * FROM $active_table where id = '$id' AND (in_process =1 OR shifted = 1)";
			$q_result = mysqli_query( $conn,$get_sql);
			if ( mysqli_num_rows( $q_result ) > 0 )
			{
				echo 'Lot Number already transfered.You can not chnage the price';
				return false;
			}
			/////////////
			/*$sql = mysqli_query( $conn, "UPDATE $active_table  SET bid_price='$jans_bid_price', remarks='$remarks', last_edit_by='$user_id', edit_by_browser='$browser', edit_by_ip = '$ip', updated_at = '$u_date',
			updated_from = 'dbonline' 
			WHERE id='$id'" );
			*/
		    $log_sql = "INSERT INTO auction_data_log 
                        select * from auction_data where id = '$id'";
            mysqli_query( $conn,$log_sql);
            $jpn_chk = 0;
            if($jans_bid_price == 'nashi' || $remarks == 'nashi')
            {
                $jans_bid_price = 99999999;
                $remarks = 'nashi';
                $jpn_chk  = 1;
            }
			
			$sql = mysqli_query( $conn, "UPDATE $active_table  SET bid_price='$jans_bid_price', remarks='$remarks', 
                          last_edit_by='$user_id', purchase_country='$jans_country', edit_by_browser='$browser', 
                          edit_by_ip = '$ip', updated_at = '$u_date',
			              updated_from = 'dbonline',added_by = '$user_id',japan_check = '$jpn_chk'
			WHERE id='$id'" );
			

		} else {
			echo 'You are not allowed to alter this entry' . $id . " " . $user_id;
			return false;
		}
	} else {
		echo 'Sorry, username OR pwd is incorrect ' . $username;
	}
}

function delete_data( $mydata ) {
	global $active_table;

	$id = $mydata->id[ 0 ];
	$username = $mydata->username[ 0 ];
	$password = $mydata->password[ 0 ];

	$conn = mysqli_connect($GLOBALS['db_host'], $GLOBALS['db_username'], $GLOBALS['db_password'], $GLOBALS['db_name'] );
	mysqli_set_charset( $conn, "utf8mb4" );

	$result = mysqli_query( $conn, "SELECT * FROM users_for_ext where login_id = '$username' AND password = '$password'" );

	if ( mysqli_num_rows( $result ) > 0 ) {

		while ( $row = mysqli_fetch_assoc( $result ) ) {
			$user_id = $row[ 'user_id' ];
		}

		$result = mysqli_query( $conn, "SELECT ad.id, ad.added_by,ur.role_id,rc.role_id,rc.country_id,ad.purchase_country FROM $active_table  AS ad, roles_countries AS rc,users_roles AS ur WHERE ad.id='$id' AND ad.added_by='$user_id' AND ur.role_id=rc.role_id AND rc.country_id=ad.purchase_country" );

		if ( mysqli_num_rows( $result ) > 0 ) {

			$sql = mysqli_query( $conn, "DELETE FROM $active_table  WHERE id='$id'" );


		} else {
			echo 'You are not allowed to alter this entry';
			return false;
		}
	} else {
		echo 'Sorry, username OR pwd is incorrect ' . $username;
	}





}

function insert_data( $mydata, $added_date_time ) {

	global $active_table;
	///print_r($mydata);

	$username = $mydata->username[ 0 ];
	$password = $mydata->password[ 0 ];
	/////////////
	$extension_version = $mydata->extension_version[ 0 ];
	$extension_view = $mydata->extension_view[ 0 ];
	/////////////
	$user_id  = '';

	$conn = mysqli_connect($GLOBALS['db_host'], $GLOBALS['db_username'], $GLOBALS['db_password'], $GLOBALS['db_name'] );
	mysqli_set_charset( $conn, "utf8mb4" );

	$result = mysqli_query( $conn, "SELECT * FROM users_for_ext where login_id = '$username' AND password = '$password'" );

	if ( mysqli_num_rows( $result ) > 0 ) {





		while ( $row = mysqli_fetch_assoc( $result ) ) {
			$user_id = $row[ 'user_id' ];
		}
		if(empty($user_id))
		{
			echo "Please first login";
			return false;
		}
		
		$jans_auction_date = $mydata->jans_auction_date[ 0 ];
		
		if(empty($jans_auction_date))
		{
			echo "Your auction date is not properly set!";
			return false;
		}
	
		/////

		//$jans_auction_date = DateTime::createFromFormat( 'd/m/Y', $jans_auction_date );
		//echo $jans_auction_date = $jans_auction_date->format( 'Y-m-d' );
		$phpdate = strtotime($jans_auction_date);
			$jans_auction_date  = date( 'Y-m-d', $phpdate );
		////


		// correction in uss//

		$uss_time = "";
		$uss_is_correction = "";

		if(isset($mydata->uss_time[0]))
		{
			$uss_time = $mydata->uss_time[0];
		}
		if(isset($mydata->uss_is_correction[0]))
		{
			$uss_is_correction = $mydata->uss_is_correction[0];
		}
		
		//end uss//
		$auction_companys = $mydata->auction_company;
		$jans_country = $mydata->jans_country[ 0 ];
		$lot_nos1 = $mydata->lot_no1;
		$lot_nos2 = $mydata->lot_no2;
		$modelyears = $mydata->modelyear;
		$carnames = $mydata->carname;
		$grades = $mydata->grade;
		
		$types = $mydata->ctype;
		$ccs = $mydata->cc;
		$rates = $mydata->crate;
		$exts = $mydata->ext;
		$inters = $mydata->inter;
		$colors = $mydata->color;
		$colornos = $mydata->color_no;
		$shifts = $mydata->shift;
		$acs = $mydata->ac;
		$chassiscodes = $mydata->chassiscode;
		$inspections = $mydata->inspection;
		$mileages = $mydata->mileage;
		$jans_bid_prices = $mydata->jans_bid_price;
		$car_detail_urls = $mydata->car_detail_url;
		$remarks = $mydata->remark;
		$start_prices = $mydata->start_price;
		$aimage = $mydata->aimage;
		$fimage = $mydata->fimage;
		$rimage = $mydata->rimage;
		///extended///
		$ex_documents = $mydata->ex_document;
		$ex_notes = $mydata->ex_note;
		$ex_vehicle_historys = $mydata->ex_vehicle_history;
		$ex_drives = $mydata->ex_drive;
		$ex_accessoriess = $mydata->ex_accessories;
		$ex_fuels = $mydata->ex_fuel;
		$ex_seatss = $mydata->ex_seats;
		$ex_load_capacitys = $mydata->ex_load_capacity;
		$ex_registeration_months = $mydata->ex_registeration_month;
		$ex_doorss = $mydata->ex_doors;
			
		//echo count($colors);

		$check_user_country = mysqli_query( $conn, "SELECT ur.id FROM users_roles ur 
										INNER JOIN roles_countries rc ON rc.role_id = ur.role_id
										WHERE ur.user_id = '$user_id' AND rc.country_id = '$jans_country'" );

		if ( mysqli_num_rows( $check_user_country ) == 0 ) {

			echo "Selected country not in your rights";
			return false;
			//	exit();
		}
		////check user if is lock or ounlci
		$check_user_country_lock = mysqli_query( $conn, "SELECT id FROM  hr_level_detail WHERE id = '$jans_country' AND
		bid_lock = 1" );
		if ( mysqli_num_rows( $check_user_country_lock ) > 0 ) {

			echo "Purchase for this Market has been stopped by Japan Office.";
			return false;
			//	exit();
		}
		//////




		$rc = 0;
		//mysqli_select_db($auction,'shippings');

		for ( $j = 0; $j < count( $auction_companys ) - 1; $j++ ) {

			$lot_no1 = $lot_nos1[ $j ];
			$lot_no2 = $lot_nos2[ $j ];
			$modelyear = $modelyears[ $j ];
			$carname = $carnames[ $j ];
			if($carname)
			{
				//$carname = mysqli_real_escape_string($carname);
				$carname = strip_tags($carname);
				$carname = trim($carname);
			}
			$grade = $grades[ $j ];
			if($grade)
			{
				$grade = strip_tags($grade);
				//$grade = mysqli_real_escape_string($grade);
			 $grade = trim($grade);
				$grade = str_replace("'",'',$grade);
			}
			$type = $types[ $j ];
			if($type)
            {
                $type = trim($type,' ');
                $type = trim($type,'-');
            }

			$cc = $ccs[ $j ];
			if($cc)
			{
				$cc = strip_tags($cc);
				$cc = trim($cc);
			}
			$rate = $rates[ $j ];
			if($rate)
			{
				$rate = mysqli_real_escape_string($rate);
			$rate = trim($rate);
			}
			$ext = $exts[ $j ];
			$inter = $inters[ $j ];
			$color = $colors[ $j ];
			$colorno = $colornos[ $j ];
			$shift = $shifts[ $j ];
			if($shift)
			{
				$shift = strip_tags($shift);
				$shift = trim($shift);
			}
			$ac = $acs[ $j ];
			$auctionsheet = $aimage[ $j ];
			$frontimage = $fimage[ $j ];
			$rearimage = $rimage[ $j ];
			$chassiscode = $chassiscodes[ $j ];
			if($chassiscode)
                $chassiscode = trim($chassiscode,' ');
			$inspection = $inspections[ $j ];
			$mileage = $mileages[ $j ];
			$jans_bid_price = $jans_bid_prices[ $j ];
			$car_detail_url = $car_detail_urls[ $j ];
			$remark = $remarks[ $j ];
			$start_price = $start_prices[ $j ];
			$auction_company = $auction_companys[ $j ];
			$auction_company = strip_tags($auction_company);
			//if($auction_company == 'AAA')
			//$carname = '';
			
			$lot_no = $lot_no1."//".$lot_no2;
			///$lot_no=preg_replace("/[^0-9]/", "", $lot_no);
			$start_price=preg_replace("/[^0-9]/", "", $start_price);
			$company_id = get_auction_company_id($auction_company);
			///
			///extended///
		$ex_document = $ex_documents[$j];
		$ex_note = $ex_notes[$j];
		$ex_vehicle_history = $ex_vehicle_historys[$j];
		$ex_drive = $ex_drives[$j];
		$ex_accessories = $ex_accessoriess[$j];
		$ex_fuel = $ex_fuels[$j];
		$ex_seats = $ex_seatss[$j];
		if($ex_seats)
		$ex_seats = mysqli_real_escape_string($ex_seats);
		$ex_load_capacity = $ex_load_capacitys[$j];
		$ex_registeration_month = $ex_registeration_months[$j];
		$ex_doors = $ex_doorss[$j];
			///


		/*
			$check_record = mysqli_query( $conn, "SELECT id FROM $active_table  where deleted_at is null and auction_date = '$jans_auction_date' AND company_name = '$auction_company' AND purchase_country = '$jans_country' AND lot_no = '$lot_no'" );
			*/
			$check_record = mysqli_query( $conn, "SELECT id FROM $active_table  where deleted_at is null and auction_date = '$jans_auction_date' AND company_name_id = '$company_id' AND purchase_country = '$jans_country' AND lot_no2 = '$lot_no2'" );
			
			//echo "Hello";
			//echo mysqli_num_rows($check_record);
			if ( mysqli_num_rows( $check_record ) == 0 ) {


                                $browser = $_SERVER['HTTP_USER_AGENT'];
                                $ip = $_SERVER['REMOTE_ADDR'];
                                $jpn_chk  = 0;
                                if($jans_bid_price == 'nashi' || $remark == 'nashi')
                                {
                                    $jans_bid_price = 99999999;
                                    $remark = 'nashi';
                                    $jpn_chk  = 1;
                                }
				$sql = "INSERT INTO $active_table(`company_name`,`lot_no`,`year`,`car_name`,`grade`,`type`,`cc`,`condition`,`ext_grade`,`int_grade`,`color`,`color_no`,`shift`,`ac`,`auction_sheet`,`front_image`, `rear_image`, `inspect`,`mileage`,`auction_date`,`added_by`,`purchase_country`,`bid_price`, `chassis_code`, `extension`, `remarks`, `start_price`, `created_at`,`detail_link`, `browser`, `ip`,`auction_no`,`lot_no2`,`company_name_id`,`bid_price_ori`,`extension_version`,`extension_view`,`japan_check`) VALUES('$auction_company','$lot_no','$modelyear','$carname','$grade','$type','$cc','$rate','$ext','$inter','$color','$colorno','$shift','$ac','$auctionsheet','$frontimage','$rearimage','$inspection','$mileage','$jans_auction_date','$user_id','$jans_country','$jans_bid_price', '$chassiscode', 'dbonline', '$remark', '$start_price', '$added_date_time','$car_detail_url', '$browser', '$ip','$lot_no1','$lot_no2','$company_id','$jans_bid_price','$extension_version','$extension_view','$jpn_chk');";
                                 
				if ( $conn->query( $sql ) === TRUE ) {
					$last_id = $conn->insert_id;
					$ex_sql = "INSERT INTO auction_data_extended(`auction_data_id`,`document`,`note`,`vehicle_history`,
					`drive`,`accessories`,`fuel`,`seats`,`load_capacity`,`registeration_month`,`doors`,`uss_time`,`uss_is_correction`)
					VALUES('$last_id','$ex_document','$ex_note','$ex_vehicle_history','$ex_drive','$ex_accessories',
					'$ex_fuel','$ex_seats','$ex_load_capacity','$ex_registeration_month','$ex_doors','$uss_time','$uss_is_correction')";
					$conn->query($ex_sql);

						///////////////////////
						$url = "https://www.JJPurchase.com/api/update_market_cap_rates";
						$data = array (
								'auction_data_id' => $last_id,
							);
							$post = http_build_query($data);
							$x = curl_init($url);
							curl_setopt($x, CURLOPT_POST, true);
							curl_setopt($x, CURLOPT_RETURNTRANSFER, true);
							curl_setopt($x, CURLOPT_SSL_VERIFYPEER, false);
							curl_setopt($x, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
							curl_setopt($x, CURLOPT_POSTFIELDS, $post);
							$y = curl_exec($x);
							///print_r($y);
							curl_close($x);
						///////////////////////

					//echo "data from db is " . $lot_no . ", " .  $car_detail_url . ",####";
				} else {
					echo "Error: " . $sql . "<br>" . $conn->error;
				} {
					///	$rtnjsonobj->message= mysqli_error($auction);
					//echo $_POST['callback']. '('. json_encode($rtnjsonobj) . ');';
				}
				$rc++;
			}
			else
			{
				echo "Lot number is already exist in database!";
				die();
			}
		}
		if ( $rc > 0 ) {
			//echo $rc . ' cars added successfully';
			echo $last_id;
		}

		/////////////////////////////////////////




	} else {
		//echo "Sorry username/pwd is incorrect";
		echo 'Sorry, username OR pwd is incorrect ' . $username;
	}
}



//////////////////////////////////////////////////////////////
function get_auction_company_id($company_name)
{
	$conn = mysqli_connect($GLOBALS['db_host'], $GLOBALS['db_username'], $GLOBALS['db_password'], $GLOBALS['db_name'] );
	mysqli_set_charset( $conn, "utf8mb4" );
 $sql = "SELECT * from auction_companies_other where auction_company_name = '$company_name'";
	$result = mysqli_query($conn,$sql) or die(mysqli_error());
	$company_id = '';
	while ( $row = mysqli_fetch_assoc( $result ) ) {
			 $company_id = $row[ 'company_name_id_master' ];
		
		}
		return $company_id;
	
}

	/////////////////////////
	
	function get_login_users_cntry($user_id)
	{
		$conn = mysqli_connect($GLOBALS['db_host'], $GLOBALS['db_username'], $GLOBALS['db_password'], $GLOBALS['db_name'] );
	mysqli_set_charset( $conn, "utf8mb4" );
		
		$result = mysqli_query($conn, "SELECT hr.id,  hr.hr_name 
		FROM hr_level_detail AS hr
		INNER JOIN roles_countries AS rc
		ON rc.country_id = hr.id
		INNER JOIN users_roles AS ur
		ON ur.role_id = rc.role_id
		WHERE ur.deleted_at IS NULL
		AND ur.user_id = '$user_id'" );
		$country_arr = array();
		if ( mysqli_num_rows( $result ) > 0 ) {
			while ( $row = mysqli_fetch_assoc( $result ) ) {
				//echo "<option value='" . $row[ "id" ] . "'>"  . $row[ "hr_name" ]  . "</option>";
				$country_arr[] = $row[ "id" ];
			}
		}
		return $country_arr;
	}



///////////////delete exsisting bid////////////////////////


function delete_existing_bids($mydata)
{

    $username = $mydata->username[ 0 ];
    $password = $mydata->password[ 0 ];
	$bid_id = $mydata->id[ 0 ];

    $action = 'login';
    $fields = array(

        'login_id' => $username,
        'password' => $password,

    );
	//////////////////////////////////////////////////
	
	$con = mysqli_connect($GLOBALS['db_host'], $GLOBALS['db_username'], $GLOBALS['db_password'], $GLOBALS['db_name'] );
	mysqli_set_charset( $con, "utf8mb4" );
	
	$result = mysqli_query( $con, "SELECT * FROM users where login_id = '$username'" );
	$user_id = '';
	if ( mysqli_num_rows( $result ) > 0 ) {

		while ( $row = mysqli_fetch_assoc( $result ) ) {
			$user_id = $row[ 'id' ];
			$api_token = $row['remember_token'];
		}
	}
    $action = 'del_bid';
    $bid_ids = array($bid_id);
    $fields = array(
    	"app_id" => 155,
        'app_token' => "216875912",
        'app_user_id' => $user_id,
        'auction_data_id' => $bid_id,
        "api_token" => "pwM0rcVzZ9gA4rdOGgWz2gyRLebg84qN7cQRD0AfrzugWKwlNiQOns9N8QAt"

    );
    $response = api_call($action,$fields);
    echo json_encode($response);
}
function api_call($action,$fields=array()){

    $base_url = 'https://www.jjpurchase.com/api/';
    $url = $base_url.$action;
    foreach($fields as $key=>$value) { 
    	$fields_string .= $key.'='.$value.'&'; 
    }
    rtrim($fields_string, '&');
    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch, CURLOPT_USERAGENT, "IAUC Extention");
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_POST, count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //execute post
    $result = curl_exec($ch);

    $result = json_decode($result);

    //close connection
    curl_close($ch);
    return $result;
}

///////////////////////////////////////////////////////////////

function is_block_company($country_id,$company_id)
{
	$conn = mysqli_connect($GLOBALS['db_host'], $GLOBALS['db_username'], $GLOBALS['db_password'], $GLOBALS['db_name'] );
	mysqli_set_charset( $conn, "utf8mb4" );
	$result = mysqli_query( $conn, "SELECT * FROM country_restriction_company WHERE country_id = $country_id AND company_id = $company_id AND is_deleted IS NULL" );

	if ( mysqli_num_rows( $result ) > 0 ) {
		return true;
	}
	return false;
}
//////////////////////////////////////////////////////////////////////


?>