<?php

namespace App\Http\Controllers\Action;

use DB;

/**
 * Having internel methods accessed by ActionController
 * @version	0.1
 * @author varun palekar
 * @github varunpalekar
 *
 */

class Post
{
  // User's ID from token
  private $user_id = '' ;
  private $email = ''   ; 
  public $session ;

  /**
   * Constructor of initialization of userid and email of user
   * @param string $userid
   * @param string $email
   */
  function __construct($userid='' , $email='' )
  {
    $this->user_id = $userid;
    $this->email = $email;
    $this->session = array();
  }

	/**
	 * Used to re generate activation email
	 * @param $user_email: string (user's email)
	 * @return int
	 *
	 * @return code:
	 * 	1. Success
	 * 	2. Already verified
	 * 	3. email not found in out database
	 * 	4. Unexpected error
	 */
  public function regenerateActivationMail( $user_email)
	{
		$mail_activation_token = str_random($_ENV['MAIL_TOKEN_LENGTH']) ;

		/*
		 * Get userid from email
		 */
		$user = DB::table($_ENV['USER_TABLE'])
					->select($_ENV['USER_ID'])
					->where($_ENV['EMAIL'] , '=' , $user_email )
					->first();

		if($user)
		{
			/**
			 * Already verifed
			 */
			if ($user[$_ENV['VERIFIED_COLUMN']] == 1 )
				return 2;
			//Delete old email verification token
			DB::table($_ENV['MAIL_ACTIVATION_TABLE'])
				->where($_ENV['EMAIL'], '=', $user_email )
				->delete();

			//Now create a new entry in activation table
			$result = DB::table($_ENV['MAIL_ACTIVATION_TABLE'])
						->insert([ $_ENV['MAIL_ACTIVATION_USERID_COLUMN'] => $user[$_ENV['USER_ID'] ] ,
									$_ENV['MAIL_ACTIVATION_TOKEN_COLUMN'] => $mail_activation_token ]);

			if ( $result)
			{
				$activation_link = $_ENV['EMAIL_CONFIRMATION_LINK'].'/'.$mail_activation_token ;
				//MAIL::send( $user_email, $message) ;

				$message_con = "Welcome to steelmint. To complete your registration please click the following link: ".$activation_link;

				$data = array( 'email' => $user_email , 'from' => $_ENV['MAIL_FROM'] );

				Mail::raw($message_con, function ($message) use ($data) {
					$message->from($data['from']);
					$message->subject('Steelmint activation');

					$message->to($data['email']);
				});
				return 1;
			}
			else
				return 4;
		}
		else
			return 3;

	}

  public function distinctitems($f_pdt)
  {
  	$fProducts = explode(',',$f_pdt);
  	$item_name='';
  	for($i=0; $i<count($fProducts);$i++)
  	{
  		$clause='';
  		$product_name=$fProducts[$i];
  		$clause.="product_name like '".$product_name.",%' or product_name like '%,".$product_name.",%' or product_name like '%,".$product_name."' or product_name = '".$product_name."' ";
  		$rs_pdt = DB::table('tbl_email_pref')
                        ->select('subgroup')
                        ->whereRaw($clause )
                        ->get();
  		if( count($rs_pdt) > 0)
  		{
  			foreach ($rs_pdt as $rw_pdt)
  			{
  				$item_name.=$rw_pdt['subgroup'].',';
  			}
  		}
  		
  	}
  	$item_name = substr($item_name, 0, -1);
  	return($item_name);
  }

  /**
   * Set class variable session with all values, doesn't return any values
   * @param string $item		item name 
   * @param string $at_palce	item place 
   * @param string $as_on_date	data of item
   * @param string $type		type of user
   * @param string $dPlace
   * @return number 
   * 	0: Visitor
   * 	1: Paid for product
   * 	2. free trail
   * 	3: Need to upgrade
   *   -1: Complete/Premium user
   */
  public function getTakenServicesByUser($item='', $at_palce='', $as_on_date='', $type='', $dPlace='')
  {
  	/**
  	 * If user services are not fetched from database, then we have to fetch and set in $this->session variable.
  	 */
  	$rows_to_show=0;
  	$maxCount = 0 ;
  	
  	if(!empty($this->user_id))
  	{
	    if(empty($this->session['W']['userService']))
	    	$this->getUserServices();
	    
	    $rows_to_show=0;
	    $maxCount = 0 ;
	    $as_on_date = strtotime($as_on_date);
		$_fromdate = $fromdate = $_enddate = $enddate = '' ;
		if (!empty($this->session['W']['startdate']))
		{
			$_fromdate = $this->session['W']['startdate'];
			$fromdate = strtotime($this->session['W']['startdate']);
		}
		if (!empty($this->session['W']['enddate']))
		{
			$_enddate = $this->session['W']['enddate'];
			$enddate = strtotime($this->session['W']['enddate']);
		}

	  
	    $this->session['userType'] = $this->session['W']['userType'];
	    if(($this->session['W']['userService']!='Free Trial' && (!empty($this->session['mid'])))  && ($at_palce=='inner' || $at_palce=='popup' || $at_palce=='steelnews')){
	      
	      //$first_paid_expired_log_startdate = getStartDateOfFirstLog($this->session['mid']);
	      
	      ///if( 56350 == $this->session['mid'] )$first_paid_expired_log_startdate =$this->session['W']['startdate'];
//	      if($first_paid_expired_log_startdate) {
//	        $_fromdate = $first_paid_expired_log_startdate;
//	      }
	      
	      //if($at_palce=='steelnews'){///// for news gv access for 6 months when invoice date duration is less then 6 months       
	      $d1 = new DateTime($GLOBALS['currDate']);
	      $d2 = new DateTime($_fromdate);
	      $interval = $d2->diff($d1);       
	      $_yr_diff = $interval->format('%y');
	      $_mnt_diff = ($_yr_diff*12) + $interval->format('%m');
	      
	      if( $_mnt_diff < 6)
	        $fromdate = strtotime($_fromdate.'-6 months');
	      else
	        $fromdate = strtotime($_fromdate);
	     
	    }
	    else if(($this->session['W']['userService']!='Free Trial' && (!empty($this->session['mid']))) && $at_palce=='reports')
	    {
	      $fromdate = strtotime($_fromdate . '-1 years');
	    }
	    
	    //free Trial User
	    else if($this->session['W']['userService']=='Free Trial' && "reports" != $at_palce)
	    {
	       $_assessement = $this->getAssesment($item, $type, $cond_type='', $f_cond=$dPlace);
	    
	      if($_assessement =='WEEKLY') 
	        $fromdate = strtotime(date('Y-m-d',strtotime(_getMondayOfWeek($this->session['W']['startdate']))));
	      else if($_assessement =='MONTHLY') 
	        $fromdate = strtotime(date('Y-m-01',strtotime($this->session['W']['startdate'])));
	      else
	        $fromdate = strtotime(date('Y-m-d',strtotime($this->session['W']['startdate'].'-3 days')));
	    } 
	  
	  
	    if ($as_on_date >= $fromdate && $as_on_date <= $enddate) //to free trial users show data for dates in his active tenure only
	    //if ($as_on_date >=  strtotime(date('Y-m-d',strtotime($GLOBALS['currDate'].'-30 days')))  )
	    {
	      $rows_to_show=1;
	    }else
	      $rows_to_show=0;

		$fromdate = '' ;
		if (!empty($this->session['W']['startdate']))
		{
			$fromdate = $this->session['W']['startdate'];
		}

	
	    
	    $userService = $this->session['W']['userService'];
	    
	    if($item=='coalmint' && $this->session['mid']){
	      $userService = 'ProductWise';
	    }
	      
	    //if( 56350 == $this->session['mid'] || $item=='coalmint') echo $item."-->".$userService;
	    switch($at_palce){
	      case "mobileapp": //
	        if($item=='tenders')
	        {
	          if($userService=='VAS-P')
	            $maxCount = -1;
	          elseif($userService=='Visitor')
	            $maxCount = 1;
	          else
	            $maxCount = 0;            
	        }
	        else
	        {        
	          switch($userService)
	          {         
	            case "VAS-P":
	            case "VAS-G":           
	            case "ProductWise": 
	            case "Free Trial":    
	              $maxCount = -1;           
	            break;
	            case "Upgrade":
	              $maxCount=0;  
	            break;  
	            default:
	              $maxCount=1;//visitor 
	            break;        
	          }
	        }       
	      break;
	      case "statistics":  //prices
	        switch($userService){
	          case "VAS-P":
	            $maxCount = -1; //premium user
	          break;
	          case "VAS-G":
	            $maxCount = 0; //Basic or complete service user
	          break;
	          case "ProductWise":
	            if( strpos(strtoupper($this->session['W']['product_items']), strtoupper($item))!==false)
	              $maxCount = -1; //Basic or complete service user
	            else
	              $maxCount = 0; //upgrade for product
	          break;
	          case "Free Trial":
	            /*if($rows_to_show==1)
	              $maxCount = 2; //upgrade + free trial
	            else*/
	              $maxCount=0;
	          break;
	          case "Upgrade":
	              $maxCount=0;
	          break;
	          default:    
	            $maxCount=1;//visitor
	          break;
	        }
	      break;
	      
	      default:              
	        switch($userService)
	        {
	          case "VAS-P":
	            $maxCount = -1; //premium user
	          break;
	          case "VAS-G":
	            $maxCount = -1; //Basic or complete service user
	          break;
	          case "ProductWise":
	            if( strpos(strtoupper($this->session['W']['product_items']), strtoupper($item))!==false)
	              $maxCount = -1; //Basic or complete service user
	            else
	              $maxCount = 0; //upgrade for product
	          break;
	          case "Free Trial":
	            if($rows_to_show)
	              $maxCount = 3;
	            else
	              $maxCount=0;//upgrade
	          break;
	          case "Upgrade":
	              $maxCount=0;
	          break;  
	          default:    
	            $maxCount=0;//visitor
	            if(empty($this->session['tbl'.$type.$dPlace]) || $as_on_date=='' || ((!empty($this->session['tbl'.$type.$dPlace])) && $as_on_date==$this->session['tbl'.$type.$dPlace]))
	              $maxCount = 1;
	            else
	              $maxCount = 0;
	          break;
	        } 
	      break;
	    }
  	}
  	else{
  		$maxCount = 0;
  	}
  return $maxCount;
  }

  /**
   * Function for geting user'd subscribed service
   * Set user's service in $this->session variable
   * Case 1: If user is not login ($this->user_id is empty), then user is visitor 
   * Case 2: If user is login but in trail. 
   */
  public function getUserServices()
  {
    // if user id not set, means user not login
    if ( !empty($this->user_id) )
    {
      $temp_result = DB::table('tbl_updated_reg_logs_bm as upd_rl')
                        ->select(DB::raw('count(*) as cnt, startdate, enddate, upd_rl.services as f_product, upd_rl.paid_unpaid as f_tenure, active_products as sel_prods'))
                        ->where('upd_rl.memid',   '=' , $this->user_id)
                        ->where('upd_rl.status',  '=' , 'Active')
                        ->where('upd_rl.services','<>', 'M')
                        ->groupBy(['f_product', 'f_tenure'])
                        ->get();

      if ($temp_result)
      {
        foreach ($temp_result as $result) 
        {
          $this->session[$result['f_product']]['startdate'] = $result['startdate'];
          $this->session[$result['f_product']]['enddate'] = $result['enddate'];

          $rows = implode(',', array_keys(array_flip(explode(',', $result['sel_prods']))));

			$this->session[$result['f_product']]['takenItems'] = $rows;

          if ($this->allowAccessToDownloaddataInEXCEL($this->email) == 1)
            $this->session[$result['f_product']]['XLS']='XLS';
          $rows = explode(',', $rows);
          $rows = array_diff($rows, array("steelnews","Reports","VAS-G","VAS-P","XLS"));
          $servTaken = count($rows);

          $items_results = DB::table('tbl_product_items')
                        ->select('f_product', 'web_sms', 'f_items')
                        ->where('web_sms',   '=' , 'W')
                        ->where('f_price',  '>' , 0)
                        ->where('f_product','<>', 'Reports')
                        ->orderBy('f_product' , 'asc')
                        ->get();
          
          foreach ($items_results as $items) 
          {
            if (in_array($items['f_product'] , $rows )) 
              if(!empty( $this->session[$result['f_product']]['product_items']) )
                $this->session[$result['f_product']]['product_items'].=',';
              if( empty($this->session[$result['f_product']]['product_items']) )
              	$this->session[$result['f_product']]['product_items'] = '';
              $this->session[$result['f_product']]['product_items'] .= $items['f_items'];

          }
			
          $date_diff=0;
          if( $result['f_tenure'] == 'not-paid' )
          {
            $str = strtotime($result['enddate']) - (strtotime($result['startdate']));
            $date_diff = floor($str/3600/24);         
            
            if( $date_diff == 10  )
            {
              $this->session[$result['f_product']]['userType'] = 1;
              $this->session[$result['f_product']]['userService'] = 'VAS-G';
            }
            else
            {
              $this->session[$result['f_product']]['userType'] = 2;  
              $this->session[$result['f_product']]['userService'] = 'Free Trial';  
            }
          } 
          else{
            if( strpos($this->session[$result['f_product']]['takenItems'], 'VAS-P')!==false){
              $this->session[$result['f_product']]['userService'] = 'VAS-P';
              $this->session[$result['f_product']]['userType'] = 1;
            //}else if($servTaken >= $totalItems){/// chk for complete access
            }else if(strpos($this->session[$result['f_product']]['takenItems'], 'VAS-G')!==false){/// chk for complete access
              $this->session[$result['f_product']]['userType'] = 1;
              $$this->session[$result['f_product']]['userService'] = 'VAS-G';
            }else if($servTaken > 0){/// chk for complete access
              $this->session[$result['f_product']]['userType'] = 1;
              $this->session[$result['f_product']]['userService'] = 'ProductWise';
            }else{
              $this->session[$result['f_product']]['userType'] = 3;
              $this->session[$result['f_product']]['userService'] = 'Upgrade';
            }       
          }         
        }
      }
      else
      {
        $this->session['W']['userType'] = 3;
        $this->session['W']['userService'] = 'Upgrade';
      }
        

    }
    else
      {
        $this->session['W']['userType'] = 0;
        $this->session['W']['userService'] = 'Visitor';
      }
  }

  /**
   * Function for fetching all tender data according to given conditions through database
   * @param string $conditions		: extra where condition of the sql query
   * @return string $result 		: query result of the tender
   */
  public function getTenderdata($conditions)
  {

  	$result = DB::table('tbl_tenders')
	  	->whereRaw( $conditions )
	  	->orderBy('id', 'desc')
	  	->get();

  	return $result; 
  }
  
  /**
   * Function for fetching all event data according to given conditions through database
   * @param string $conditions		: extra where condition of the sql query
   * @return string $result 		: query result of event
   */
  public function getEventdata($conditions)
  {

  	$result = DB::table('tbl_events')
	  	->whereRaw( $conditions )
	  	->orderBy('id', 'asc')
	  	->get();
  	return $result;
  }

  
  /**
   * Simple function for logging entry in log table 
   * @param string $uname
   * @param string $method
   * @param string $section
   * @param string $section_id
   * @param string $currDateTime
   * @param string $remark
   */
  public function createlog($uname='', $method='', $section='all' , $section_id='',$currDateTime='', $remark = '') 
  {
  	$insert = ['username'=> $uname , 'method' => $method , 'created_on' => $currDateTime ] ;
  	if (!empty($section))
  		$insert['section_type'] = $section;
  	if (!empty($section_id))
		$insert['section_id'] = $section_id;
  	if (!empty($remark))
  		$insert['remarks'] = $remark;
  	DB::table($_ENV['LOG_TABLE'])->insert( $insert );
  }
  
  public function getUserProfileById( )
  {
  	$result = DB::table('tbl_members')
  					->where('id', '=' , $this->user_id )
  					->first();
  	
  	$city = '';
  	$state_name = '';
  	$country = '';
  	
  	if (!empty($result['city']))
  	{
  		$res_city_arr = DB::table('tbl_state_city')
  					->where('city_id' , '=' , $result['city'] )
  					->first();
  		$city = $res_city_arr['city_name'];
  		$state_name = $res_city_arr['state_name'];
  	}
  	else 
  	{
  		$city = '';
  		$state_name = '';
  	}
  	
  	if( !empty($result['country']) )
  	{
  		$qry_country = DB::table('tbl_country')
  					->where('where' , '=' , $result['country'] )
  					->first();
  		$country = $qry_country['country'];
  	}
  	else
  	{
  		$country = '';
  	}
  	return  array(
  			'name'=>$result['name'],
  			'address'=>$result['address'],
  			'phoneno'=>$result['phoneno'],
  			'email'=>$result['email'],
  			'city'=>$city,
  			'state'=>$state_name,
  			'country'=>$country,
  			'pin_code'=>$result['pin_code']
  	);
  }

  /**
   * Check the access to download data in Excel format 
   * @param string $email
   * Return: 	0: Not access
   * 			1: Has Access
   */
  private function allowAccessToDownloaddataInEXCEL($email)
  {
  	$email = strtolower($email);
  	$curdate  = $GLOBALS['currDate'];
  	$r = DB::table('tbl_allow_historical_data')
  			->where('email' , '=' , $email)
  			->where('startdate', '<=', $GLOBALS['currDate'] )
  			->where('enddate' , '>=' , $GLOBALS['currDate'])
  			->get();
  	
  	if( count($r) > 0  )
  		return 1;
  	return 0;
  }
  
  /**
   * Return assessement duration in MONTHY, DAILY, WEEKLY, etc.
   * @param string $item
   * @param string $type
   * @param string $cond_type
   * @param string $f_cond
   * @return string
   */
	private function  getAssesment($item='', $type='', $cond_type='',$f_cond='')
	{

		if(($item == 'IRON ORE' && strpos(strtoupper($f_cond), 'CHATTISGARH')!==false) || ($item == 'TMT' and $cond_type=='Primary'))
		{
			$assessement = 'MONTHLY';
		}
		elseif(($item== 'SCRAP' && $type=='DOM') || $item== 'SPONGE_IRON' || $item== 'SPONGE_PELLET'  || ($item == 'TMT' && $type=='DOM') || ($item== 'WIRE' && $type=='DOM') || ($item== 'BILLET' && $type=='DOM') || $item== 'INGOT' || ($item== 'IRON ORE' && $type=='E_I'))
		{
			$assessement = 'DAILY';
		}else
			$assessement = 'WEEKLY';

		return $assessement;
	}

}









