<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | Common database model class. It use for common functions             |
// | File name : common.php                                               |
// | PHP version >= 5.2                                                   |
// | Created On 4 January 2012                                            |
// +----------------------------------------------------------------------+
// | Author: Rajath Kamal <rajath.k@armiasystems.com>                     |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems ? 2010                                      |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------|



class ControllerPaypal extends BaseController
{
	/*
		construction function. we can initialize the models here
	*/
    public $userName   =   '';
    public $userPass   =   '';
    public $userId     =   0;
     public function init()
    {
        parent::init();
        $this->_session = new LibSession();
                if($this->_session->get('user_id')=="")
                   {
                       $this->switchmodule(ConfigUrl::base('default'));
                       exit;
                   }

                $this->_common		= new ModelCommon;
		$this->_modelpaypal		= new ModelPaypal;
//                $this->_indexmodel      = new ModelIndex;
//                LibSession::set('user_id',1);
   
            $this->Libpaypal_class = new  LibPaypal_class();

    }



    
	public function process($listId,$status='')
	{
           $this->Libpaypal_class = new  LibPaypal_class();

           $paypalEnable    =   $this->_common->selectRow("settings","value","settingfield='enablepaypal'");

           $paypalTestMode  =   $this->_common->selectRow("settings","value","settingfield='enablepaypalsandbox'");

           $paypalEmail     =   $this->_common->selectRow("settings","value","settingfield='paypalemail'");

           //$paymentAmount   =   $this->_common->selectRow("settings","value","settingfield='nFeatured_Amount'");
           if($status == ''){
                $paymentAmount   =   $this->_common->selectRow("settings","value","settingfield='nFeatured_Amount'");
            }
            else{
                $join   =" INNER JOIN ".MYSQL_TABLE_PREFIX."plans AS plans ON plans.nPlanId = product.nPlanId";
                $where  =" WHERE  product.nBusId =".$listId;
                $row_listings    =   $this->_common->getAllData('plans.vPlanAmount,plans.vPlanDuration','product AS product',$join ,$where);
               //echopre1($row_listings);
                $paymentAmount = $row_listings[0]->vPlanAmount;
                //exit;
                $duration = $row_listings[0]->vPlanDuration;
               //$amount   =   $this->_common->selectRow("settings","value","settingfield='nFeatured_Amount'"); 
            }

           $paymentCurrency =   $this->_common->selectRow("settings","value","settingfield='admin_currency'");
           //exit;

            if($paypalTestMode == "Y"){
                //$paypalurl ="http://192.168.0.11/sudheesh/paypal.php";
                    $paypalurl = "https://www.sandbox.paypal.com/cgi-bin/webscr";
                    $paypalbuttonurl = "https://www.sandbox.paypal.com/en_US/i/btn/x-click-but23.gif" ;
            }else{
                //$paypalurl ="http://192.168.0.11/sudheesh/paypal.php";
                    $paypalurl = "https://www.paypal.com/cgi-bin/webscr";
                    $paypalbuttonurl = "https://www.paypal.com/en_US/i/btn/x-click-but23.gif" ;
            }

        // User Information

        $this->userName = $this->_session->get('user_login');
        $this->userPass = $this->_session->get('user_pass');
        $this->userId   = $this->_session->get('user_id');

        if($status == ''){
            $this_script_success    = BASE_URL."business/paypal/success/".$listId;
        }
        else{
            $this_script_success    = BASE_URL."business/paypal/success/".$listId."/renew";
        }

        $this_script_cancel     = BASE_URL."business/paypal/cancel";
         //if($status == ''){
            $this_script_ipn        = BASE_URL."paypal/ipn";
//          }
//        else{
//            $this_script_ipn        = BASE_URL."business/paypal/ipn/renew";
//        }

        $txtUserFirstName =  $this->_common->selectRow("users","vFirstName","nUserId='".$this->userId."'");

        $txtUserLastName =  $this->_common->selectRow("users","vLastName","nUserId='".$this->userId."'");

        $listName        = $this->_common->selectRow("product","Title","nBusId='".$listId."'");
        

        $this->view->txtUserFirstName       = $txtUserFirstName;

        $this->view->txtUserLastName        = $txtUserLastName;

        $this->view->paypalEmail             = $paypalEmail;
        
        $this->view->paypalEmail             = $paypalEmail;
        
        $this->view->this_script_success     = $this_script_success;
        
        $this->view->this_script_cancel      = $this_script_cancel;

        $this->view->this_script_ipn         = $this_script_ipn;
        
        $this->view->paymentAmount           = $paymentAmount;

        $this->view->paymentCurrency         = $paymentCurrency;
        
        
        $this->view->submit_paypal_post      = 'submit_paypal_post';

        $this->view->paypalUrl               = $paypalurl;
        
        
         $this->view->Libpaypal_class       = $this->Libpaypal_class;

         $this->view->listName              = $listName;

         $this->view->listId              = $listId;


        
                  /*$this->Libpaypal_class->add_field('first_name', $txtUserFirstName);
                  $this->Libpaypal_class->add_field('last_name', $txtUserLastName);
                  $this->Libpaypal_class->add_field('business', $paypalEmail);
                  $this->Libpaypal_class->add_field('return', $this_script_success);
                  $this->Libpaypal_class->add_field('cancel_return', $this_script_cancel);
                  $this->Libpaypal_class->add_field('notify_url', $this_script_ipn);
                  $this->Libpaypal_class->add_field('item_name', 'Paypal Test Transaction');
                  $this->Libpaypal_class->add_field('amount', $paymentAmount);
                  $this->Libpaypal_class->add_field('currency_code', $paymentCurrency);

                  //$this->Libpaypal_class->add_field('custom', 'hhh-yyyy-uuu');

                  $this->Libpaypal_class->submit_paypal_post($paypalurl);*/


          
            
	}

        public function ipn_renew()
        {
          mail('smitha.m@armiasystems.com','Test subject','Test Message');
        }


        public function ipn($status='')
        {
//            $f3 = fopen("testipn.txt","a+");
//            fwrite($f3, $status);
//            fclose($f3);
            mail('smitha.m@armiasystems.com','Test subject','Test Message');

            $paypalTestMode  =   $this->_common->selectRow("settings","value","settingfield='enablepaypalsandbox'");

             if($paypalTestMode == "Y"){
                //$paypalurl ="http://192.168.0.11/sudheesh/paypal.php";
                    $paypalurl = "https://www.sandbox.paypal.com/cgi-bin/webscr";
                    $paypalbuttonurl = "https://www.sandbox.paypal.com/en_US/i/btn/x-click-but23.gif" ;
            }else{
                //$paypalurl ="http://192.168.0.11/sudheesh/paypal.php";
                    $paypalurl = "https://www.paypal.com/cgi-bin/webscr";
                    $paypalbuttonurl = "https://www.paypal.com/en_US/i/btn/x-click-but23.gif" ;
            }

               
            $this->Libpaypal_class = new  LibPaypal_class();
            if ($this->Libpaypal_class->validate_ipn($paypalurl)) {

          /*foreach ($this->Libpaypal_class->ipn_data as $key => $value) { $body2 .= "\n$key: $value"; }

            $f3 = fopen("testipn.txt","a+");
            fwrite($f3, $body2);
            fclose($f3);*/

                $paymentAmount = $this->Libpaypal_class->ipn_data['mc_gross'];

                $transaction_id = $this->Libpaypal_class->ipn_data['txn_id'];
          
                if($this->Libpaypal_class->ipn_data['custom']!='') {

                $Custom_Array = $this->Libpaypal_class->ipn_data['custom'];

                $Exp = explode('=>',$Custom_Array);

                $ListingId              = $Exp[0];

                $ListName               = $Exp[1];

                $txtUserFirstName       = $Exp[2];


                $txtUserLastName       = $Exp[3];


                $listName               = $Exp[4];

                
                   }
            }


            if($transaction_id!='')
                {

                 $paymentId = $this->_common->selectRow("payments","nPaymentId","vTransactionId='".$transaction_id."'  AND nListId=".$ListingId."");
                      
                    $arrProfile =   array("nListId"=>$ListingId,
                                        "vUserFirstName"=>$txtUserFirstName,
                                        "vUserLastName"=>$txtUserLastName,
                                        "vAmount"=>$paymentAmount,
                                        "vProductName"=>$ListName,
                                        "vTransactionId"=>$transaction_id
                                       );

if($paymentId=='') {
                  $paymentId =   $this->_common->addFields("payments",$arrProfile);
}     

                  if($status==''){
                    $arrProfile         =   array("nFeatured"=>1);

                    $this->_common->updateFields("product",$arrProfile,"nBusId='".$ListingId."'");
                  }
                  else{
                      //Renew Listing
                      $res = mysql_query("SELECT ADDDATE(CURDATE(),INTERVAL $duration Month) AS Expiry_date");
                      $row = mysql_fetch_row($res);
                      $expiry_date=$row['0'];
                      $arrProfile         =   array("nStatus"=>1,
                                                    "nPaymentStatus"=>1,
                                                     "nPlanExpiryDate"=>$expiry_date);

                    $this->_common->updateFields("product",$arrProfile,"nBusId='".$ListingId."'");
                      
                  }

                 

            }

            

        }

        public function success($listId,$status='')
        {
             mail('smitha.m@armiasystems.com','Test success subject','Test success Message');
                 if($_GET['tx']!='')
                     {

                   $transaction_id = $_GET['tx'];
                   //if($status==''){
                        $paymentId = $this->_common->selectRow("payments","nPaymentId","vTransactionId='".$transaction_id."' AND vPaymentStatus='P' AND nListId=".$listId."");
                      

                        if($paymentId!='')
                            {
                                 $arrUpdate  =   array("vPaymentStatus"=>'C');

                                 $this->_common->updateFields("payments",$arrUpdate,"nPaymentId='".$paymentId."'");
                                 $where  = "nBusId = '$listId'";
                                 $alias    =   $this->_common->selectRow('product','alias',$where);

                                  $this->redirect('index/viewlisting/'.$alias.'/1/2/');
                                  exit;
                          }
//                   }
//                   else{
//                       
//                       
//                   }
                          $this->view->message='success';

                }


            
        }
	
	/*
	function to load the index template
	*/
    
    public function loadComments()
    {

         if((!$this->_session->get('user_id'))){
            $this->redirect("index");
            exit;
        }
        $userId =   $this->_session->get('user_id');
        $this->view->disableLayout();
        $id =    $this->get('id');
        $resComments    =    $this->_common->getDatas("PC.*,P.Title","productcomment AS PC","product AS P ON P.nBusId=PC.nProductId","LEFT JOIN","nId='".$id."' AND P.nUserId='".$userId."'","","","","1");
        $this->view->resComments    =   $resComments[0];
    }
    

		

}
?>