<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
// use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Response;

use App\Http\Controllers\Action\Action;
use App\Http\Controllers\Auth\authentication;
use App\Http\Controllers\Auth\User;
use DOMDocument;
use DOMXPath;


use Illuminate\Http\JsonResponse;
use DateTime;
use DateTimeZone;
use CssToInlineStyles;

use DB;
use Mail;

/**
 * Class to handle /v1/action
 * Laravel controller
 * @version	0.1
 * @author varun palekar
 * @github varunpalekar
 *
 */
class ActionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    private $user_id 	= '' ;
    private $email 		= '' ; 
    private $uname	 	= ''  ;
    private $user ;
    private $request ; 
    private $action;
    
    /**
     * Main function of the action route, responsible for all return
     * @route:	/v1/action/{$method}
     * @param Request $request: Illuminate\Http\Request
     * @param unknown $method: route's subroute
	 * @return Respose: Response to the api request
     */
    public function call(Request $request, $method)
    {
    	
    	/**
    	 * Some intialiation so that every function can globally access it
    	 */
    	$this->request = $request ;
    	$GLOBALS['currDate'] = date("Y-m-d"); 
    	$GLOBALS['currDateTime'] = date("Y-m-d H:i:s") ;
        if ($request->has('token'))
        {
            $token = $request->input('token');
            $auth = new authentication();

            $user_id = $auth->authToken($token);
            if ($user_id) {
                /**
                 * Setting private variables of class to be globally access by other function 
                 * Helps in accessing common variables need to be shared
                 * @var Ambiguous $user_id
                 * @var Ambiguous $email
                 * $var Ambiguous $action
                 */
            	
            	$us = new User();
            	
            	$this->user = $us->get($user_id) ; 
                $this->user_id = $user_id ;

                $this->email = $this->user[$_ENV['EMAIL']];
                $this->uname = $this->user['username'];
                $this->action = new Action($this->user_id, $this->email );
            }
        }
        else {
        	/**
        	 * this column for guest user, which didn't login
        	 */
        	$this->action = new Action();
        }

        /**
         * Switch case to call other function based on sub routes (method type)
         * @var $method
         */
        switch ($method) {

            case 'getsubscriptionplan':
                return new Response( array ( "status#" => "1" , "data#" => $this->getsubscriptionplan() ));
                
                break;

            case 'services':
                return new Response( array ( "status#" => "1" , "data#" => $this->services() ));
                
                break;

            case 'getnotification':
            	$res = $this->getnotification();
            	if (empty($this->user_id))
            		return new Response( array ( "status#" => "1061" , "message#" => "required used login for setnotification" ), 401 );
            		
                return new Response( array ( "status#" => "1" , "data#" => $res ));
                
                break;

            case 'setnotification':
            	if (empty($this->user_id))
            		return new Response( array ( "status#" => "1061" , "message#" => "required used login for setnotification" ), 401 );
                return new Response( array ( "status#" => $this->getnotification()) );
                break ;

            case 'getcms':
                return new Response( array ( "status#" => "1" , "data#" => $this->getcms() ));
                
                break;
                
            case 'call_from_mobile_app':
            	$this->action->createlog($this->uname , 'call_from_mobile_app', 'all', '' , $GLOBALS['currDateTime'] );
            	return new Response( array( "status#" => "1" , "message" => "call from mobile to tell active after 15 days") );
            	
            	break;

            case 'resendemail':
            	//TODO
                if ( $this->$request->has('email') )
                {
                    //send verification email again
                    $result = $this->action->regenerateActivationMail($this->$request->input('email'));
                    switch($result)
                    {
                        case 1:
                            return new Response( array ( "status#" => "1" , "message#" => "Verification mail send" ) , 200 );
                            break;

                        case 2:
                            return new Response( array ( "status#" => "1027" , "message#" => "Already verified" ) , 200 );
                            break;

                        case 3:
                            return new Response( array ( "status#" => "1028" , "message#" => "email not found in out database" ) , 200 );

                            break;

                        case 4:
                            return new Response( array ( "status#" => "1029" , "message#" => "Unexpected error" ) , 200 );

                            break;
                    }

                    return new Response( array ( "status#" => "1023" , "message#" => "Error in Verification mail send" ) , 200 );

                }
                //else send error response
            	return new Response(array ( "status#" => "1023", "message#" => "Error in Verification mail send"  ));
            
            default:
            	$this->action->createlog($this->uname, $method, '' , "", $GLOBALS['currDateTime'], "invalid method name");
            	return new Response( array ( "status#" => "1060" , "message#" => "Not valid method" ) , 406 );
                break;
        }	

    }





    
	/*
	 * Get the subscription plans
	 */
    private function getsubscriptionplan()
    {
        # code...
    	$res_arr['plan'][] = array(
    			'title'=>'Standard Plan',
    			'description'=>'Access to Basic Services (News, Prices, Market Trade, Comments, Graphs).
    							Value Added Services in Application and Website',
    			'price'=>'28950',
    			'you_get'=>'you_get desc',
    			"btn" => "Buy"
    	);
    	$res_arr['plan'][] = array(
    			'title'=>'Professional Plan',
    			'description'=>'Access to Basic Services (News, Prices, Market Trade, Comments, Graphs).
    							No Access to Vale Added Service in Website.',
    			'price'=>'23950',
    			'you_get'=>'you_get desc2',
    			"btn" => "Buy"
    	);
    	$res_arr['plan'][] = array(
    			'title'=>'Mobile Application (Introductory Offer- 6 Months)',
    			'description'=>'Prices, News, Tender, Logistics, Email Alert, Reports. Free Add-on	of 6 months SMS alerts worth INR 3,000/-',
    			'price'=>'12950',
    			'you_get'=>'you_get desc2',
    			"btn" => "Buy"
    	);
    	$res_arr['plan'][] = array(
    			'title'=>'Free Trial for 14 days',
    			'description'=>'Not Interested yet, want to take free trial for 14 Days',
    			'price'=>'0',
    			'you_get'=>'you_get desc2',
    			"btn" => "Free Trial"
    	);
    		
    	$res_arr['note'] = '#Service Tax 12.36% Extra.
							Above mentioned packages are for One Email Id and one Mobile Number only. For multiple subscription (Corporate Package) speak to our marketing team
							Sharing user account details, reports or other information with other unsolicited parties is strictly prohibited.';
    		
    	$res_arr['Service'] = 'Products Covered: Iron Ore Lumps & Fines, Pellets, Coal, Ferrous Scrap, Pig Iron, Sponge Iron, MS Billet, MS Ingot, TMT, Structure, Wires, Flat Steel and Ferro Alloys
1. Basic Services: Market Trade Prices, Latest Industry News + Archive News, Expert Interviews and Comments. News Alerts - Latest News Alerts, Stock Updates, Evening Market at a Glance Mailer, Important Circulars, etc.
2. Value Added Services: Logistics, Import-Export Data, Tenders, Archive Data Graph and Previous Prices, Live Market Tracker. ';
    	
    	if (empty($this->user_id) )
    		$res_arr['user_info'] = "null";
    	else
    		$res_arr['user_info'] = $this->action->getUserProfileById() ;
    	
    	return $res_arr ;
    }

	/**
	 * Get info of free trail service, terms, contactus
	 * TODO
	 */
    private function services()
    {
        # code...
    	if( $this->request->has('type') && (!empty($this->user_id)) )
    	{
    		switch($this->request->input('type'))
    		{
    			case 'freetrail':
    				return 'SteelMint provides real-time Trade prices, News, Tender / Auction, Statistics, Logistics, Market views, Expert comments and archived information for over 20 products in the Iron & Steel industry. We help the industry - Manufacturer, Broker/Trader, Importer/Exporter, Logistics Companies, Government organisations, Banking, and other users to take informed business decisions. ';
    				break;
    			case 'terms':
    				return 'terms and privacy policy';
    				break;
    			case 'contactus':
    				return 'contactus';
    				break;
    			default:
    				return 'Welcome To SteelMint';
    				break;
    		}
    	}
    	else
    	{
    		return 'Invalid request, please try again.';
    	}
    }

	/*
	 * Get the notification only for login user 
	 * TODO
	 */
    private function getnotification()
    {
        # code...
        if(empty($this->user_id))
        	return false;
        	
    	$this->action->createlog($this->uname, 'getnotification', '' , '',$GLOBALS['currDateTime']);
    	
    	$the_query  = new \WP_Query( array(  'posts_per_page' => 20, 
    						'post_status' => 'publish', 'post_type' => 'post', 
    						'orderby' => 'post_date', 'order' => 'DESC' ) );
    	$i=0;
    	if ( $the_query->have_posts() ) 
    	{
    		while ( $the_query->have_posts() ) 
    		{
    			$the_query->the_post();
    			$date = get_the_time('Y-m-d H:i');
    			$myDateTime = new DateTime($date, new DateTimeZone('GMT'));
    			$myDateTime->setTimezone(new DateTimeZone('Asia/Kolkata'));
    			$date  =  $myDateTime->format('M d, Y H:i');
    				
    			$res_arr['notification'][$i] = array(
    					'category'=>'news',
    					'message'=> get_the_title(),
    					'time'=>$date
    			);
    				
    			$i++;
    		}
    	}
        
    }

    /*
     * TODO
     */
    private function setnotification()
    {
        # code...
    	if ( !$this->request->has('mobile_notification') )
    		abort( 1062 , "No mobile_notification data send" );
    	$result = DB::table('tbl_members')
    			->where('id', '=' , $this->user_id)
    			->update(['mobile_notification' => $this->request->input('mobile_notification') ]);
    	
    	$this->action->createlog($this->uname, 'setnotification', '' , '',$GLOBALS['currDateTime']);
    	return "1";
    			
    }

    /**
     * get cms data only.
     *
    **/
    private function getcms()
    {
        # code...
        $str = '';

        if ( !$this->request->has('type') )
        	abort(1063 , "No type param in getcms request");
		///for CoalMint
		if($this->request->has('appType') && strtoupper($this->request->input('appType')) == 'CM'){
			switch($this->request->input('type'))
			{
				case 'aboutus' :
					$str = '
						<img width="290px" src="img/steelmint_slidenew1.jpg"/><br/>
						<img width="290px" src="img/steelmint_slidenew2.jpg"/><br/>
						<img width="290px" src="img/steelmint_newslide3.jpg"/><br/> <br/>
						<p>Thanks for choosing us as your information provider. The new CoalMint App is the best way to access data, news & information on Coal markets across the world on your mobile! (And we are constantly working to improve it)</p>
						
						Stay ahead in the completion with instant notifications, live price updates and important news alerts on more than 3 Coal products.<br/>
						1. Coal News - Latest news & analysis from Coal industry<br/>
						2. Coal Prices - Live global/domestic Price Updates<br/>
						3. Tenders - Current Coal Tenders on your finger tips<br/>
						4. Logistics - Coal Vessel Data<br/><br/>
						Access everything on the move.<br/>
						Simplifying Coal Trade!<br/>
					';
					break;
				case 'terms':
					$str = '<p>Prices provided are only indicative and for reference purposes only. Such prices	may differ from plant to plant and are subjected to change depending upon the macro market even during the day</p>
							<br/>
							<p>CoalMint accepts no responsibility for and excludes all liabilities in connection to any sort of errors, inaccuracies, omissions or misleading statement that may be based on one’s own interpretation</p>';
					break;
				case 'contactus':
					$str = 'For Marketing & Registration : <strong>+91 97702 58888</strong><br/><br/>
							For Operation : <strong>+91 7044070530</strong><br/><br/>
							Email : <strong>info@coalmint.com</strong><br/><br/>';
					break;
				case 'feedback':
					if($this->request->has('name') && $this->request->has('message'))
					{
						$message_con = "<u><b>Feedback sent by user from CoalMint Mobile App:</b></u> <br><br><strong>Name</strong>: ".$this->request->input('name'). "<br><strong>Message</strong>: ";
						$message_con .= $this->request->input('message');
						
					   if ($this->request->has('tokens'))
					   {
							$token = $this->request->input('tokens');
							$auth = new authentication();
							$user_id = $auth->authToken($token);
							$message_con .= "<br /> <strong>Memid</strong>: <a href = 'https://www.steelmint.com/steeladmin/operations/tem_screenshot/html/index_new.php?id=" . $user_id ."'>" . $user_id . "</a>";						
					   } else {
							if($this->request->has('email'))
								$message_con .= "<br /> <strong>Email</strong>: " . $this->request->input('email');
							if($this->request->has('phoneno'))
								$message_con .= "<br /> <strong>Phoneno</strong>: " . $this->request->input('phoneno');
					   }		 
						
						
						file_get_contents("https://www.steelmint.com/registrationAJAX.php?app_sendFeedbackmail=Y&message_con=" . urlencode($message_con) . "&to=info@coalmint.com&sub=" . urlencode("CoalMint APP: Feedback"));

						$str = "Feedback Sent Successfully";
					}
					else
						$str = "Please enter name/message in feedback form";
					break;
				case 'enquiry':
					if($this->request->has('name') && $this->request->has('lastname') && $this->request->has('email') && $this->request->has('email')  && $this->request->has('interest') && $this->request->has('address') )
					{
						$message_con = "Name: ".$this->request->input('name') ;
						$message_con .= "<br>Lastname: ".$this->request->has('lastname') ;
						$message_con .= "<br>Lastname: ".$this->request->has('email') ;
						$message_con .= "<br>Lastname: ".$this->request->has('email') ;
						$message_con .= "<br>Lastname: ".$this->request->has('interest') ;
						$message_con .= "<br>Lastname: ".$this->request->has('address') ;

						$data = array( 'email' => $_ENV['FEEDBACK_MAIL']  , 'from' => $_ENV['MAIL_FROM'] );
						
						require_once("/home/steelmin/public_html/mf.php");
						sendSMMail($message_con, $data['email'], $to_name="", "CoalMint APP : Client Enquiry mail" );

						$str = "Contact us mail send successfully";
					}
					else
						$str = "Please send complete contactus form";

					break;
				default:
					$str = 'Welcome To CoalMint';
					break;
			}
		}else{///for SteelMint
			switch($this->request->input('type'))
			{
				case 'aboutus' :
					$str = '
						<img width="290px" src="img/steelmint_slidenew1.jpg"/><br/>
						<img width="290px" src="img/steelmint_slidenew2.jpg"/><br/>
						<img width="290px" src="img/steelmint_newslide3.jpg"/><br/> <br/>
						<p>Thanks for choosing us as your information provider. The new SteelMint App is the best way to access data, news & information on Iron & Steel markets across the world on your mobile! (And we are constantly working to improve it)</p>
						
						Stay ahead in the completion with instant notifications, live price updates and important news alerts on more than 30 Steel products.<br/>
						1. Steel News - Latest news & analysis from Iron & Steel industry<br/>
						2. Steel Prices - Live global/domestic Price Updates<br/>
						3. Tenders - Current Steel Tenders on your finger tips<br/>
						4. Events - Updates about Global Steel events<br/>
						5. Plant & Machinery - Updates from Plantbee.com<br/>
						6. Logistics - Iron ore & Coal Vessel Data<br/><br/>
						Access everything on the move.<br/>
						Simplifying Steel Trade!<br/>
					';
					break;
				case 'terms':
					$str = '<p>Prices provided are only indicative and for reference purposes only. Such prices	may differ from plant to plant and are subjected to change depending upon the macro market even during the day</p>
							<br/>
							<p>SteelMint accepts no responsibility for and excludes all liabilities in connection to any sort of errors, inaccuracies, omissions or misleading statement that may be based on one’s own interpretation</p>';
					break;
				case 'contactus':
					$str = 'For Marketing & Registration : <strong>+91 9575100530</strong><br/><br/>
							For Operation : <strong>+91 9575100430</strong><br/><br/>
							Email : <strong>info@steelmint.com</strong><br/><br/>';
					break;
				case 'feedback':
					if($this->request->has('name') && $this->request->has('message'))
					{
						$message_con = "<u><b>Feedback sent by user from mobile app:</b></u> <br><br><strong>Name</strong>: ".$this->request->input('name'). "<br><strong>Message</strong>: ";
						$message_con .= $this->request->input('message');
						
					   if ($this->request->has('tokens'))
					   {
							$token = $this->request->input('tokens');
							$auth = new authentication();
							$user_id = $auth->authToken($token);
							$message_con .= "<br /> <strong>Memid</strong>: <a href = 'https://www.steelmint.com/steeladmin/operations/tem_screenshot/html/index_new.php?id=" . $user_id ."'>" . $user_id . "</a>";						
					   } else {
							if($this->request->has('email'))
								$message_con .= "<br /> <strong>Email</strong>: " . $this->request->input('email');
							if($this->request->has('phoneno'))
								$message_con .= "<br /> <strong>Phoneno</strong>: " . $this->request->input('phoneno');
					   }		 
						
						
						file_get_contents("https://www.steelmint.com/registrationAJAX.php?app_sendFeedbackmail=Y&message_con=" . urlencode($message_con) . "&to=info@steelmint.com&sub=" . urlencode("SteelMint APP: Feedback"));

						$str = "Feedback Sent Successfully";
					}
					else
						$str = "Please enter name/message in feedback form";
					break;
				case 'enquiry':
					if($this->request->has('name') && $this->request->has('lastname') && $this->request->has('email') && $this->request->has('email')  && $this->request->has('interest') && $this->request->has('address') )
					{
						$message_con = "Name: ".$this->request->input('name') ;
						$message_con .= "<br>Lastname: ".$this->request->has('lastname') ;
						$message_con .= "<br>Lastname: ".$this->request->has('email') ;
						$message_con .= "<br>Lastname: ".$this->request->has('email') ;
						$message_con .= "<br>Lastname: ".$this->request->has('interest') ;
						$message_con .= "<br>Lastname: ".$this->request->has('address') ;

						$data = array( 'email' => $_ENV['FEEDBACK_MAIL']  , 'from' => $_ENV['MAIL_FROM'] );
						
						require_once("/home/steelmin/public_html/mf.php");
						sendSMMail($message_con, $data['email'], $to_name="", "SteelMint APP : Client Enquiry mail" );

						$str = "Contact us mail send successfully";
					}
					else
						$str = "Please send complete contactus form";

					break;
				default:
					$str = 'Welcome To SteelMint';
					break;
			}
        }
//        $this->action->createlog($this->uname , 'getcms' , '' , "", $GLOBALS['currDateTime']);
        return $str ;
    }

}
