<?php

$GLOBALS['STtax'] = 14;
$GLOBALS['SBCesstax'] = 0.5;
$GLOBALS['KKCesstax'] = 0.5;
$GLOBALS['currDateTime'] = date('Y-m-d H:i:s');
$GLOBALS['currDate']= date('Y-m-d');
$GLOBALS['currTime']= date('H:i:s');

//$con_obj	= mysql_connect('localhost','steelmin_apitest','apitest1@3') or die('On Maintenance, please try again in some minutes.');
//$seldb		= mysql_select_db("steelmin_api_test", $con_obj) or die(mysql_error());

//include_once ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
require("/home/steelmin/public_html/inc/config1.php");
require("/home/steelmin/public_html/hf.php");

//require("cf.php");
//require("cf_new.php");
//ini_set('display_errors',1);

/*
$evnts = getEvents();
print_R($evnts); */
//$type = "All, Upcoming, Expaired";

function getEvents($type='All'){
    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
    $whrcond="1";

    if('Upcoming'==$type)
        $whrcond = "status >= 1";
    if('Expired'==$type)
        $whrcond = "status = 0";

    $rs = mysql_query("
		select id as event_id, event_name, event_start_date, event_end_date, event_venue, agenda, status, event_image
		from tbl_sm_events_events
		where $whrcond
		order by status, event_start_date desc
	")or die(mysql_error());

    $_rs_array = array();

    while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
        $thumb ='';$image='';$event_video='';
        if($row['event_image']){
            $thumb = 'https://events.steelmintgroup.com/images/events/thumb_'.$row['event_image'];
            $image = 'https://events.steelmintgroup.com/images/events/'.$row['event_image'];
        }
        if($row['event_video'])
            $event_video= 'https://events.steelmintgroup.com/images/events/'.$row['event_video'];

        $venue_arr = explode(",", $row['event_venue']);
        $event_venue='';
        $event_location='';

        if($tot = count($venue_arr) >=2 ){
            $event_location = $venue_arr[$tot-1];
            $event_venue= str_replace(','.$event_location, "", $row['event_venue']);
        }else{
            $event_venue='';
            $event_location=$row['event_venue'];
        }

        $event_start_date = $row['event_start_date'];
        $event_end_date = $row['event_end_date'];

        $event_date = null ;

        if($event_start_date > '2000-01-01' && $event_start_date!=$event_end_date)
            $event_date = date("d", strtotime($event_start_date)).'-'.date("d M Y", strtotime($event_end_date));
        else
            $event_date = date("M Y", strtotime($event_start_date));

        if($row['status']==1){
            $_rs_array[] = [
                'id'=>$row['event_id'],
                'name'=>$row['event_name'],
                'timestamp'=>$event_date,
                'venue'=>$event_venue,
                'location'=>$event_location,
                'agenda'=>$row['agenda'],
                'thumb_img'=>$thumb,
                'img'=>$image,
                'video'=>$event_video ,
                'enable' => true ,
            ];
        }else{
            $_rs_array[] = [
                'id'=>$row['event_id'],
                'name'=>$row['event_name'],
                'timestamp'=>$event_date ,
                'venue'=>$event_venue,
                'location'=>$event_location,
                'agenda'=>$row['agenda'],
                'thumb_img'=>$thumb,
                'img'=>$image,
                'video'=>$event_video ,
                'enable' => false ,
            ];
        }
    }

    include ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php' );

    return $_rs_array;

}

/////////////////////////////Speakers list//////////////
/*
$event_id='5';//optional default it returns current event Speakers list
$evnts = getSpeakers();
print_R($evnts); */
function getSpeakers($event_id=''){
    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
    $whrcond="1";

    if($event_id=='')
        $event_id = getActiveEventId();

    $whrcond = " t.event_id = $event_id";
    //$whrcond = " t.event_id = '$event_id' or like '%,$event_id' or like '$event_id,%'";
//    $sql ="
//		select s.id, s.name,s.designation,s.company,s.basic_profile,t.topic,t.event_id,image
//		from tbl_sm_events_speakers as s
//		left outer join
//		tbl_sm_events_speakers_topic as t
//		ON s.id=t.speaker_id
//		where $whrcond
//		order by id asc
//	";
//    $sql = "
//		select s.*, t.topic
//		from
//		(
//			select 	id, name, designation, company, basic_profile, $event_id as eventId
//			from 	tbl_sm_events_speakers
//			where  	( event_id like ',$event_id,' or event_id like '%,$event_id' or event_id like '$event_id,%' or event_id = '$event_id')
//		) as s
//
//		left outer join tbl_sm_events_speakers_topic as t ON s.id = t.speaker_id
//		AND  t.event_id = $event_id
//		order by 2 asc
//	";
//    $sql = "
//        select s.*, t.topic
//        from
//        (
//        select id, name, designation, company, basic_profile, $event_id as event_id, image
//        from tbl_sm_events_speakers
//        where  	( event_id like ',$event_id,' or event_id like '%,$event_id' or event_id like '$event_id,%' or event_id = '$event_id')
//        ) as s
//
//        left outer join tbl_sm_events_speakers_topic as t ON s.id = t.speaker_id
//        AND  t.event_id = $event_id
//        order by 2 asc
//        ";

    $sql = "
		select s.*, t.topic
		from
		(
			select 	id, name, designation, company, basic_profile, $event_id as event_id, image
			from 	tbl_sm_events_speakers
			where  	( event_id like ',$event_id,' or event_id like '%,$event_id' or event_id like '$event_id,%' or event_id = '$event_id')
		) as s

		left outer join tbl_sm_events_speakers_topic as t ON s.id = t.speaker_id
		AND  t.event_id = $event_id
		order by 2 asc
	";

    $rs = mysql_query($sql)or die(mysql_error().$sql);

    $_rs_array = array();

    while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
        $thumb ='';$image='';
        if($row['image']){
            $thumb = 'https://events.steelmintgroup.com/images/events/speakers/thumb_'.$row['image'];
            $image = 'https://events.steelmintgroup.com/images/events/speakers/'.$row['image'];
        }

        $_rs_array[] = array(
            'id' => $row['id'] ,
            'event_id'=>$row['event_id'],
            'name'=>  ucwords(strtolower($row['name'])),
            'position'=>ucwords(strtolower($row['designation'])),
            'company'=>ucwords(strtolower($row['company'])),
            'desc'=> $row['basic_profile']. $row['company'] ,
            'subject'=>$row['topic'],
            'thumb_img'=>$thumb,
            'image'=>$image
        );
    }
    include ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php' );

    return $_rs_array;
}

/////////////////////////////Sponsers list//////////////
/*
$event_id=5;//optional default it returns current event Speakers list
$type='';//optional exhibitor/sponser
$evnts = getSponsors();
//$evnts = getSponsors($event_id,$type);
print_R($evnts); */

function getSponsors($event_id='', $type=''){
    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
    if($event_id=='')
        $event_id = getActiveEventId();

    $whrcond = " (  event_id like ',$event_id,' or event_id like '%,$event_id' or event_id like '$event_id,%' or event_id = '$event_id' ) ";


    if(''!=$type)
        $whrcond .= " AND sponser_or_exhibitor = '$type'";
    $sql = "
		select id , event_id, sponser_type, company, logo, location, sponser_website_link, sponser_or_exhibitor
		from tbl_sm_events_sponsors
		where $whrcond
		order by id desc
	";

    $rs = mysql_query($sql)or die(mysql_error().$sql);

    $_rs_array = array();

    $_rs_array['exhibitors'] = [];

    while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
        $thumb ='';$image='';
        if($row['logo']){
            $thumb = 'https://events.steelmintgroup.com/images/events/sponsers/thumb_'.$row['logo'];
            $image = 'https://events.steelmintgroup.com/images/events/sponsers/'.$row['logo'];
        }

        if($row['sponser_or_exhibitor']=='sponsor'){
            $_rs_array['sponsors'][$row['sponser_type']][] = array(
                'id'        => strval($row['id']) ,
                'event_id'  =>$row['event_id'],
                'name'      =>$row['company'],
//                'region'    =>$row['state'].", ".$row['city'],
                'region'    => $row['location'] ,
                'website'   =>$row['sponser_website_link'],
                'thumb_img'=>     $thumb,
                'img'=>$image
            );

        }else if ($row['sponser_or_exhibitor']=='exhibitor'){
            $_rs_array['exhibitors'][] = array(
                'id' => strval($row['id']) ,
                'event_id'=>$row['event_id'],
                'name'=>$row['company'],
                'region'=>$row['location'],
                'website'=>$row['sponser_website_link'],
                'thumb_img'=>$thumb,
                'img'=>$image
            );
        }
    }

    include ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php' );

    return $_rs_array;
}

/////////////////////////////Participant list//////////////
//
//$event_id=5;//optional default it returns current event Speakers list
//
////1) for all delegates/Participant
////$evnts = getParticipant($event_id);
//
////2) with fillters => delegates/Participant
////$fillters['country'] = '5,6,15';///comma seprated values
//$fillters['company'] = 'steel,SteelMint';///comma seprated values
////$fillters['designation'] = '1,9,2,5';///comma seprated values
////$fillters['profile'] = '35,34,37';///comma seprated values
//
//$evnts = getParticipant($event_id,$fillters);
//print_R($evnts);

///delegate_profile = companytype in tbl_members
/*
*/
//print_R($evnts);
function getDelegatesIds($event_id){
    if($event_id=='')
        $event_id = getActiveEventId();
    //$whrcond = " event_id = $event_id and inv_no <> '' ";
    $whrcond = " event_id = $event_id ";
$_sql = "
		SELECT `delegates_ids`
		FROM `tbl_sm_events_payment_details`
		WHERE $whrcond
		AND `registering_id`
		IN (

		SELECT registering_id
		FROM `final_status`
		WHERE (`closed` = 'Y')
		AND $whrcond

		)
		AND `inv_no` <> ''
		
		UNION All

		SELECT registering_id
		FROM `final_status`
		WHERE (`complementary` = 'Y')
		AND `eventid` = $event_id
		
	";
	/* UNION All

		SELECT `memid`
		FROM `tbl_event_tag_mapping`		
		WHERE `tag` = 'CLOSED' 
		group by memid
	*/
	return qryToCommaSepString($_sql);
    /* return qryToCommaSepString("
		SELECT delegates_ids
		from tbl_sm_events_payment_details
		where $whrcond
	"); */
}


function getParticipant($event_id='', $fillters=array()){
    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
//    $event_id = 1 ;
    if($event_id=='')
        $event_id = getActiveEventId();

    $delegates_ids = getDelegatesIds($event_id);

//    var_dump($delegates_ids) ;

    if($delegates_ids=='')
        $delegates_ids=0;

    $whrcond = " d.id in ($delegates_ids) ";
    if(isset($fillters['profile'])){
        $profile = "'". str_replace( ",", "','", $fillters['profile'])."'";
        $whrcond .= " AND d.companytype in ($profile)";
    }

    $having='';
    if(isset($fillters['country'])){
        $_contry_ids = $fillters['country'];
        $whrcond .= " AND d.country in ($_contry_ids)";
    }

    if(isset($fillters['company'])){
        $company = "'". str_replace( ",", "','", $fillters['company'])."'";
        $whrcond .= " AND d.company in ($company)";
    }

    /* if(isset($fillters['profile'])){
        $profile = "'". str_replace( ",", "','", $fillters['profile'])."'";
        $having .= " AND delegate_profile in ($profile)";
    } */

    /* if(isset($fillters['profile'])){
        $profile = "'". str_replace( ",", "','", $fillters['profile'])."'";
        $having .= " AND companytype in ($profile)";
    } */

    if(isset($fillters['designation'])){
        $designation = "'". str_replace( ",", "','", $fillters['designation'])."'";
        $whrcond .= " AND designation in ($designation)";
    }

    if($having)$having = " having 1 ".$having;

    $sql = "
		select d.id, d.name, des.name as designation, company,email, phoneno,
		CASE
			WHEN d.country=113 AND other_city<>'' THEN concat(other_city, ', India')
			WHEN d.country=113 AND other_city='' THEN concat(city_name, ', ', sc.state_name, ', ', c.country)
			WHEN d.country=0 AND other_city<>'' THEN other_city
			WHEN d.country=0 AND other_city='' THEN 'Others'
			ELSE c.country
		END as location,  ct.name as delegate_profile, d.country
		from tbl_members d
		left join tbl_companytype ct
		ON ct.id = d.companytype
		left join tbl_state_city sc
		ON d.country=sc.country_id
		AND d.state=sc.state_id
		AND d.city=sc.city_id
		left join tbl_country c
		ON d.country=c.id
		left join tbl_designation des
		ON d.designation = des.id
		where $whrcond
		group by d.id
		$having
		order by id desc
	";
//	die;
    $rs = mysql_query($sql)or die(mysql_error().$sql);

    $_rs_array = array();

//    var_dump(mysql_fetch_assoc($sql)) ;

    while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
        $thumb ='';$image='';
        /* if($row['delegate_image']){
            $thumb = 'https://events.steelmintgroup.com/images/events/delegates/thumb_'.$row['delegate_image'];
            $image = 'https://events.steelmintgroup.com/images/events/delegates/'.$row['delegate_image'];
        } */
//        var_dump($row) ;        $thumb = 'https://events.steelmintgroup.com/images/events/delegates/thumb_'.$row['id'].'.jpg';        $image = 'https://events.steelmintgroup.com/images/events/delegates/'.$row['id'].'.jpg';//
		$thumb = 'https://events.steelmintgroup.com/images/events/delegates/dummy-man.jpg';
        $image = 'https://events.steelmintgroup.com/images/events/delegates/dummy-man.jpg';
		$_rs_array[] = array(
            "id" => $row['id'] ,
            'name'=> ucwords(strtolower($row['name'])),
            'designation'=>ucwords(strtolower($row['designation'])),
            'company'=> ucwords(strtolower(html_entity_decode($row['company'], ENT_QUOTES))),
            'email'=>$row['email'],
//            'email'=>"mohan@steelmint.com",
            'phoneno'=>$row['phoneno'],
            'profile'=>$row['delegate_profile'],
            'region'=>$row['location'],
            'thumb_img'=>$image,
            'img'=> $thumb
        );
    }

    include ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php' );
    return $_rs_array;
}

//
//$event_id=5
//print_r(getParticipantFilters($event_id));

function getParticipantFilters($event_id=''){
    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
//    $event_id =1 ;
    if($event_id=='')
        $event_id = getActiveEventId();

    $delegates_ids = getDelegatesIds($event_id);

    $_participant =array();

    $_participant['designation'] = array( ['filter'=>'Director' ],
        ['filter'=>'Executive'],
        ['filter'=>'Manager']
    );

    $_participant['designation'] = array_values($_participant['designation']) ;

    //$_participant['company'] = array('OMC','NMDC','PIG_IRON');
    $_participant['profile'] = array( ['filter'=>'Broker' ],
        ['filter'=>'Trader'],
        ['filter'=>'Exporter'],
        ['filter'=>'Importer'],
        ['filter'=>'Manufacture']);

    $_participant['profile'] = array_values($_participant['profile']) ;


    //$whrcond = " event_id = '$event_id' ";

    $whrcond = " d.id in ($delegates_ids) ";

    $sql = "
		SELECT DISTINCT d.country as country_id, c.country AS country_name
		from tbl_members d
		left outer join
		tbl_country c
		ON d.country=c.id
		where $whrcond
		HAVING country_id <>0
		order by country_name asc
	";
    $rs = mysql_query($sql)or die(mysql_error().$sql);

    $_rs_array = array();

    while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
        if(!empty($row['country_id'] ) )
            $_participant['country'][$row['country_id']] = array(
                "filter" => $row['country_name'] );
        else
            $_participant['country']['0'] = array( "filter" => 'Others' ) ;
    }

    $_participant['country'] = array_values($_participant['country']) ;
//    $whrcond = " id in ($delegates_ids) ";
    $sql = "
		SELECT DISTINCT company as company_name
		from tbl_members d
		where $whrcond

		order by company_name asc
	";
    $rs = mysql_query($sql)or die(mysql_error().$sql);

    $_rs_array = array();

    while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
        if(!empty($row['company_name']))
            $_participant['company'][] = array(
                "filter" => trim($row['company_name']));
    }

    include ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php' );
    return $_participant;
}


/* /////////////////////////////Speakers list//////////////
$event_id='5';//optional default it returns current event Schedules list
$evnts = getSchedules();
print_R($evnts);  */
function getSchedules($event_id='', $timezone = 'Asia/Kolkata'){
    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
    $whrcond="1";

    if($event_id=='')
        $event_id = getActiveEventId();

    $whrcond = " event_id = $event_id";
    //$whrcond = " t.event_id = '$event_id' or like '%,$event_id' or like '$event_id,%'";
    $sql ="
		select *
		from tbl_sm_events_schedule
		where $whrcond
		order by id 
	";
    $rs = mysql_query($sql)or die(mysql_error().$sql);

    $_rs_array = array();

    while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){

        $date = new DateTime($row['schedule_date'] . " ".$row['schedule_time'] , new DateTimeZone($timezone));
        $timestamp =  $date->getTimestamp();
        $_rs_array[] = [
//            "time" => strtotime($row['schedule_date'] . " ".$row['schedule_time'] ) ,
            "time" => $timestamp ,
//            "temp" => $row['schedule_date'] . " ".$row['schedule_time'] ,
            "title" => $row['schedule_title'] ,
            "desc" => $row['schedule_desciption'] ,
            "event_time" => $row['formatted_time']
        ] ;
    }
    include ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php' );

    return $_rs_array;
}

/////////////////////////////An Event Details //////////////
/*
$event_id='5';//optional default it returns current event Schedules list
$ip='103.46.241.130';

$evnts = getEventPackageDetail();
print_R($evnts);
 */
function get_client_ip()
 {
      $ipaddress = '';
      if (getenv('HTTP_CLIENT_IP'))
          $ipaddress = getenv('HTTP_CLIENT_IP');
      else if(getenv('HTTP_X_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
      else if(getenv('HTTP_X_FORWARDED'))
          $ipaddress = getenv('HTTP_X_FORWARDED');
      else if(getenv('HTTP_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_FORWARDED_FOR');
      else if(getenv('HTTP_FORWARDED'))
          $ipaddress = getenv('HTTP_FORWARDED');
      else if(getenv('REMOTE_ADDR'))
          $ipaddress = getenv('REMOTE_ADDR');
      else
          $ipaddress = 'UNKNOWN';

      return $ipaddress;
 }

function getEventPackageDetail($ip='', $event_id='', $_prices_for=''){
    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
    $_rs_array = array();
    if($event_id=='')
        $event_id = getActiveEventId();

    $event_details = get_latest_event_details($event_id);
    list($event_venue , $event_date , $event_name , $indian_first_delegate , $indian_second_delegate , $indian_third_delegate , $nonindian_first_delegate , $nonindian_second_delegate , $nonindian_third_delegate, $is_offer_active , $std_indian_first_delegate , $std_indian_second_delegate , $std_indian_third_delegate , $std_nonindian_first_delegate , $std_nonindian_second_delegate , $std_nonindian_third_delegate, $is_onspot_active , $onspot_indian_first_delegate , $onspot_indian_second_delegate , $onspot_indian_third_delegate , $onspot_nonindian_first_delegate , $onspot_nonindian_second_delegate , $onspot_nonindian_third_delegate, $early_bird_date, $is_std_active, $super_early_bird_date) = explode('/*/',$event_details);


    //$ip_countryName = ipTocntry($ip); // This function was giving time out
    //$url = "https://www.ip-api.com/json/".$ip;
	
	//following lines commented by tarun on 3-July-2017 as for upcoming event only USD is considered; consider getting country_name from APP itself
    /* $url = "https://www.freegeoip.net/json/".$ip;
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $response = curl_exec($ch);
    curl_close($ch);	
    $ipToCountryApiData = (array) json_decode($response, true);	
    $ip_countryName = strtoupper($ipToCountryApiData['country_name']); */

//    $is_std_active = 0;
    if($is_offer_active==1)
        $is_std_active =2;
	
	 if($is_onspot_active!=1)
        $is_onspot_active =2;
	else{
		$is_std_active =0;
	}
	
	$super_early_bird_datetime = strtotime($super_early_bird_date);
	$currDateTime = strtotime($GLOBALS['currDateTime']);
   // if(trim($ip_countryName) == 'INDIA'){
    if(0){///for bangkok event all in Dollers
        
		if($currDateTime <= $super_early_bird_datetime){//super early bird date
			$_rs_array['early_bird']= array(
				'is_active' => $is_offer_active,
				'onspot_date' => $super_early_bird_date,
				"p_type" => "INR" ,
				"tab_name" => "Super Early Bird" ,
				"delegate" => array(
					'1 Delegates' => intval ($indian_first_delegate ),
					'2 Delegates'=> $indian_second_delegate ,
					'3 Delegates'=> $indian_third_delegate
					),
			);
		}else{
			$_rs_array['early_bird']= array(
				'is_active' => $is_offer_active,
				'onspot_date' => $early_bird_date,
				"p_type" => "INR" ,
				"tab_name" => "Early Bird" ,
				"delegate" => array(
					'1 Delegates' => intval ($indian_first_delegate ),
					'2 Delegates'=> $indian_second_delegate,
					'3 Delegates'=> $indian_third_delegate
					),
			);
		}
		
        $_rs_array['standard']= array(
            'is_active' => $is_std_active,
            "p_type" => "INR" ,
			"tab_name" => "Standard" ,
            "delegate" => array(
                '1 Delegates' =>intval ($std_indian_first_delegate),
                '2 Delegates'=> $std_indian_second_delegate ,
                '3 Delegates'=> $std_indian_third_delegate
                ),
        );
        $_rs_array['onspot']= array(
            'is_active' => $is_onspot_active,
            "p_type" => "INR" ,
			"tab_name" => "On Spot" ,
//            'onspot_date' => $onspot_date,
            "delegate" => array(
                '1 Delegates' => intval ($onspot_indian_first_delegate),
                '2 Delegates'=> $onspot_indian_second_delegate ,
                '3 Delegates'=> $onspot_indian_third_delegate
                ),
        );

    }else{
        
		if($currDateTime <= $super_early_bird_datetime){//super early bird date
			$_rs_array['early_bird']= array(
				'is_active' => $is_offer_active,
				"p_type" => "USD" ,
				"tab_name" => "Super Early Bird" ,
				'onspot_date' => $early_bird_date,
				"delegate" => array(
					'1 Delegates' => intval ($nonindian_first_delegate ),
					'2 Delegates'=> $nonindian_second_delegate ,
					'3 Delegates'=> $nonindian_third_delegate
					),
			);
		}else{
			$_rs_array['early_bird']= array(
				'is_active' => $is_offer_active,
				"p_type" => "USD" ,
				"tab_name" => "Early Bird" ,
				'onspot_date' => $early_bird_date,
				"delegate" => array(
					'1 Delegates' => intval ($nonindian_first_delegate ),
					'2 Delegates'=> $nonindian_second_delegate ,
					'3 Delegates'=> $nonindian_third_delegate
					),
			);
		}
        $_rs_array['standard']= array(
            'is_active' => $is_std_active,
            "p_type" => "USD" ,
			"tab_name" => "Standard" ,
            "delegate" => array(
                '1 Delegates' => intval ($std_nonindian_first_delegate ),
                '2 Delegates'=> $std_nonindian_second_delegate ,
                '3 Delegates'=> $std_nonindian_third_delegate
                ) ,
        );
        $_rs_array['onspot']= array(
            'is_active' => $is_onspot_active,
//            'onspot_date' => $onspot_date,
            "p_type" => "USD" ,
			"tab_name" => "On Spot" ,
            "delegate" => array(
                '1 Delegates' => intval ($onspot_nonindian_first_delegate),
                '2 Delegates'=> $onspot_nonindian_second_delegate  ,
                '3 Delegates'=> $onspot_nonindian_third_delegate
                ),
        );
    }

    /* $_rs_array['early_bird']= array(
                            'is_active' => $is_offer_active,
                            'onspot_date' => $early_bird_date,
                            'indian_first_delegate' => $std_indian_first_delegate,
                            'indian_second_delegate'=>$std_indian_second_delegate ,
                            'indian_third_delegate'=>$std_indian_third_delegate ,
                            'nonindian_first_delegate'=>$std_nonindian_first_delegate ,
                            'nonindian_second_delegate'=>$std_nonindian_second_delegate ,
                            'nonindian_third_delegate'=>$std_nonindian_third_delegate
                        );
    $is_std_active = 0;
    if($is_onspot_active==0 && $is_offer_active==0)
        $is_std_active =1;

    $_rs_array['standard']= array(
                            'is_active' => $is_std_active,
                            'indian_first_delegate' => $indian_first_delegate,
                            'indian_second_delegate'=>$indian_second_delegate ,
                            'indian_third_delegate'=>$indian_third_delegate ,
                            'nonindian_first_delegate'=>$nonindian_first_delegate ,
                            'nonindian_second_delegate'=>$nonindian_second_delegate ,
                            'nonindian_third_delegate'=>$nonindian_third_delegate
                        );
    $_rs_array['onspot']= array(
                            'is_active' => $is_onspot_active,
                            'onspot_date' => $onspot_date,
                            'indian_first_delegate' => $onspot_indian_first_delegate,
                            'indian_second_delegate'=>$onspot_indian_second_delegate ,
                            'indian_third_delegate'=>$onspot_indian_third_delegate ,
                            'nonindian_first_delegate'=>$onspot_nonindian_first_delegate ,
                            'nonindian_second_delegate'=>$onspot_nonindian_second_delegate ,
                            'nonindian_first_delegate'=>$onspot_nonindian_third_delegate
                        ); */

     if($currDateTime <= $super_early_bird_datetime)
		$_rs_array['note'] = 'Super Early Bird Service Expires on '. date('d/M/Y', strtotime($super_early_bird_date));
	 elseif($is_offer_active==1)
		$_rs_array['note'] = 'Early Bird Service Expires on '. date('d/M/Y', strtotime($early_bird_date));
	 elseif($is_std_active==1)
		$_rs_array['note'] = 'Standerd Service Expires on '. date('d/M/Y', strtotime($event_date . ' - 1 days'));
	 else
		$_rs_array['note'] = 'On Spot Service Expires on '. date('d/M/Y', strtotime($event_date));
   // $_rs_array['note'] = 'Diwali Savings Offer Expires on '. date('d/M/Y H:s', strtotime($early_bird_date));
	$_rs_array['note'] .= "; GST @18% applicable for Indian Clients; 1USD=INR65 conversion for Indian clients";
	
    include ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php' );

    if($_prices_for!='')
        return $_rs_array[$_prices_for];
    else
        return $_rs_array;///alll
}

///////////////////prceedWithDelegatesDetails/////////////////
/*
$event_id=6;
$ip='182.73.37.246';
$_no_delegates=3;
//$is_indian=true;
$tab_type='early_bird';
$memid=56014;/// blank when new or not loggedin else memid of user when loggedin in
$evnts = getPaymentDetails($ip, $memid, $event_id, $_no_delegates, $tab_type);
print_R($evnts);
 */
function getPaymentDetails($ip='', $memid='', $event_id='', $_no_delegates=1, $type='early_bird', $price_type='INR'){

    $_rs_array = array();
    if($event_id=='')
        $event_id = getActiveEventId();

    $ip_countryName = ipTocntry($ip);

    $_prices = getEventPackageDetail($ip, $event_id, $_prices_for=$type);

    $subtot=0; $discount=0;
    //print_r($_prices);

    $subtot+=$_prices["delegate"][$_no_delegates . ' Delegates'];

    $_rs_array['delegates'][$_no_delegates . ' Delegates'] = strval( $_prices["delegate"][$_no_delegates . ' Delegates'] );

    if(strtoupper($ip_countryName)=='INDIA' && $price_type=='USD'){

        $_rs_array['delegates']['Service Tax ' . $GLOBALS['STtax'] .'%'] = strval ($subtot_st=(($subtot * $GLOBALS['STtax'])/100) );
        $_rs_array['delegates']['Swachh Bharat Cess ' . $GLOBALS['SBCesstax'] .'%'] = strval($subtot_st_cess=(($subtot * $GLOBALS['SBCesstax'])/100) );
        $_rs_array['delegates']['Krishi Kalyan Cess ' . $GLOBALS['KKCesstax'] .'%'] = strval($subtot_st_cess1=(($subtot * $GLOBALS['KKCesstax'])/100) );
        $_rs_array['delegates']['subtot']= strval($subtot);
        $_rs_array['delegates']['discount']= strval($discount);
        $_rs_array['delegates']['Total']= strval( $total=$subtot_st_cess+$subtot_st_cess1+$subtot_st+$subtot );
    }else{
		$_rs_array['delegates']['Service Tax ' . $GLOBALS['STtax'] .'%'] = 0;
        $_rs_array['delegates']['Swachh Bharat Cess ' . $GLOBALS['SBCesstax'] .'%'] = 0;
        $_rs_array['delegates']['Krishi Kalyan Cess ' . $GLOBALS['KKCesstax'] .'%'] = 0;
        $_rs_array['delegates']['subtot']= strval($subtot);
        $_rs_array['delegates']['discount']= strval($discount);
		$_rs_array['delegates']['Total']= strval( $total=$subtot );
    }
    /* if($is_indian){
        if($_no_delegates>=1){
            $subtot+=$_prices['indian_first_delegate'];
            $_rs_array['delegates']['First Delegate'] = $_prices['indian_first_delegate'];
        }
        if($_no_delegates>=2){
            $subtot+=$_prices['indian_second_delegate'];
            $_rs_array['delegates']['Second Delegate']= $_prices['indian_second_delegate'];
        }
        if($_no_delegates>=3){
            $subtot+=$_prices['indian_third_delegate'];
            $_rs_array['delegates']['Third Delegate'] = $_prices['indian_third_delegate'];
        }

        $_rs_array['delegates']['Service Tax ' . $GLOBALS['STtax'] .'%'] = $subtot_st=(($subtot * $GLOBALS['STtax'])/100);
        $_rs_array['delegates']['Swachh Bharat Cess ' . $GLOBALS['SBCesstax'] .'%'] = $subtot_st_cess=(($subtot * $GLOBALS['SBCesstax'])/100);

        $_rs_array['delegates']['Total']= $total=$subtot_st_cess+$subtot_st+$subtot;
    }else{
        if($_no_delegates<=1){
            $subtot+=$_prices['nonindian_first_delegate'];
            $_rs_array['delegates']['First Delegate'] = $_prices['nonindian_first_delegate'];
        }
        if($_no_delegates<=2){
            $subtot+=$_prices['nonindian_second_delegate'];
            $_rs_array['delegates']['Second Delegate'] = $_prices['nonindian_second_delegate'];
        }
        if($_no_delegates<=3){
            $subtot+=$_prices['indian_third_delegate'];
            $_rs_array['delegates']['Third Delegate'] = $_prices['nonindian_third_delegate'];
        }

        $_rs_array['delegates']['Total']= $total=$subtot;
    } */

    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
    if($memid){
        $qry = mysql_query("
					select email, name, company, phoneno, designation, id as memid
					from tbl_members
					where id=$memid
				")or die(mysql_error());
        $row=mysql_fetch_array($qry,MYSQL_ASSOC);
        $_rs_array['user_details'] = $row;
    }

    include ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php' );

    return $_rs_array;
}

///////////////////prceedWithDelegatesDetails/////////////////
//
//$event_id='6';//optional default it returns current event
//$_no_delegates=3;
//$memid=56014;
//$type='early_bird';
//$ip='';

///prceedWithDelegatesDetails($ip, $event_id, $memid,$input, $_no_delegates, $type);

//function prceedWithDelegatesDetails($ip='', $event_id='', $memid='',$input=array() , $_no_delegates=1, $type='early_bird', $visited_on="MOBAPP", $selected_ids='', $subTotal='', $discount='', $SBCess='', $serviceTax='' ){//8NFffUZzSR7EhRQ55OuJExGcIlfhX21A
function prceedWithDelegatesDetails($ip='', $event_id='', $memid='',$input=array() , $_no_delegates=1, $type='early_bird', $visited_on="MOBAPP", $selected_ids='', $subTotal=0, $discount=0, $SBCess=0, $serviceTax=0, $amtToCharge=0 ) {
    $_rs_array = array();
    if($event_id=='')
        $event_id = getActiveEventId();

    $ip_countryName = ipTocntry($ip);
//    $_prices = getEventPackageDetail($ip, $event_id, $_prices_for=$type);
//    $subtot = $_prices["delegate"][$_no_delegates . ' Delegates'];///sub total
//
//    if(strtoupper($ip_countryName)=='INDIA'){
//        $subtot_st=(($subtot * $GLOBALS['STtax'])/100);
//        $subtot_st_cess=(($subtot * $GLOBALS['SBCesstax'])/100);
//        $_rs_array['delegates']['Total']= $total=$subtot_st_cess+$subtot_st+$subtot;
//    }else{
//        $_rs_array['delegates']['Total']= $total=$subtot;
//    }

/* return $input;
echo "<br /> event_id---" .  $event_id;
echo "<br /> no_delegates---" .  $_no_delegates;
echo "<br /> type---" .  $type;
echo "<br /> visited_on---" .  $visited_on;
echo "<br /> subTotal---" .  $subTotal;
echo "<br /> discount---" .  $discount;
echo "<br /> SBCess---" .  $SBCess;
echo "<br /> serviceTax---" .  $serviceTax;
echo "<br /> amtToCharge---" .  $amtToCharge; 

    include ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php');
	die;*/
    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');

    if($memid==''){
        $email = $input['delegates'][0]['email'];
        $memid='';$verified='';
        $_is_exist= isEmailExists($id = '', $email, $memid, $verified);

        if($_is_exist==0){
           /*  $name = htmlentities( $input['delegates'][0]['name'], ENT_QUOTES);
            $email = $input['delegates'][0]['email'];
            $company = htmlentities($input['delegates'][0]['company'], ENT_QUOTES);
            $phoneno = $input['delegates'][0]['phoneno'];
            $city = $input['delegates'][0]['city'];
            $state = $input['delegates'][0]['state'];
            $country = $input['delegates'][0]['country'];
            $other_city = $input['delegates'][0]['other_city'];
//            $input['delegates'][0]['password'] = $phoneno ;



            $column.='name,company,email,username,phoneno,ipaddress,date,main_source,source_from,city,state,country,other_city,ol_be';
            $value.="'".$name."','".$company."','".$email."','".$email."','".$phoneno."','".$ip."','".$GLOBALS['currDateTime']."','Events Mobileapp','Registering ID','".$city."','".$state."','".$country."','".$other_city."','EVT MOBAPP'";*/

            
			$phoneno = $input['delegates'][0]["phoneno"];
			$isd_code = $input['delegates'][0]["country"];
			$name = htmlentities( $input['delegates'][0]['name'], ENT_QUOTES). " " .htmlentities( $input['delegates'][0]['lastname'], ENT_QUOTES);;
			//$password = htmlentities($input['delegates'][0]["password"], ENT_QUOTES);
			$password = '123456';
			$company = htmlentities($input['delegates'][0]["company"], ENT_QUOTES);
			$member_id = $memid;
			
			list($cnty, $std_code) = explode(" ", $isd_code);
			
			$country = qryToCommaSepString("
					select id
					from tbl_country
					where std_code='$std_code'");			
			
			$column.='name,password,company,email,username,phoneno,ipaddress,date,main_source,source_from,country,ol_be,primary_source';
            $value.="'".$name."','".$password."','".$company."','".$email."','".$email."','".$phoneno."','".$ip."','".$GLOBALS['currDateTime']."','Events Mobileapp','Registering ID','".$country."','EVT MOBAPP', 'CAMP24'";
			
			mysql_query("insert into  tbl_members (".$column.") values(".$value.")")or die(mysql_error(). "insert into  tbl_members (".$column.") values(".$value.")");
            $memid = mysql_insert_id();
            $rid = $memid; 
			
        } else {
            $rid = $memid;
        }
    }else{
        $qry = mysql_query("
					select email, name, company, phoneno, designation, id as memid
					from tbl_members
					where id=$memid
				")or die(mysql_error(). $qry);
        $row=mysql_fetch_array($qry,MYSQL_ASSOC);
        $memid = $row['memid'];
        $email = $row['email'];
        $phoneno = $row['phoneno'];
        $rid = $memid;
    }
//    $_reg_log_sql ="
//			insert into  tbl_sm_events_registration_logs (datetime,email,mobile,event_id)
//			values(NOW(), '$email', '$phoneno', " . $event_id . ")
//		";
//
//
//    mysql_query($_reg_log_sql) or die(mysql_error());
//    $log_id = mysql_insert_id();
//    makeEntryInTableFinalStatus($email, $event_id);
    makeEntryInTableFinalStatus($memid, $event_id);
    $_com_sql ="INSERT INTO tbl_comments(memid, `f_date`, `f_time`, `comments`, `created_by`, `comments_for`, event_id) VALUES ($rid, '".$GLOBALS['currDate']."', '".$GLOBALS['currTime']."', 'Visited on mobileapp', 'Created from event attendee page', 'EV', ".$event_id.")";
    mysql_query($_com_sql) or die(mysql_error() . $_com_sql);

    $del_ids='';

    foreach($input['delegates'] AS $_delegates){
        /* $name = htmlentities($_delegates['name'], ENT_QUOTES);
        $email = $_delegates['email'];
        $company = htmlentities($_delegates['company'], ENT_QUOTES);
        $phoneno = $_delegates['phoneno'];
        $city = $_delegates['city'];
        $state = $_delegates['state'];
        $country = $_delegates['country'];
        $other_city = $_delegates['other_city']; */
//        $_delegates['password'] = $phoneno ;
		$email = $_delegates["email"];
		$phoneno = $_delegates["phoneno"];
		$isd_code = $_delegates["country"];
		$name = htmlentities( $_delegates['name'], ENT_QUOTES). " " .htmlentities( $_delegates['lastname'], ENT_QUOTES);;
		//$password = htmlentities($_delegates["password"], ENT_QUOTES);
		$password = '123456';
		$company = htmlentities($_delegates["company"], ENT_QUOTES);
	
		
		list($cnty, $std_code) = explode(" ", $isd_code);
		
		$country = qryToCommaSepString("
				select id
				from tbl_country
				where std_code='$std_code'");	

        $memid='';$verified='';
        $_is_exist= isEmailExists($id = '', $email, $memid, $verified);

        if($_is_exist==0){
            $insrt="INSERT INTO `tbl_members`(billing_name, password, `name` ,`company`,`phoneno`, `date`, `ipaddress`,email,username,  `country`, ol_be, main_source,source_from,primary_source) VALUES ('$name', '$password', '".$name."', '".$company."', '".$phoneno."', NOW(),'".$ip."', '".$email."', '".$email."','".$country."', 'EVT MOBAPP','Events Mobileapp','new delegate', 'CAMP24' )";
            //echo  "<br>tbl_members for  delegates : ".  $insrt;
            mysql_query($insrt) or die(mysql_error().$insrt);
            $memid = mysql_insert_id();
        }
        if($del_ids)
            $del_ids.=",";
        $del_ids.=$memid;///DELGATES IDS
    }
    $newPage='';
	
    if($del_ids)
    {
        $bill_no = getSMorderNoForCCAVENUE("EVENTS");
        //$bill_no = 'EVENTS_test'; 
       // $amtToCharge = $type;
	    $round_off=0;
        if($serviceTax)$round_off = $amtToCharge - (($subTotal-$discount) + $SBCess + $serviceTax);

        $payment_gateway = null ;

        if( "india" != strtolower($ip_countryName))//paypal
            $insrt = "INSERT INTO `tbl_sm_events_payment_details` (`event_id`, `registering_id`, `pay_amt`, `pay_date`, `pymt_details`, `pym_mode`, `bill_no`, `nb_order_no`, `nb_bid`, `card_category`, `bank_name`, `comments`, `delegates_ids`,  selected_services,sub_total,discount,stax,cess,round_off) VALUES(".$event_id.",".$rid.", '$amtToCharge', '".$GLOBALS['currDateTime']."', 'PAYPAL', 'NEFT/Online', '$bill_no', '', '', '', '', '', '$del_ids', '" . $selected_ids . "', '" . $subTotal . "', '" . $discount . "', '" . $serviceTax . "', '" . $SBCess . "', '" . $round_off . "');";
        else
            $insrt = "INSERT INTO `tbl_sm_events_payment_details` (`event_id`, `registering_id`, `pay_amt`, `pay_date`, `pymt_details`, `pym_mode`, `bill_no`, `nb_order_no`, `nb_bid`, `card_category`, `bank_name`, `comments`, `delegates_ids`, selected_services,sub_total,discount,stax,cess,round_off) VALUES(".$event_id.",".$rid.", '$amtToCharge', '".$GLOBALS['currDateTime']."', 'CCAVENUE', 'NEFT/Online', '$bill_no', '', '', '', '', '', '$del_ids', '" . $selected_ids . "', '" . $subTotal . "', '" . $discount . "', '" . $serviceTax . "', '" . $SBCess . "', '" . $round_off . "');";

//        if( "INDIA" != $ip_countryName)//paypal
//            $insrt = "INSERT INTO `tbl_sm_events_payment_details` (`event_id`, `registering_id`, `pay_amt`, `pay_date`, `pymt_details`, `pym_mode`, `bill_no`, `nb_order_no`, `nb_bid`, `card_category`, `bank_name`, `comments`, `delegates_ids`, log_id) VALUES(".$event_id.",".$rid.", '$amtToCharge', '".$GLOBALS['currDateTime']."', 'PAYPAL', 'NEFT/Online', '$bill_no', '', '', '', '', '', '$del_ids', '" . $log_id . "');";
//        else
//            $insrt = "INSERT INTO `tbl_sm_events_payment_details` (`event_id`, `registering_id`, `pay_amt`, `pay_date`, `pymt_details`, `pym_mode`, `bill_no`, `nb_order_no`, `nb_bid`, `card_category`, `bank_name`, `comments`, `delegates_ids`, log_id) VALUES(".$event_id.",".$rid.", '$amtToCharge', '".$GLOBALS['currDateTime']."', 'CCAVENUE', 'NEFT/Online', '$bill_no', '', '', '', '', '', '$del_ids', '" . $log_id . "');";
////mysql_query($insrt); return mysql_error().' got it <pre>'.$insrt.'</pre>'.mysql_error();
        mysql_query($insrt) or die(mysql_error().$insrt);

        $reg_log_ids = $evnt_pay_id =mysql_insert_id();

        if( "india" != strtolower($ip_countryName)){//paypal
        //if( 1){//paypal
            include_once("/home/steelmin/public_html/sm_group_events/regProcess/paypal_country.php");

            $item_desc = getActiveEventName($event_id);

//            if(in_array(strtoupper($ip_countryName), $_paypal_country))
//            {
               // $payment_gateway = "PAYPAL" ;
//                $newPage = "https://www.steelmint.com/paypal/payment.php?reglogs_id=".$evnt_pay_id."&amt=" . intval($amtToCharge) . "&orderid=" . $bill_no. "&orderid=" . $bill_no. "&item_desc=" . $_SESSION['item_desc'];
//            }
//            else {
                //$payment_gateway = "PAYPAL" ;
//                $newPage = "https://www.steelmint.com/pay/newCheckOut.php?reglogs_id=" . $evnt_pay_id . "&amt=" . intval($amtToCharge) . "&orderid=" . $bill_no . "&uid=" . $memid . "&pymtSrc=online_reg&productPurchased=" . $_SESSION['item_desc'] . "&crency=USD&page_name=Events";
//            }
            if(in_array(strtoupper($ip_countryName), $_paypal_country) !== false)
                $newPage = "https://www.steelmint.com/paypal/payment.php?reglogs_id=".$evnt_pay_id."&amt=" . intval($amtToCharge) . "&orderid=" . $bill_no. "&orderid=" . $bill_no. "&item_desc=" . $item_desc;
            else
                $newPage = "https://www.steelmint.com/pay/newCheckOut.php?reglogs_id=".$evnt_pay_id."&amt=" . intval($amtToCharge) . "&orderid=" . $bill_no. "&uid=".$memid."&pymtSrc=online_reg&productPurchased=" . $item_desc."&crency=USD&page_name=Events";
        }else {
            $payment_gateway = "CCAVENUE" ;
			$amtToCharge = round($amtToCharge * 65);
			$amtToCharge += ($amtToCharge * 0.18);
            $newPage = "https://events.steelmintgroup.com/checkout.php?reglogs_id=".$evnt_pay_id."&amt=" . intval($amtToCharge) . "&orderid=" . $bill_no;
        }
       /*  return array(
            "page" => $newPage ,
            "bill_no" => $bill_no ,
            "log_id" => $evnt_pay_id ,
            "payment_gateway" => $payment_gateway ,
        ); */
		
		return $newPage;
    }else
        return false;
}

///////////////////onclick of "contact us for more delegates"/////////////////
//$event_id=6;
//$memid=56014;
//$input1['name']='Mohan R';
//$input1['email']='mohan@steelmint.com';
//$input1['phoneno']='9691633274';
//$input1['company']='SM';
//$input1['country']='INDIA';
//
//contactUs($event_id, $memid,$input1);

function contactUs($event_id='', $memid='',$input=array()){
    include ($_ENV['COMMON_ROOT_PATH'].'/config1.php');
    if($memid != ''){
        $qry = mysql_query("
					select tm.email, tm.name, tm.company, tm.phoneno, (select name from tbl_designation where id = tm.designation) as designation, tm.id as memid
					from tbl_members as tm
					where tm.id = $memid
				")or die(mysql_error());
        $row=mysql_fetch_array($qry,MYSQL_ASSOC);
        $input = $row;

    }
    $name = $input['name'];

    $subject = 'Steelmint Events: Mr. '.$name.' wants to register for more than 3 delegates on mobile app';
    $body = '';
    foreach($input as $key=>$val){
        if($body)$body.='<br>';
        $body.= $key. ' <strong> : '.$val.'</strong>';
    }

    include "/home/steelmin/public_html/mf.php";
    $res = sendSMMail($body, "kapil@steelmint.com", "", $subject, "", "info@steelmint.com", "SteelMint Events", "info@steelmint.com");

    include ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php' );
    return "Some one from our Team will contact you soon";
}

include ($_ENV['COMMON_ROOT_PATH'].'/desconfig.php' );

