<?php
/*
Documentation: https://goo.gl/w3kKoH
*/
require_once dirname( __FILE__ ).'/base.addon.php';

if( !class_exists( 'CPABC_iDealTargetPay' ) )
{
    class CPABC_iDealTargetPay extends CPABC_BaseAddon
    {
       
        /************* ADDON SYSTEM - ATTRIBUTES AND METHODS *************/
		protected $addonID = "addon-idealtargetpay-20160616";
		protected $name = "iDeal TargetPay";
		protected $description;
		
		public function get_addon_form_settings( $form_id )
		{
			global $wpdb;			
			// Insertion in database
			if( 
				isset( $_REQUEST[ 'CPABC_iDealTargetPay_id' ] )
			)
			{
			    $wpdb->delete( $wpdb->prefix.$this->form_table, array( 'formid' => $form_id ), array( '%d' ) );
				$wpdb->insert( 	
								$wpdb->prefix.$this->form_table, 
								array( 
									'formid' => $form_id,
									'idealtargetpay_api_username'	 => $_REQUEST["idealtargetpay_api_username"],																		
									'mode'	 => $_REQUEST["mode"],									
									'enabled'	 => $_REQUEST["targetpay_enabled"]
								), 
								array( '%d', '%s', '%s') 
							);					
			}		

			
			$rows = $wpdb->get_results( 
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $form_id ) 
					);
			if (!count($rows))
			{
			    $row["idealtargetpay_api_username"] = "";
			    $row["mode"] = "";			    
			    $row["enabled"] = "0";
			} else {
			    $row["idealtargetpay_api_username"] = $rows[0]->idealtargetpay_api_username;
			    $row["mode"] = $rows[0]->mode;
			    $row["enabled"] = $rows[0]->enabled;
			}   
			
			?>
			<div id="metabox_basic_settings" class="postbox" >			
				<h3 class='hndle' style="padding:5px;"><span><?php print $this->name; ?></span></h3>
				<div class="inside"> 
				   <input type="hidden" name="CPABC_iDealTargetPay_id" value="1" />
                   <table class="form-table">
                    <tr valign="top">        
                    <th scope="row"><?php _e('Enable iDeal-TargetPay? (if enabled PayPal Standard is disabled)', 'cpabc'); ?></th>
                    <td><select name="targetpay_enabled">
                         <option value="0" <?php if (!$row["enabled"]) echo 'selected'; ?>><?php _e('No', 'cpabc'); ?></option>
                         <option value="1" <?php if ($row["enabled"]) echo 'selected'; ?>><?php _e('Yes', 'cpabc'); ?></option>
                         </select> 
                    </td>
                    </tr>   
                    <tr valign="top">        
                    <th scope="row"><?php _e('RTLO Subaccount ID', 'cpabc'); ?></th>
                    <td><input type="text" name="idealtargetpay_api_username" size="20" value="<?php echo esc_attr($row["idealtargetpay_api_username"]); ?>" /></td>
                    </tr>  
                    <tr valign="top">        
                    <th scope="row"><?php _e('Payments Mode', 'cpabc'); ?></th>
                    <td><select name="mode">
                         <option value="1" <?php if ($row["mode"]) echo 'selected'; ?>><?php _e('Test Mode', 'cpabc'); ?></option>
                         <option value="0" <?php if (!$row["mode"]) echo 'selected'; ?>><?php _e('Production - Real Payments', 'cpabc'); ?></option>
                         </select> 
                    </td>
                    </tr>    
                   </table>  
				</div>
			</div>	
			<?php
		} // end get_addon_form_settings
		

		
		/************************ ADDON CODE *****************************/
		
        /************************ ATTRIBUTES *****************************/    
        
        private $form_table = 'cpabc_dex_form_idealtargetpay';        
        private $_inserted = false;
        
        /************************ CONSTRUCT *****************************/
		
        function __construct()
        {
			$this->description = __("The add-on adds support for iDeal via TargetPay payments", 'cpabc' );
            // Check if the plugin is active
			if( !$this->addon_is_active() ) return;
			
			add_action( 'cpabc_process_data', array( &$this, 'pp_idealtargetpay' ), 1, 2 );						

			add_action( 'init', array( &$this, 'pp_idealtargetpay_update_status' ), 10, 1 );
			add_action( 'init', array( &$this, 'pp_idealtargetpay_return_page' ), 10, 1 );
			
			add_filter( 'cpabc_the_form', array( &$this, 'insert_banks'), 99, 2 );
			
			add_filter( 'cpabc_get_option', array( &$this, 'get_option' ), 10, 3 );					
			
			$this->update_database();
            
			
        } // End __construct
        

        
        /************************ PRIVATE METHODS *****************************/
        
		/**
         * Create the database tables
         */
        protected function update_database()
		{
			global $wpdb;			
			$sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix.$this->form_table." (
					id mediumint(9) NOT NULL AUTO_INCREMENT,
					formid INT NOT NULL,
					enabled varchar(10) DEFAULT '0' NOT NULL ,
					idealtargetpay_api_username varchar(255) DEFAULT '' NOT NULL ,					
					mode varchar(10) DEFAULT '' NOT NULL ,					
					UNIQUE KEY id (id)
				);";
				//  idealtargetpay_api_signature varchar(255) DEFAULT '' NOT NULL ,
				//	currency varchar(255) DEFAULT '' NOT NULL ,
				
			$wpdb->query($sql);
		} // end update_database		        	
        
        
		/************************ PUBLIC METHODS  *****************************/                               

               
		/**
         * Inserts banks
         */ 
        public function	insert_banks( $form_code, $id )
		{
            global $wpdb;
            
			$rows = $wpdb->get_results( 
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $id ) 
					);
			if (!$rows[0]->enabled)		
			    return $form_code;			   			
			
			$url="https://www.targetpay.com/ideal/getissuers?ver=3&format=html";
            $strResponse = $this->httpGetRequest($url);
			//$strResponse = '<option selected value="">Kies uw bank...</option><option value="ABNANL2A">ABN AMRO</option><option value="ASNBNL21">ASN Bank</option><option value="BUNQNL2A">bunq</option><option value="INGBNL2A">ING</option><option value="KNABNL2H">Knab</option><option value="RABONL2U">Rabobank</option><option value="RBRBNL21">RegioBank</option><option value="SNSBNL2A">SNS Bank</option><option value="TRIONL2U">Triodos Bank</option><option value="FVLBNL22">van Lanschot</option>';
			$code = "<div class=\"dfield\"><select name=\"bank\" required>".$strResponse."</select></div>";
			
			return preg_replace( '/<!-- rcadon -->/i', '<!-- rcadon -->'.$code, $form_code );	
		} // End insert_recaptcha               
               
		/**
         * process payment
         */		
		public function pp_idealtargetpay($params)
		{               
            global $wpdb;
			            
			// documentation: https://goo.gl/w3kKoH                     
           
            $rows = $wpdb->get_results( 
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $params["formid"] ) 
					);
			if (!$rows[0]->enabled)		
			    return;
			    
            $key = $rows[0]->idealtargetpay_api_username;            
            $bank = $_POST["bank"]; "INGBNL2A"; 
            try 
            {

                $test=$rows[0]->mode; // Set to 1 for testing as described in paragraph 1.3
                $url= "https://www.targetpay.com/ideal/start?".
                "rtlo=".$key.
                "&bank=".$bank.
                "&description=".urlencode(cpabc_get_option('paypal_product_name', CPABC_APPOINTMENTS_DEFAULT_PRODUCT_NAME)).
                "&amount=".round($params["final_price"]*100,0). 
                "&returnurl=".urlencode(cpabc_appointment_get_FULL_site_url().'/?cp_idealtargetpay_ipnreturn=1&itemnumber='.$params[ 'itemnumber' ].'&d='.$params["formid"]).
                "&reporturl=".urlencode(cpabc_appointment_get_FULL_site_url().'/?cp_idealtargetpay_ipncheck=1&itemnumber='.$params[ 'itemnumber' ].'&d='.$params["formid"]).
                "&test=".$test.
                "&ver=3";
                $strResponse = $this->httpGetRequest($url);
                $aResponse = explode('|', $strResponse );
                # Bad response
                if ( !isset ( $aResponse[1] ) ) die('Error' . $aResponse[0] );
                $responsetype = explode ( ' ', $aResponse[0] );
                $trxid = $responsetype[1];
                // Hier kunt u het transactie id aan uw order toevoegen.
                if( $responsetype[0] == "000000" ) header("Location: " . $aResponse[1] );
                else die($aResponse[0]);                
                
            } catch (Exception $e) {
                echo "Error: ".$e->getMessage();
            }
            exit;   
		} // end pp_idealtargetpay               
		

		/**
		 * utility connection function
		 */		
		private function httpGetRequest($url)
		{
		    $ch = curl_init( $url );
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1) ;
            $strResponse = curl_exec($ch);
            curl_close($ch);
            if ( $strResponse === false )
            die("Could not fetch response " . $url );
            return $strResponse;
        }
		
		/**
		 * log
		 */
		private function _log($adarray = array())
		{
			$h = fopen( __DIR__.'/logs.txt', 'a' );
			$log = "";
			foreach( $_REQUEST as $KEY => $VAL )
			{
				$log .= $KEY.": ".$VAL."\n";
			}
			foreach( $adarray as $KEY => $VAL )
			{
				$log .= $KEY.": ".$VAL."\n";
			}
			$log .= "================================================\n";
			fwrite( $h, $log );
			fclose( $h );
		}
		
		public function pp_idealtargetpay_return_page( )
		{
            global $wpdb;      
            if ( !isset( $_GET['cp_idealtargetpay_ipnreturn'] ) || $_GET['cp_idealtargetpay_ipnreturn'] != '1' || !isset( $_GET["itemnumber"] ) )
                return;
                
            $itemnumber = intval(@$_GET['itemnumber'] );    
            $formid = intval(@$_GET['d'] );  
                       			            
            $rowstargetpay = $wpdb->get_results( 
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $formid ) 
					);
					
			$once=1;
            $url= "https://www.targetpay.com/ideal/check?".
            "rtlo=".$rowstargetpay[0]->idealtargetpay_api_username.
            "&trxid=".$_GET['trxid'].
            "&once=".$once;
            $result = $this->httpGetRequest($url);		
					           			            
            $myrows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM ".CPABC_APPOINTMENTS_CALENDARS_TABLE_NAME." WHERE reference=%d", $itemnumber ) );
                                    
			if ($result != '000000 OK')
			{
				$location = cpabc_get_option('url_cancel', CPABC_APPOINTMENTS_DEFAULT_OK_URL);
	            header( 'Location: '.$location );				
			}
			else 
			{
                $location = cpabc_get_option('url_ok', CPABC_APPOINTMENTS_DEFAULT_OK_URL);
                header( 'Location: '.$location);				    
			}
	
            exit();              
              
		}
		
		
		public function pp_idealtargetpay_update_status( )
		{
            global $wpdb;      
            if ( !isset( $_GET['cp_idealtargetpay_ipncheck'] ) || $_GET['cp_idealtargetpay_ipncheck'] != '1' || !isset( $_GET["itemnumber"] ) )
                return;
                                
            $itemnumber = explode(";",$_GET["itemnumber"]);            
            $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_APPOINTMENTS_TABLE_NAME." WHERE id=".intval($itemnumber[0]) ); 
            
            $rowstargetpay = $wpdb->get_results( 
						$wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", intval($_GET["d"]) ) 
					);
			
	                
            if (!( isset($_POST['rtlo']) && isset($_POST['trxid']) && isset($_POST['idealtrxid']) && isset($_POST['status']) ))	            
	        {
	            echo 'Payment failed.';
	            exit;
	        }    

						
            
            $myrows = $wpdb->get_results( "SELECT * FROM ".CPABC_TDEAPP_CALENDAR_DATA_TABLE." WHERE reference='".intval($itemnumber[0])."'" );
            if (!count($myrows))
                cpabc_process_ready_to_go_appointment($_GET["itemnumber"]);            
            
			
			$location = cpabc_get_option('url_ok', CPABC_APPOINTMENTS_DEFAULT_OK_URL);
            header("Location: ".$location);
	
            exit();              
              
		}
               
       
		/**
		 * Used to deactivate PayPal Standard if PayPal Pro is enabled for the form
		 */
		public function get_option( $value, $field, $id )
		{
			if( $field == 'enable_paypal' )
			{
			    global $wpdb;
			    $rows = $wpdb->get_results( 
						$wpdb->prepare( "SELECT enabled FROM ".$wpdb->prefix.$this->form_table." WHERE formid=%d", $id ) 
					);
			    if ( !empty( $rows ) && $rows[0]->enabled)
				    $value = 0;
			}	
			return $value;
		} // End get_option		
				              	          		        			
		
		
    } // End Class
    
    // Main add-on code
    $CPABC_iDealTargetPay_obj = new CPABC_iDealTargetPay();
    
	// Add addon object to the objects list
	global $cpabc_addons_objs_list;
	$cpabc_addons_objs_list[ $CPABC_iDealTargetPay_obj->get_addon_id() ] = $CPABC_iDealTargetPay_obj;
}


?>