<?php

	//header('Content-Type: application/json');
	ini_set('display_startup_errors',1);
	ini_set('display_errors',1);
	error_reporting(1);
	ini_set("log_errors", 1);
	ini_set("error_log", "php-error.log");
	date_default_timezone_set('Asia/Kolkata');
	require_once("database.php");

	class IncentivePayout
	{
		private $conn;
		public  $previousPayoutID;
		public  $currentPayoutID;
		public  $startDate;
		public  $endDate;
		
		function __Construct()
		{
			$dbconnect = new Database();
			$this->conn = $dbconnect->getConnection();
			$this->conn->beginTransaction();
		}

		function approvalPending()
		{
			try{
				$stmt  = $this->conn->prepare("SELECT * from my_payout_run where status=0");
				$stmt->execute(array($this->startDate));
				$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

				if($result)
                   return true;
				else
				{
                   return false;
				}
			  }catch(Exception $err){
				return false;
			  } 
		}


		function checkPayoutEntry()
		{
			try{

				$stmt  = $this->conn->prepare("SELECT * from my_payout_run where payout_end_date >=?");
				//$stmt2  = $this->conn->prepare("INSERT into my_payout_run(payout_run_date, payout_start_date, payout_end_date, status) VALUES(?, ?, ?, ?)");
				
				$stmt->execute(array($this->startDate));
				$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

				if($result)
                   return false;
				else
				{
                   /*$result2 = $stmt2->execute(array(date("Y-m-d H:i:s"), $this->startDate, $this->endDate, 0));
				   $this->currentPayoutID = $this->conn->lastInsertId();*/
				   return true;
				}
				

			  }catch(Exception $err){
				return false;

			  } 
		}


		function setPreviousPayoutID()
		{
			
			try{

				$stmt  = $this->conn->prepare("SELECT id from my_payout_run where status='1' order by id DESC Limit 1");
				$stmt->execute();
				$result = $stmt->fetch(PDO::FETCH_ASSOC);

				if($result)
				{
                   $this->previousPayoutID = $result['id'];
				   $this->currentPayoutID  = $this->previousPayoutID + 1;
				}
				
				else
				{
				   $this->previousPayoutID = 0;
   				   $this->currentPayoutID  =  $this->previousPayoutID + 1;
				}

				$stmt2  = $this->conn->prepare("INSERT into my_payout_run(id, payout_run_date, payout_start_date, payout_end_date, status) VALUES(?, ?, ?, ?, ?)");
				$result2 = $stmt2->execute(array( $this->currentPayoutID, date("Y-m-d H:i:s"), $this->startDate, $this->endDate, 0));

				return true;
				
		      }catch(Exception $err){
				return false;

			  } 

 		}



		function addMemberPayout()
		{

		   try{

				$stmt  = $this->conn->prepare("SELECT distinct refer_id from my_member_package where payment_status='1' AND upload_volume='1' AND deleted='0' AND date_entered <=? AND power_leg<>1");
				$stmt2 = $this->conn->prepare("SELECT sum(total_PV) as total_PV from my_member_package where payment_status='1' AND upload_volume='1' AND deleted='0' AND refer_id=?");
				$stmt3 = $this->conn->prepare("SELECT * from my_member_payout where refer_id=?");
				$stmt4 = $this->conn->prepare("SELECT sum(total_PV) as capping from (SELECT * from my_member_package where payment_status='1' AND upload_volume='1' AND deleted='0' AND refer_id=? AND date_entered<=? order by date_modified ASC limit 0,6) my_member_package");
				$stmt5 = $this->conn->prepare("INSERT INTO my_member_payout(refer_id, entered_date, total_PV, capping, approve) VALUES (?, ?, ?, ?, ?)");
				$stmt6 = $this->conn->prepare("UPDATE my_member_payout set total_PV=?, capping=? where refer_id=? AND approve='1'");

				$stmt->execute(array($this->endDate));
				$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

				foreach($result as $row){					
					$stmt2->execute(array($row['refer_id']));
					$result2 = $stmt2->fetch(PDO::FETCH_ASSOC);
					if($result2['total_PV'] >= 3000.00)
					{
						$stmt3->execute(array($row['refer_id']));
						$result3 = $stmt3->fetch(PDO::FETCH_ASSOC);

						if(!$result3)
						{
							$stmt4->execute(array($row['refer_id'], $this->endDate));
							$result4 = $stmt4->fetch(PDO::FETCH_ASSOC);
         					$stmt5->execute(array($row['refer_id'], date("Y-m-d H:i:s"), $result2['total_PV'], $result4['capping'], '1'));
						}
						else
						{
							$stmt4->execute(array($row['refer_id'], $this->endDate));
							$result4 = $stmt4->fetch(PDO::FETCH_ASSOC);
							$stmt6->execute(array($result2['total_PV'], $result4['capping'], $row['refer_id']));
						
						}

					}

				}

				return true;
					
			  }catch(Exception $err){

				 //echo $err->getMessage();
				 return false;

			  } 
		
		}


		

		function addDirectPayout()
		{
			 try{

					$stmt  = $this->conn->prepare("select * from my_member_package where payment_status='1' AND upload_volume='1' AND deleted='0' AND date_entered >=? AND date_entered<=? AND power_leg=0 AND repurchase=0");

					$stmt2  = $this->conn->prepare("select sponsor_by from my_registration where refer_id=?");

					$stmt3  = $this->conn->prepare("select * from my_direct_payout where package_id=?");

					$stmt4  = $this->conn->prepare("INSERT INTO my_direct_payout(refer_id, sponsored_id, package_id, purchase, purchase_pv, incentive, payout_start_date, payout_end_date, payout_entry_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");


					$stmt->execute(array($this->startDate, $this->endDate));
					$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

					if(!$result)
				    {
						$result = array();
						$result['status'] = '0';
						$result['message'] = "Not a single member package is bought for a given time period!";
						print $return = json_encode($result);
						exit;
					}

					foreach($result as $row){
						$stmt2->execute(array($row['refer_id']));
						$result2 = $stmt2->fetch(PDO::FETCH_ASSOC);

						$stmt3->execute(array($row['id']));
						$result3 = $stmt3->fetch(PDO::FETCH_ASSOC);

						/*echo "package id:" . $row['id']	 . "\n";
						echo "refer id:"   . $row['refer_id']	 . "\n";		
						echo "package2:"   . $result3['id'] . "\n";*/

						if(!$result3)
						{
							//$directPayRate=0.05;

							//$directPayRate=0.1;

							if($row['total_PV'] == 12500)
							{
								$emiNo =  intval(substr($row['name'],4));
								
								if($emiNo > 4)
									$directPayRate = 0.1;

								else
									$directPayRate = 0;
							}
							
							else if($row['total_PV'] == 35000)
								$directPayRate = 0.15;

							else
								$directPayRate = 0.10;

							$stmt4->execute(array($result2['sponsor_by'], $row['refer_id'], $row['id'], $row['product_price'], $row['total_PV'],  $row['total_PV'] * $directPayRate,  $this->startDate, $this->endDate,  date("Y-m-d H:i:s")));
						}

					}

					return true;
					
			  }catch(Exception $err){

				  echo $err->getMessage();

				return false;

			  } 
			
		}




	
	


    }


	
	$result = array();
	/*if(!isset($_REQUEST['startDate'] ) || $_REQUEST['startDate']  == '') {
		$validationErr = "Please mention the Start Date!";
	}else if(!isset($_REQUEST['endDate']) || $_REQUEST['endDate'] == '') {
		$validationErr = "Please mention the End Date!";
	}else if($_REQUEST['startDate'] >= $_REQUEST['endDate']){
		$validationErr = "Please mention the valid Start and End Date !";
	}*/

	

	if($validationErr != '') {

		$result = array();
		$result['status']  = '0';
		$result['message'] = $validationErr;
		print $return      = json_encode($result);
		exit;

	}


	$incentivePayout = new IncentivePayout();
	$date = str_replace('/', '-', $_REQUEST['payout_date']);

	$incentivePayout->startDate = date('Y-m-d 00:00:00', strtotime($date));
	$incentivePayout->endDate   = date('Y-m-d 23:59:59', strtotime($date));




	if($incentivePayout->approvalPending())
	{
		$result['status']  = '0';
		$result['message'] = "Payout Release Pending!";
		print $return      = json_encode($result);
		exit;
	}


	if($incentivePayout->startDate >= $incentivePayout->endDate)
	{
		$result['status']  = '0';
		$result['message'] = "Please mention the valid Start and End Date!";
		print $return      = json_encode($result);
		exit;
	}


	if(!$incentivePayout->checkPayoutEntry())
	{
		$result = array();
		$result['status']  = '0';
		$result['message'] = "Payout for a given interval is already done!";
		print $return      = json_encode($result);
		exit;
	}



    //Set Previous Payout ID
	$incentivePayout->setPreviousPayoutID();


    //$incentivePayout->previousPayoutID = 0;
	//$incentivePayout->currentPayoutID  = 1;


	if($incentivePayout->addMemberPayout())
	{

		if($incentivePayout->addDirectPayout())
		{
				$result['success'] = true;
				$result['message'] = "Incentive payout calculation process successful!";
				

			
		}

		else
		{
			$result['success'] = false;
			$result['message'] = "Direct payout calculation process failed!";

		}

	}

	else
	{
		$result['success'] = false;
		$result['message'] = "Direct payout calculation process failed!";

	}



	echo json_encode($result);



?>


   
