<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Billing extends MY_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */

    public function __construct()
    {
        parent::__construct();

		$this->load->model ( 'merchant/Merchant_model', 'Merchant_model', TRUE );

    }
	public function index()
	{
		$this->load->view('welcome_message');
	}
	public function signup()
	{
		$menu['active_nav_tab'] = '';

		$data['header'] = $this->load->view('header',$menu, TRUE);
		//$data['homepageslider'] = $this->load->view('homepageslider',NULL, TRUE);
		//$data['service_and_testimonial'] = $this->load->view('service_testimonial',NULL, TRUE);
		//$data['pricing_table'] = $this->load->view('pricing',NULL, TRUE);
		$data['footer'] = $this->load->view('footer',NULL, TRUE);
		$page_contents = $this->load->view('signup',$data,TRUE);



		/*
		$page['contents'] = preg_replace(
				array(
						'/ {2,}/',
						'/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
				),
				array(
						' ',
						''
				),
				$page_contents);
		*/

		$page['contents'] = $page_contents;

		$this->load->view('template',$page);
	}

    public function charging()
    {
		$this->load->library('session');
		$this->load->helper( 'security' );
		$this->load->model('administration/admin_user_model', 'Admin_user_model', TRUE );
		$this->load->model('Merchant_Signup_model', 'Merchant_Signup_model', TRUE );
		$this->load->model('scheduleJob/Recurring_Payment_model', 'Recurring_Payment_model', TRUE );
		$this->load->model('merchant/Merchant_model', 'Merchant_model', TRUE );
		$this->load->model('api/notification_model', 'Notification_model', true);
		$this->load->model('mailData/Mailer_model', 'Mailer_model', TRUE);
		$this->load->model ( 'administration/package_model', 'Package_model', TRUE );
		
		//print_r($_POST);
		
		//die();
		$data ['package_id'] = $this->input->post('package_id');
		$data ['subscription_type']  = $this->input->post('subscription_type');


		$data['billing_address'] = $this->input->post('address1');
		$data['merchant_address'] = $data['billing_address'];
		$data['billing_city'] = $this->input->post('city');
		$data['merchant_city'] = $data['billing_city'];
		$data['billing_country'] = $this->input->post('country');
		$data['billing_state'] = $this->input->post('state');

		$data['state_province_name'] = $data['billing_state'];
		$data['merchant_country'] = $data['billing_country'] ;

		$data ['first_name'] = $this->input->post('first_name', true );
		$data ['last_name'] = $this->input->post('last_name', true );
		$data ['email_address'] = $this->input->post('login_email', true );
		$data ['company_name'] = $this->input->post('company_name', true );
		$data ['merchant_contact_phone'] = $this->input->post ('business_phone', true );
		$data ['mobile'] = $this->input->post('mobile', true );
		$data ['card_holder_contactname'] = $this->input->post('card_holder_name', true );

		$userPassword = $this->input->post('acc_password', true );
		$data ['acc_password'] = $this->input->post('acc_password', true );
		$data ['user_password'] = dohash($userPassword, 'md5' );

		
		
		
		
		

		if ($data['billing_state']=="N/A")
			$data['billing_state'] = $this->input->post('other_state');


		$data['billing_zip_code'] = $this->input->post('zip_code');
		$data['merchant_zip_code'] = $data['billing_zip_code'];
		
		$data ['activation_code'] = dohash ( rand ( 22334, 98765 ), 'md5' );
        $data ['admin_id'] = 1; //for SUPER ADMIN ONLY


		$data ['card_type'] = $this->input->post('cctype');
		$data ['card_number'] = $this->input->post('card_number'); //4236078542999499


		if ($data ['card_type'] =='V')
			$data ['card_type']  = 'Visa';

		if ($data ['card_type'] =='M')
			$data ['card_type']  = 'Master Card';

		if ($data ['card_type'] =='A')
			$data ['card_type']  = 'American Express';

		if ($data ['card_type'] =='D')
			$data ['card_type']  = 'Discover';



		$data ['card_exp_month'] = $this->input->post('exp_month');

		$data ['card_exp_year']  = $this->input->post('exp_year');
		$data ['card_cvc_code'] = $this->input->post('cvc');
		
		/*
		echo '<pre>';
		print_r($_POST);
		echo '</pre>'; 
		*/
		
		///
		/* echo '<pre>';
		print_r($data );
		echo '</pre>'; */
		//die();
		///
		//echo 'user password:'.$userPassword.'>>'.$data ['user_password'];
		$notification = array(
								  'merchant_id' => $merchant['merchant_id'],
								  'first_name' => $data ['first_name'],
								  'last_name' => $data ['last_name'],
								  'company_name' => $data ['company_name'],
					              'hear_about_us' => '',
								  'email' => $data ['email_address'],
							      'phone' => $data ['merchant_contact_phone'],
								  'address' => $data['merchant_address'],
				                  'city' => $data['merchant_city'],
								  'state' => $data['billing_state'],
								  'zip_code' => $data['merchant_zip_code'],
								  'postal_code' => $data['merchant_zip_code'],
								  'country' => $data['billing_country'],
                                  'website' => '',
                                  'password_hash' => dohash ( $userPassword, 'sha1' ),
                                  'password_hash_md5' => $data ['user_password'],

								  'package_id' => $data ['package_id'],
				                  'subscription_type' => $data ['subscription_type']);
								  
         
		/*
        echo 'Notification Type:';
		echo '<pre>';
		print_r($notification);
		echo '</pre>'; 
		die();
		*/
		

		
		$paymentGateway = $this->Admin_user_model->getAdminGatewaySetup();

		
		/*
		echo '<pre>';
		print_r($paymentGateway);
		echo '</pre>'; 
		die('Here I am');
		*/
		/*
		 stdClass Object
			(
			    [admin_gateway_row_id] => 1
			    [payment_provider] => 
			    [paypal_api_user_name] => cartlemon_api1.gmail.com
			    [paypal_api_key] => JZC8Q4E23P68SLS9
			    [paypal_api_signature] => A--8MSCLabuvN8L.-MHjxC9uypBtAzIHrUvXq.1MTH5-cM7T5sn5KE1L
			    [credit_cards_selected] => American Express,Discover,Master Card,Visa
			    [real_time_gateway] => 3
			    [paypal_api_password] => JZC8Q4E23P68SLS9
			    [authorize_api_login_key] => 
			    [authorize_api_transaction_key] => 
			    [authorize_api_signature] => 
			)
		 */
		
		

		$data['credit_cards_selected'] = $paymentGateway->credit_cards_selected;

		$packageInfo = $this->Package_model->getPackage ( $data ['package_id'] );
		
		
		/*
		echo '<pre>';
		print_r($packageInfo);
		echo '</pre>'; 
		//die('Here I am');
		 
		 */
		

		$data['packageInfo'] = $packageInfo ;
		$data['is_trial']  = $data['packageInfo']['is_trial'] ;

		if($data['packageInfo']['is_trial'] && $data['packageInfo']['trial_amount'] > 0)
		{
			$data['price'] = $data['packageInfo']['trial_amount'];
			$data['package_name'] = $data['packageInfo']['package_name'];
		}
		else if($data['subscription_type'] == 1) // MONTHLY
		{
			$data['price'] = $data['packageInfo']['monthly_price'] + $data['packageInfo']['setup_fee'];
			$data['package_name'] = $data['packageInfo']['package_name'] . ' - Monthly';
		}
		else if($data['subscription_type'] == 2)  // YEARLY
		{
			$data['price'] = $data['packageInfo']['annual_price'] + $data['packageInfo']['setup_fee'];
			$data['package_name'] = $data['packageInfo']['package_name'] . ' - Annually';
		}

		$isCardNumberValid = checkCreditCard ( $data ['card_number'], $data ['card_type'], $error_number, $error_text );
		$isExpired = cardExpiryValid ( $data ['card_exp_month'], $data ['card_exp_year'] );

		//1209600 - 14 days
		if(($packageInfo['is_trial']))
		{
			$data ['signup_amount'] = $signupAmount = $packageInfo['trial_amount'] ;
			$data ['subscription_type'] = '0';
			$nextBillingDate = date('Y-m-d H:i:s', time() + ($data['packageInfo']['trail_duration'] * 86400));
		}
		else
		{
			if ($data ['subscription_type'] == $this->config->item('monthly_subcription'))
			{
				$data ['signup_amount'] = $signupAmount = $packageInfo ['monthly_price'] + $packageInfo['setup_fee'];


				$nextBillingDate = date('Y-m-d H:i:s', time() + ($data['packageInfo']['trail_duration'] * 86400)); // After 28 Days
			}
			else
			{
				$data ['signup_amount'] = $signupAmount = $packageInfo ['annual_price'] + $packageInfo['setup_fee'];
				$nextBillingDate = date('Y-m-d H:i:s', time() + 31536000);
			}
		}

		$data['description'] = 'Merchant Signup Fee '.$packageInfo['currency_code'].' '.$packageInfo['monthly_price'].' (Package - '. $packageInfo['package_name'].') on '.$this->config->item('project_name');

		//echo 'Billing Description:'.$data ['description'].'<br/>';


		$this->load->model ('paymentModel/Payment_model', 'Payment_model', TRUE );
		$merchantData = $data;

		$merchantData['billing_address'] = $data['billing_address'];
		$merchantData['billing_city'] = $data['billing_city'];
		$merchantData['billing_country'] = $data['billing_country'];
		$merchantData['billing_state'] = $data['billing_state'];
		$merchantData['billing_zip_code'] = $data['billing_zip_code'];
		
		$merchantData['invoice_id'] = 'TASKGUM-'.date('Y-M-D-His');
		
		$paymentDetails = $this->Payment_model->chargeForMerchantSignUp($merchantData, $paymentGateway, 1);
		
		/*
		 Array
		(
		    [reason_code] => 
		    [response_code] => 
		    [response_reason_code] => 
		    [payment_gateway] => 3
		    [amount] => 1
		    [curl_error_message] => 
		    [version] => 52.0
		    [auth_code] => 
		    [transaction_id] => 8R723557VY996224L
		    [transaction_type] => 
		    [success] => 1
		    [ack] => Success
		    [error_text] => 
		    [description] => Merchant Signup Fee USD 1.00 (Package - Friends & Family) on TASKGUM
		)
		 */
		/*
		echo '<pre>';
		print_r($paymentDetails);
		echo '</pre>';
		
		die('here');
		*/
		/*
		$paymentDetails  = array();
		$paymentDetails ['reason_code'] = '';
		$paymentDetails ['response_code'] = '';
		$paymentDetails ['response_reason_code'] = '';
		$paymentDetails ['payment_gateway'] = 3;
		$paymentDetails ['amount'] = 1;
		$paymentDetails ['curl_error_message'] = '';
		$paymentDetails ['version'] = 52.0;
		$paymentDetails ['auth_code'] = '';
		
		
		$paymentDetails ['success'] = true;
		$paymentDetails ['transaction_id'] = '8R723557VY996224L';
		$paymentDetails ['transaction_type'] = '';
		$paymentDetails ['ack'] = 'failed';//Success
		$paymentDetails ['error_text'] = '';
		$paymentDetails ['description'] = 'Merchant Signup Fee USD 1.00 (Package - Friends & Family) on TASKGUM';
		*/
		/* echo '<pre>';
		print_r($merchantData);
		echo '</pre>';
		
		echo '<pre>';
		print_r($paymentDetails);
		echo '</pre>'; */
		//die();
		
		
		

		if ($paymentDetails['ack'] != 'Success')
		{
			/*
			$this->Merchant_model->addBlackListIP();
			if(count($this->Merchant_model->getBlackListByIP($_SERVER['REMOTE_ADDR'])) >= 2)
			{
				die('BLACKLIST;'.$paymentDetails ['error_text']);
			}
			*/
			$debugText = 'Merchant Sign Up Failed.<br />
                              Reason:' . $paymentDetails ['error_text'];
			
			
			$to      = 'support@taskgum.com';
			$subject = 'Failed Signup for TaskGum - '.$data ['email_address'];
			$message = '<table border="0" cellpadding="0" cellspacing="0" width="100%" id="templateBody">
                        	 <tr>
                                <td valign="top" class="bodyContent" colspan="3">
                                    Dear Agent,
                                    <br/><br/>
                                    <strong>One merchant could not  Signup with '.$data ['first_name'].' '.$data ['last_name'].' </strong>
									<br/>
									<strong>Error Reason: '.$paymentDetails ['error_text'].' </strong>
                                    		
                                </td>
                            </tr>
                        </table';
			
			//die($message);
			
			$headers  = 'MIME-Version: 1.0' . "\r\n";
			//$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
			$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
			$headers .= 'To: ZERIN <a.r.zerin@gmail.com>' . "\r\n";
			$headers .= 'From: Support <no-reply@taskgum.com>' . "\r\n";
			
			@mail($to, $subject, $message, $headers);
			
			$this->failed();die();
			
			//log_email($debugText);

			exception($paymentDetails ['error_text']);
			die('ERROR;'.'ERROR;'.$paymentDetails ['error_text']);

			$data ['packageInfo'] = $packageInfo;

			//$this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/template_signup', $data );
			return;
		}
		else
		{

			
			$data['active_status'] = 1;
			$data ['renew_date'] = $data ['last_transaction_date']
				= $data ['last_due_date']
				= $paymentDetails ['date_of_transaction']
				= getCurrentDateTimeForDB();
			$data['next_charge_date'] = $nextBillingDate;
			//echo 'Next Charge Date:'.$data['next_charge_date'] ;

		}
		
		
		$data ['activation_code'] = dohash ( rand ( 22334, 98765 ), 'md5' );
		$data ['admin_id'] = 1; //for ZERIN only
		$data ['activation_date'] = $data ['last_transaction_date'];
		$data ['signup_amount'] = $signupAmount - $packageInfo['setup_fee'];
		

		
		$to      = $data ['email_address'];
		$subject = 'Welcome to TaskGum.com - Your Access Login';
		$data['email_content'] = $email_content = $this->load->view('email/newsignup', $data, TRUE);
		$message = $email_content;
		
		
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		//$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
		//$headers .= 'To: '.$agents_info->firstname.' '.$agents_info->lastname.' <' .$agents_info->email.'>' . "\r\n";
		$headers .= 'From: Taskgum <no-reply@taskgum.com>' . "\r\n";
		
		@mail($to, $subject, $message, $headers);
		
/* 		echo '<pre>';
		print_r($data);
		echo '</pre>'; */
		//die();

		$data ['merchant_row_id'] = $paymentDetails ['merchant_row_id'] = $this->Merchant_Signup_model->saveMerchant($data);
		
		//echo 'MERCHANT ROW ID:'.$data ['merchant_row_id'].'<BR/>'; //5598
		
		//die('here');
		//Saving Payment Details
		

		$this->Recurring_Payment_model->savePaymentDetails ( $paymentDetails );

		
		$this->Merchant_model->updateProfile(array('merchant_row_id' => $data ['merchant_row_id'],
			'enc_merchant_row_id' => md5($data ['merchant_row_id'])));

		/****************************************************************/
		/* Setup Shipping Starts */
		//$this->load->model('shipping/Shipping_model', 'shipping_model', TRUE);
		//$this->shipping_model->setShippingInfoMerchant($data ['merchant_row_id']);
		/* Setup Shipping Ends */
		/****************************************************************/


		//$this->load->model('Mail_Manager_model', 'Mail_Manager_model', TRUE);
		//$this->Mail_Manager_model->copyMailsForNewMerchant($data['merchant_row_id']);


		/**
		 * Track merchant package information
		 */
		$this->Merchant_model->saveMerchantPackage($data);

		

		// Adding default product for Free Form Charge
		//$this->load->model('products/Product_model', 'Product_model', true);
		//$this->Product_model->saveDefaultProduct($data['merchant_row_id']);


		/*
		echo '<pre>';
		print_r($paymentDetails);
		echo '</pre>';
		*/
		
		ob_start();
		echo '<pre>';
		print_r($paymentDetails);
		echo '</pre>';

		$logdata = ob_get_contents();
		ob_end_clean();

		$fp = fopen( 'logs/taskgum_'.date('d-m-Y H:i').'_signup.txt', 'w+' );
		fwrite( $fp,  $logdata);
		fclose( $fp );

		//die();
		
        $merchant = $this->Merchant_model->getMerchant($data['merchant_row_id']);

        $notification = array(
        				'merchant_id' => $merchant['merchant_id'],
                                  'first_name' => $merchant['first_name'],
                                  'last_name' => $merchant['last_name'],
                                  'company_name' => $merchant['company_name'],
                                  'hear_about_us' => $merchant['hear_about_us'],
                                  'email' => $merchant['email_address'],
                                  'phone' => $merchant['merchant_contact_phone'],
                                  'address' => $merchant['merchant_address'],
                                  'city' => $merchant['merchant_city'],
                                  'state' => $merchant['state_province_name'],
                                  'zip_code' => $merchant['merchant_zip_code'],
                                  'postal_code' => $merchant['merchant_postal_code'],
                                  'country' => $merchant['merchant_country'],
                                  'website' => $merchant['website_url'],
                                  'password_hash' => dohash ( $userPassword, 'sha1' ),
                                  'password_hash_md5' => $data ['user_password'],
            					  'pro_category_id' => 0, //$memberShipProCategory
                                  'lite_category_id' => 0, //$memberShipLiteCategory,
                                  'project_category_id' => 0,
                                  'package_id' => $merchant['package_id'],
                                  'subscription_type' => $merchant['subscription_type'],
                                  'white_label_id' => $merchant['white_label_id']
        		
        );

        
		/*
		if($enableMembersPro)
		{
			$this->Notification_model->sendMerchantSignUpNotificationToMembersPro($notification);
		}
		if($enableAdvertising)
		{
			$this->Notification_model->sendMerchantSignUpNotificationToAdvertising($notification);
		}

		if($enableCRM)
		{
			$this->Notification_model->sendMerchantSignUpNotificationToCRM($notification);
		}
		if($enableProject)
            {
                $this->Notification_model->sendStaffProfileNotification($data['merchant_row_id']);
            } 
		*/

		//$this->Notification_model->sendMerchantSignUpNotificationToProject($data);
		
        
		$this->Notification_model->sendStaffProfileNotification($data['merchant_row_id']);
		//die('here');
		//echo 'after Notification_model';die();

/* 		echo 'NOTIFICATION SENT:<pre>';
		print_r($notification);
		echo '</pre>';
		
		
		echo 'DATA::<pre>';
		print_r($data);
		echo '</pre>';
		

		die('END');
 */

		if($paymentDetails){
			
			
			$to      = 'support@taskgum.com';
			$subject = 'New Signup for TaskGum - '.$data['merchant_row_id'];
			$message = '<table border="0" cellpadding="0" cellspacing="0" width="100%" id="templateBody">
                        	 <tr>
                                <td valign="top" class="bodyContent" colspan="3">
                                    Dear Agent,
                                    <br/><br/>
                                    <strong>You have got a Signup with '.$merchant['first_name'].' </strong>
                                    		
                                </td>
                            </tr>
                        </table';    
			
			//die($message);
			
			$headers  = 'MIME-Version: 1.0' . "\r\n";
			//$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
			$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
			$headers .= 'To: ZERIN <a.r.zerin@gmail.com>' . "\r\n";
			$headers .= 'From: Support <no-reply@taskgum.com>' . "\r\n";
			
			@mail($to, $subject, $message, $headers);
			

			$this->load->library('session');
			$paymentinformation = array();
			$paymentinformation['p_w'] = $userPassword;
			$paymentinformation['m_i'] = $data['merchant_row_id'];
			$paymentinformation['m_r_i'] = $paymentDetails['merchant_row_id'];
			$paymentinformation['login_email'] = $data ['email_address'];
			$paymentinformation['trn_id'] = $paymentDetails['transaction_id'];

			$this->successful($paymentinformation);
			die();
			unset($_SESSION['exception']);
			redirect('/successful','refresh');
		}
		else
		{
			//$this->Mailer_model->sendActivationEmail ( $data );
			unset($_SESSION['exception']);
			redirect('/failed', 'refresh');
			die('OK;'.'ACTIVATION;'.'ACTIVATION');

		}
		//echo 'MERCHANT ID:'.$data ['merchant_row_id'] ;
		//die('here I am');

		die('We will charge Now');
    }


    public function successful($paymentinformation='')
	{

		//print_r($paymentinformation);
		//die('here');
		$menu['active_nav_tab'] = '';

		$data['login_email'] = $paymentinformation['login_email'];
		$data['acc_password'] = $paymentinformation['p_w'];
		$data['merchant_id'] = $paymentinformation['m_i'];
		$data['merchant_row_id'] = $paymentinformation['m_r_i'];
		$data['transaction_id'] = $paymentinformation['trn_id'];

		/*
		 			$_SESSION['p_w'] = $userPassword; // password
			$_SESSION['m_i'] = $data['merchant_row_id'];
			$_SESSION['m_r_i'] = $paymentDetails['merchant_row_id'];
			$_SESSION['login_email'] = $data ['email_address'];
			$_SESSION['trn_id'] = $paymentDetails['transaction_id'];

		 */

		$data['header'] = $this->load->view('header',$menu, TRUE);
		$data['footer'] = $this->load->view('footer',NULL, TRUE);
		$data['pageheadertitle'] = 'CONGRATULATION !!!!';
		$page_contents = $this->load->view('successful',$data,TRUE);


		$page['contents'] = preg_replace(
			array(
				'/ {2,}/',
				'/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
			),
			array(
				' ',
				''
			),
			$page_contents);

		//$page['contents'] = $page_contents;

		$content = $this->load->view('template',$page, TRUE);
		die($content);
	}

    public function failed()
    {
    	
        $menu['active_nav_tab'] = '';
        $data = array();
        $data['header'] = $this->load->view('header',$menu, TRUE);
        $data['footer'] = $this->load->view('footer',NULL, TRUE);
        $data['pageheadertitle'] = 'OOPS Something Went Wrong !!!!';
        $page_contents = $this->load->view('failed',$data,TRUE);
        
        die($page_contents);



        $page['contents'] = preg_replace(
            array(
                '/ {2,}/',
                '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
            ),
            array(
                ' ',
                ''
            ),
            $page_contents);

        //$page['contents'] = $page_contents;

        $content = $this->load->view('template',$page);
        die($content);
    }
}
