<?php
/**
 * @version		3.0.0
 * @package		JomLand TicketCenter
 * @copyright	Copyright (C) 2010 JomLand.com. All rights reserved.
 * @link 		www.jomland.com
 * @license		GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */
defined('_JEXEC') or die('Restricted access');

use Joomla\Utilities\ArrayHelper;
use Joomla\Utilities;

require 'jlticketpayment.php';

class JLTicketCenterPaypal extends JLTicketPayment
{

    public $payment_params = array('paypal_debug'=>1,
        'paypal_email'=>'erezavny@gmail.com');

    private $payment_data = array();


    private $returnURL;
    private $cancelURL;

    function __construct(){
        $this->returnURL = JURI::base()."index.php?option=com_jlticketcenter&view=checkout&step=pay_comp";
        $this->cancelURL = JURI::base()."index.php?option=com_jlticketcenter&view=checkout&step=pay_cancel";

        if (session_id() == "")
            session_start();
    }

    function buildPanel($payment_class){

        $payment_config = $this->getConfig($payment_class);

        //$pane =  JPane::getInstance('Sliders', array());

        $output = JHtml::_('tabs.start', 'slider-', array('useCookie' => 1));
        //$output .=$pane->startPanel(JText::_('Parameters'), 'panel1');
        $output .= JHtml::_('tabs.panel', JText::_('Parameters'), 'panel1');
        $output .='<div id="payment_params">'."\n";

        $output .='<tr>'."\n";
        $output .='<td width="100" class="key">'."\n";
        $output .='<label for="published">'.JText::_('Paypal Test Mode').'</label>'."\n";
        $output .='</td>'."\n";
        $output .='<td>'."\n";
        $output .= JHTML::_('select.genericlist', array(0=>JText::_('JNO'),1=>JText::_('JYES')), 'params[paypal_debug]', null, $optKey = 'value', $optText = 'text',$payment_config->paypal_debug);

        $output .='</td>'."\n";
        $output .='</tr>'."\n";

        $output .='<tr>'."\n";
        $output .='<td width="100" class="key">'."\n";
        $output .='<label for="published">'.JText::_('PayPal payment email').'</label>'."\n";
        $output .='</td>'."\n";
        $output .='<td>'."\n";
        $output .= '<input name="params[paypal_email]" value="'.$payment_config->paypal_email.'" />'."\n";;
        $output .='</td>'."\n";
        $output .='</tr>'."\n";

        $output .='</div>';
        $output .= JHtml::_('tabs.end');

        return $output;
    }//EOF buildPanel


    function pross_payment($data){

        $pparams = new JLTicketCenterHelperSetup;

        $mainframe = JFactory::getApplication();

        //get Config
        $payment_config = $this->getConfig('paypal');

        if($payment_config->paypal_debug){
            $url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
        }
        else{
            $url = "https://www.paypal.com/cgi-bin/webscr";
        }

        $params = new JLTicketCenterHelperSetup;
        if ($params->get('logo')){
            $logo = JURI::root().'images/'.$params->get('logo');
        }else{
            $logo ='';
        }


        $post_variables = Array(
            "cmd" => "_ext-enter",
            "redirect_cmd" => "_xclick",
            "upload" => "1",
            "business" => $payment_config->paypal_email,
            "receiver_email" => $payment_config->paypal_email,
            "item_name" => JText::_('Order Number').": ". $data["order_id"],
            "order_id" => $data['order_id'],
            "invoice" => $data['order_id'],
            "amount" => round( $data['order_total'], 2),
            "shipping" => 0, //sprintf("%.2f", $db->f("order_shipping")),
            "currency_code" => $pparams->get('currency_code','USD'),
            "address_override" => "0",
            "first_name" => $data['first_name'],
            "last_name" => $data['last_name'],
            "address1" => $data['street'],
            "address2" => $data['street_2'],
            "zip" => $data['zip'],
            "city" => 	$data['city'],
            "state" => $data['state'],
            "country" => $data['country'],
            "email" => $data['user_email'],
            "night_phone_b" => '',
            "cpp_header_image" => $logo,
            "return" => JURI::base()."index.php?option=com_jlticketcenter&view=order",
            "notify_url" => JURI::  base().DS.'index.php?option=com_jlticketcenter&controller=cart&task=paypal_notification',
            "cancel_return" => JURI::base()."index.php",
            "undefined_quantity" => "0",

            //"test_ipn" => PAYPAL_DEBUG,
            "pal" => "X9STR3BFMPBDS",
            "no_shipping" => "1",
            "no_note" => "1",
            "rm" => "2"
        );


        $this->payment_data =$post_variables;

        $query_string = "?";
        foreach( $post_variables as $name => $value ) {
            $query_string .= $name. "=" . urlencode(stripslashes($value)) ."&";
        }

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

         echo $url.$query_string;
         die;
         */

        $mainframe = JFactory::getApplication();
        $mainframe->redirect( $url.$query_string, $msg );

        die;
    }// EOF pross

    public function get_paypal_IPN(){
        $payment_config = self::getConfig('paypal');
        $paypal_debug 	= $payment_config->paypal_debug;

        // read the post from PayPal system and add 'cmd'
        $req = 'cmd=_notify-validate';

        foreach ($_POST as $key => $value){
            $value = urlencode(stripslashes($value));
            $req .= "&$key=$value";
        }

        $req2 = $req;
        // post back to PayPal system to validate
        $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

        if($paypal_debug){
            $url = 'ssl://www.sandbox.paypal.com';
        }
        else{
            $url = 'ssl://www.paypal.com';
        }

        $fp = fsockopen($url , 443, $errno, $errstr, 30);

        if (!$fp) {
            $paypal_data = array('payment_status'=>'error');
        }
        else{
            fputs ($fp, $header . $req);
            while (!feof($fp)) {
                $res = fgets ($fp, 1024);

                $paypal_data = $_POST;
            }// endwhile get data from file
            fclose ($fp);
        }
        return $paypal_data;

    }// EOF get_paypal_IPN

    public function notify_proccess(){

        $paypal_data = self::get_paypal_IPN();
        $paypal_data  = ArrayHelper::toObject($paypal_data);

        if ($paypal_data->payment_status=='error'){
            return;
        }
        $timestr=strtotime($paypal_data->payment_date);
        $tran_time =strftime("%Y-%m-%d %H:%M:%S",$timestr);


        require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'models'.DS.'paymentlog.php');

        $data = array();
        $data['payment_time']=$tran_time ;
        $data['order_id']=$paypal_data->invoice;
        $data['payment_method']='PayPal Express';
        $data['amount']=$paypal_data->mc_gross;

        if ($paypal_data->payment_status !='Completed'){

            $data['status']=0;
            $data['transactionid']='';

            $model = JModelLegacy::getInstance('PaymentLog', 'JLTicketCenterModel');
            $model->store($data);

            return ;
        }

        // Success write to log and proccess the order
        $data['status']=1;
        $data['transactionid']=$paypal_data->txn_id;

        $model = JModelLegacy::getInstance('PaymentLog', 'JLTicketCenterModel');
        $model->store($data);

        require_once (JPATH_COMPONENT_ADMINISTRATOR.DS.'models'.DS.'order.php');
        require_once (JPATH_COMPONENT_ADMINISTRATOR.DS.'controllers'.DS.'order.php');

        $order = array();
        $order['order_id'] 		= $paypal_data->invoice;
        $order['order_status']	=0;
        $order['new_status']	='OrderPaid';
        $order['payment_pross']	=true;
        $order['no_redirect']	=true;
        $order[ JSession::getFormToken()]="1";

        JLTicketCenterControllerOrder::orderProcess($order);

        die;
    }//EOF
}//EOC