<?php

 ini_set('display_startup_errors',1);
 ini_set('display_errors',1);
 error_reporting(-1);

 set_time_limit ( 300 );

 ob_start();


if(!isset($_REQUEST['start']) || $_REQUEST['start'] == '') {
	$validationErr = "Please enter start position!";
} else if(!isset($_REQUEST['length']) || $_REQUEST['length'] == '') {
	$validationErr = "Please enter lenght of data!";
} 

require_once('../database.php');

class User{
    //global $sugar_config;

	public $username;
	public $password;
	public $conn;
	public $db;

		
	function __construct() {
		global $sugar_config;

		$this->username 	= $sugar_config['soap_login']['username'];
		$this->password 	= $sugar_config['soap_login']['password'];
		$this->uri 			= $sugar_config['soap_login']['uri'];
		$this->soap_url 	= $sugar_config['soap_login']['soap_url'];

		$host_name = $sugar_config['dbconfig']['db_host_name'];
		$user_name = $sugar_config['dbconfig']['db_user_name'];
		$password  = $sugar_config['dbconfig']['db_password'];
		$db_name   = $sugar_config['dbconfig']['db_name'];
		$this->tableName	= 'bb_week3_mst';
		//print "<br>payoutWeek: ".$this->payoutWeek 	= $sugar_config['soap_login']['payout_week'];

		$this->pdo = new PDO("mysql:host=$host_name;dbname=$db_name", $user_name, $password);
		// set the PDO error mode to exception
		$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		$this->pdo->beginTransaction();
		
		
		if(!$this->pdo) {
			$result = array();
			$result['status'] = '0';
			$result['message'] = "APP temporarily Unavailable!";
			print $return = json_encode($result);
			exit;
		}
		
       $options = array(
        "location" => $this->soap_url,
        "uri" => $this->uri,
        "trace" => 1
        );

		$this->sugarClient = new soapclient(NULL, $options);
		$response = $this->sugarClient->login(array('user_name' => $this->username, 'password' => md5($this->password), 'version' => '1.1'), 'myApp');

		if(!isset($response->id) || $response->id == '') {
			$result = array();
			$result['status'] = '0';
			$result['message'] = "APP temporarily Unavailable!";
			print $return = json_encode($result);
			exit;
		}

		return $this->sessionId = $response->id;
    }

	public function user_list() {

		$user_list = array();

		$sqlEarnBalance = "SELECT * FROM bb_registration WHERE 1 ";

		if(!empty($_REQUEST['user_id']))
			$sqlEarnBalance .= " AND refer_id = ".$_REQUEST['user_id'];

		if(!empty($_REQUEST['searchStr'])){

			//$sqlEarnBalance .= " AND (name LIKE '%".$_REQUEST['searchStr']."%' OR refer_id LIKE '%".$_REQUEST['searchStr']."%' OR sponsor_by LIKE '%".$_REQUEST['searchStr']."%' OR sponsor_id LIKE '%".$_REQUEST['searchStr']."%' ) "; 

			$sqlEarnBalance .= " AND (CONCAT(TRIM(`name`) ,' ', TRIM(`last_name`)) LIKE '%".$_REQUEST['searchStr']."%' OR refer_id LIKE '%".$_REQUEST['searchStr']."%' ) "; 
	
		}


		if(!empty($_REQUEST['orderColName']) && !empty($_REQUEST['orderDir']))
		$sqlEarnBalance .= " ORDER BY TRIM(".$_REQUEST['orderColName'].") ".$_REQUEST['orderDir']." ";


		if(!empty($_REQUEST['start']) && !empty($_REQUEST['length']))

			$sqlEarnBalance .= " Limit ".$_REQUEST['start'].",".$_REQUEST['length'];

		else if(!empty($_REQUEST['length']))
			$sqlEarnBalance .= " Limit ".$_REQUEST['length'];

		// else 
		// 	$sqlEarnBalance .= " Limit 10";

		//echo $user_list = $sqlEarnBalance;exit;
		$ebal = $this->pdo->prepare($sqlEarnBalance);

		$ebal->execute();

		if(isset($_REQUEST['totalRowCount']) && $_REQUEST['totalRowCount']=="yes"){

			$user_list = $ebal->rowCount();
		}
		else{
			while($earnBalancvvvve = $ebal->fetch(PDO::FETCH_ASSOC)) {

				//print_r($earnBalance['refer_id']);exit;

				$result = $this->get_member_package($earnBalance['refer_id']);

				$earnBalance = array_merge($earnBalance,$result);
				array_push($user_list, $earnBalance);
			}	
		}
				

		return  $user_list;
	}

	public function getMemberPackage($refer_id){

		$sqlQuery = "SELECT  sum(totalPV),  date_entered  FROM bb_member_package WHERE refer_id = ".$refer_id." order by date_entered";

		$stmt = $this->pdo->prepare($sqlQuery);

		$stmt->execute();

		$i = 1;
		$data = array();
		while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {

				$data['totalPV'.$i] = empty($result['totalPV']) ? 0 : $result['totalPV']; 
				$data['purchaseDate'.$i] = empty($result['date_entered']) ? '---' : date('d-m-Y H:i:s',strtotime($result['date_entered'])); 
				$i++;
				
			}	
		//print_r($data );exit;
		return $data;

	}
}

$conn 	= new member_sign_up();

try {

	$userList = $conn->user_list();

	$result['status'] = true;

	$result['userlist'] = $userList;
	
	$conn->pdo->commit();

	echo json_encode($result);
}
catch (Exception $e ){

	$conn->pdo->rollback();
v
	$result['status'] = false;
	$result['userlist'] = [];
	$result['message'] = "Error While Calling User List API";

	$result['error'] = $e->getMessage();

	echo json_encode($result);
}



?>
