<?php
/*
@author: PREMIUM WEB CART
*/
class Merchant_model extends CI_Model {

	//constructor
	public function __construct()
	{
		parent::__construct ();
	}

    function loginUserCheck($userName, $currPassword)
    {
        $sql = 'SELECT m.merchant_row_id,
                       m.merchant_id,
                       m.first_name,
                       m.last_name, m.email_address,
                       m.parent_merchant_row_id,
                       m.user_type,
                       m.access_staff_view,
                       m.access_crm,
                       m.access_project_manager,
                       m.access_ticket_system,
                       m.access_live_chat,
                       m.access_members_pro,
                       m.access_pwc,
                       m.access_store,
                       m.time_zone
               FROM tbl_merchant AS m
               WHERE m.email_address = '. $this->db->escape($userName) . '
               AND m.user_password = ' . $this->db->escape($currPassword). '
               AND m.active_status = 1';

        $resultSet = $this->db->query ( $sql );
        $user = $resultSet->row ();

        if(!$user)
          return false;

        if($user->parent_merchant_row_id)
        {
            $merchant = $this->getMerchantByRowId($user->parent_merchant_row_id);
            $user->is_expires = $merchant->is_expires;
            $user->subscription_type = $merchant->subscription_type;
            $user->package_id = $merchant->package_id;
            $user->is_chargeable = $merchant->is_chargeable;
            $user->day_count_last_trans = $merchant->day_count_last_trans;
            $user->no_of_fail_transaction = $merchant->no_of_fail_transaction;
            $user->show_system_message = $merchant->show_system_message;
            $user->free_charge_product_row_id = $merchant->free_charge_product_row_id;
            $user->stores_site_url = $merchant->stores_site_url;
            $user->white_label_id = $merchant->white_label_id;
            $user->access_staff_view = $user->access_staff_view;
            $user->access_pwc = $user->access_pwc;
            $user->access_crm = $user->access_crm;
            $user->access_project_manager = $user->access_project_manager;
            $user->access_ticket_system = $user->access_ticket_system;
            $user->access_live_chat = $user->access_live_chat;
            $user->access_members_pro = $user->access_members_pro;
        }
        else
        {
            $user =  $this->getMerchantByRowId($user->merchant_row_id);
        }

        return $user;
    }

    function loginCheckByMerchantId($merchantId)
    {
        $sql = 'SELECT m.merchant_row_id,
                       m.merchant_id,
                       m.first_name,
                       m.last_name,m.email_address,
                       m.is_expires,
                       m.subscription_type,
                       m.package_id,
                       m.parent_merchant_row_id,
                       p.is_chargeable,
                       DATEDIFF(\'' . date('Y-m-d') . '\', DATE_FORMAT(m.last_transaction_date, \'%Y-%m-%d\')) AS day_count_last_trans,
                       m.no_of_fail_transaction,
                       m.show_system_message,
                       m.free_charge_product_row_id,
                       m.stores_site_url,
                       m.white_label_id,
                       m.user_type 
               FROM tbl_merchant AS m JOIN
               tbl_package AS p ON(p.package_id = m.package_id)
               WHERE m.merchant_id = '. $this->db->escape($merchantId) .'
               AND m.active_status = 1';

        $resultSet = $this->db->query ( $sql );
        return $resultSet->row ();
    }

	function getMerchantIdByOrderId($order_id) {
		$this->db->select ( 'merchant_row_id' );
		$this->db->from ( 'tbl_order' );
		$this->db->where ( 'order_id', $order_id );
		$resultSet = $this->db->get ();
		$result = $resultSet->row ();
		return $result->merchant_row_id;
	}

    function getMerchantIDByOrderRowID($orderRowId)
    {
        $sql = 'SELECT m.merchant_id
                FROM tbl_order o
                INNER JOIN tbl_merchant m ON m.merchant_row_id = o.merchant_row_id
                WHERE o.order_row_id=\'' . $orderRowId . '\'';

        $query = $this->db->query($sql);
        $row = $query->row();
        return $row->merchant_id;
    }

    function isMerchantExist($merchantRowId, $merchantId = '')
    {
        $sql = 'SELECT merchant_row_id
                FROM tbl_merchant';

        if($merchantRowId && $merchantId)
        {
            $sql .= ' WHERE merchant_row_id = ' . $this->db->escape($merchantRowId) .'
                    AND merchant_id = ' . $this->db->escape($merchantId);
        }
        else if($merchantRowId)
        {
            $sql .= 'WHERE merchant_row_id = ' . $this->db->escape($merchantRowId);
        }
        else if($merchantId)
        {
            $sql .= 'WHERE merchant_id = ' . $this->db->escape($merchantId);
        }
        $query = $this->db->query($sql);
        $row = $query->row();

        if($row)
        {
            if($row->merchant_row_id)
            {
                return true;
            }
        }

        return false;
    }

	/**
	 * get merchant details
	 *
	 * @param $merchant_row_id
	 * @return Object
	 */
	function getMerchantDetails($merchant_row_id, $fields = '*') {
        if(!empty($merchant_row_id))
        {
		    $this->db->select ( $fields );
		    $this->db->from ( 'tbl_merchant' );
		    $this->db->where ( 'merchant_row_id', $merchant_row_id );
		    $res = $this->db->get ();
		    return $res->row ();
        }
        return false;
	}
    function getMerchantProfileToUpdate($merchant_row_id, $fields = '*') {
        if(!empty($merchant_row_id))
        {
            $this->db->select ( $fields );
            $this->db->from ( 'tbl_merchant' );
            $this->db->where ( 'merchant_row_id', $merchant_row_id );
            $this->db->where('parent_merchant_row_id', getCurrentMerchantId());
            $res = $this->db->get ();
            return $res->row ();
        }
        return false;
    }

    /**
     * get merchant details with current package info
     *
     * @param $merchant_row_id
     * @return Object
     */
    function getMerchantDetailsForUpgrade($merchant_row_id)
    {
         $sql = 'SELECT m.*,
                        pack.package_name,
                        pack.trail_duration,
                        pack.database_limit,
                        ADDDATE(m.activation_date, INTERVAL pack.trail_duration DAY) AS expiresDate
                FROM tbl_merchant m
                INNER JOIN tbl_package pack ON pack.package_id = m.package_id
                WHERE m.merchant_row_id = ' . $this->db->escape($merchant_row_id);

        $resultSet = $this->db->query($sql);
        return $resultSet->row_array();
    }

    function getMerchantRowIdByEncryptedId($enc_merchant_row_row_id)
    {
        $sql = "SELECT merchant_row_id
                FROM tbl_merchant
                WHERE enc_merchant_row_id='$enc_merchant_row_row_id'";
        $query = $this->db->query($sql);
        $row = $query->row();
        if($row)
        {
            return $row->merchant_row_id;
        }
        return 0;
    }

	/**
	 * Get merchant details where return type array
	 *
	 * @param Integer
	 * @return array
	 */
	function getMerchant($merchant_row_id, $fields = '*')
	{
		$sql = 'SELECT ' . $fields . '
                FROM tbl_merchant
                WHERE merchant_row_id = ' . $this->db->escape( $merchant_row_id );
		$result_set = $this->db->query($sql);
		return  $result_set->row_array();
	}

    function getMerchantForWelcome($merchant_row_id)
    {
        $sql = 'SELECT m.merchant_row_id,
                    m.first_name,
                    m.last_name,
                    cb.date_format AS dateformat
                FROM tbl_merchant m
                INNER JOIN tbl_cart_basic cb ON cb.merchant_row_id = m.merchant_row_id
                WHERE m.merchant_row_id = ' . $this->db->escape( $merchant_row_id );
        $result_set = $this->db->query($sql);
        $row = $result_set->row();

        if($row)
        {
            $row->dateformat = getDateFormat($row->dateformat);
        }

        return $row;
    }

	/**
	 * get merchant list for super admin
	 *
	 * @return datagrid
	 */
	function getMerchantList($searchString)
	{
		$sql = 'SELECT 	m.merchant_row_id,
						m.merchant_id,
						CONCAT(m.first_name,\' \',m.last_name) as merchant_name,
						m.email_address,
						m.company_name,
						m.merchant_country,
						p.package_name,
						m.created_on,
						(CASE m.active_status
							WHEN  1 THEN \'Active\'
							ELSE \'Inactive\'
						END) AS active_status,
						(CASE m.is_expires
							WHEN 1 THEN \'Expires\'
							ELSE \'Regular\'
						END) AS is_expires,
						\'Details\' AS view_merchant,
						DATE_FORMAT((	CASE m.subscription_type
											WHEN \'1\' THEN ADDDATE(m.last_transaction_date, 30)
											WHEN \'2\' THEN ADDDATE(m.last_transaction_date, 365)
										END),\'' . $this->config->item('show_datetime_fmt') . '\') AS next_payment_date,
                		DATE_FORMAT(m.created_on, \'' . $this->config->item('show_datetime_fmt') . '\') AS join_date
				FROM tbl_merchant m
				INNER JOIN tbl_package p ON m.package_id = p.package_id
				'.$searchString;
		$sql = '(' . $sql . ' ) AS abc';

		$this->load->library ( 'rapyd' );
		$this->rapyd->load ( 'datagrid' );
		$grid = new DataGrid ( '', $sql );
		$grid->order_by ( 'created_on', 'desc' );
		$grid->per_page = 10;
		$grid->column_orderby ( '&nbsp;&nbsp;ID', 'merchant_id');
		$grid->column_orderby ( '&nbsp;&nbsp;Name', 'merchant_name');
		$grid->column_orderby ( 'Company Name', 'company_name');
		$grid->column_orderby ( 'Country', 'merchant_country');
		$grid->column_orderby ( 'Package', 'package_name' );
		$grid->column_orderby ( 'Active?', 'active_status');
		$grid->column_orderby ( 'Expired?', 'is_expires');
        $grid->column_orderby ( 'Join Date', 'join_date');
		$grid->column_orderby ( 'Next Payment Date', 'next_payment_date', 'next_payment_date', 'width="75"');
		$grid->column_detail ( '', 'view_merchant', 'administration/merchant/showMerchant/<#merchant_row_id#>', 'align=\'left\'', false, '', true, 'colspan="3"');
		$grid->build ();
		return $grid->output;
	}

    function suspendedMerchantList($conditions)
    {
        $sql = 'SELECT  m.merchant_row_id,
                        m.merchant_id,
                        CONCAT(m.first_name,\' \',m.last_name) as merchant_name,
                        m.first_name,
                        m.last_name,
                        m.email_address,
                        m.company_name,
                        m.merchant_country,
                        p.package_name,
                        m.created_on,
                        (CASE m.is_expires
                            WHEN 1 THEN \'Expired\'
                            ELSE \'Regular\'
                        END) AS is_expires,
                        \'Details\' AS view_merchant,
                        DATE_FORMAT((    CASE m.subscription_type
                                            WHEN \'1\' THEN ADDDATE(m.last_transaction_date, 30)
                                            WHEN \'2\' THEN ADDDATE(m.last_transaction_date, 365)
                                        END),\'' . $this->config->item('show_datetime_fmt') . '\') AS next_payment_date,
                        DATE_FORMAT(m.created_on, \'' . $this->config->item('show_datetime_fmt') . '\') AS join_date
                FROM tbl_merchant m
                INNER JOIN tbl_package p ON m.package_id = p.package_id
                WHERE m.active_status = 0 '.$conditions;

        $_SESSION['session_suspended_merchant'] = $sql;
        $sql = '(' . $sql . ' ) AS abc';

        $this->load->library ( 'rapyd' );
        $this->rapyd->load ( 'datagrid' );
        $grid = new DataGrid ( '', $sql );
        $grid->order_by ( 'created_on', 'desc' );
        $grid->per_page = 25;
        $grid->column_orderby ( '&nbsp;&nbsp;ID', 'merchant_id');
        $grid->column_orderby ( '&nbsp;&nbsp;Name', 'merchant_name');
        $grid->column_orderby ( 'Company Name', 'company_name');
        $grid->column_orderby ( 'Country', 'merchant_country');
        $grid->column_orderby ( 'Package', 'package_name' );
        $grid->column_orderby ( 'Expired?', 'is_expires');
        $grid->column_orderby ( 'Join Date', 'join_date');
        $grid->column_detail ( '', 'view_merchant', 'administration/merchant/showMerchant/<#merchant_row_id#>/1', 'align=\'left\'', false, '', true, 'colspan="3"');
        $grid->build ();
        return $grid->output;
    }

    function getCountForSuspendedMerchant()
    {
       $sql = $_SESSION['session_suspended_merchant'];
       unset($_SESSION['session_suspended_merchant']);
       $res = $this->db->query($sql);
       $count = $res->num_rows();
       return $count;
    }

	/**
	 * Get merchant payment detials information
	 *
	 * @param $merchant_row_id
	 * @return unknown
	 */
	function merchantPaymentDetails($merchant_row_id)
	{
		$this->db->select('*');
		$this->db->from('tbl_payment_details');
		$this->db->where('merchant_row_id',$merchant_row_id);
		$resultSet = $this->db->get();
		return $resultSet->result();
	}

	function isMerchantEmailExists($merchantRowId, $merchantEmail)
	{
		$sql = 'SELECT merchant_row_id
                FROM tbl_merchant
                WHERE email_address = ' . $this->db->escape($merchantEmail) .'
                AND merchant_row_id != '. $this->db->escape($merchantRowId) . '
                LIMIT 1';

		$result_set = $this->db->query($sql);
		$row = $result_set->row();

        return !empty($row->merchant_row_id);
	}


	function updateMerchantInformation($data)
	{
		$this->db->where ( 'merchant_row_id', $data['merchant_row_id'] );
		$this->db->update ('tbl_merchant',$data);
	}


	/**
	 * Expires merchant account, also diactivate current package
	 *
	 * @param unknown_type $merchant_row_id
	 */
	function expiresMerchantAccount($merchant_row_id, $is_expires)
	{
		$this->db->set ( 'is_expires', $is_expires );
		//$this->db->set ( 'is_trial', '0' );
		$this->db->where ( 'merchant_row_id', $merchant_row_id );
		$this->db->update ( 'tbl_merchant' );
	}

	/**
	 * Return merchant information which is showed the dasebord
	 *
	 * @param unknown_type $merchant_row_id
	 * @return unknown
	 */
	function getMerchantInfo($merchant_row_id)
	{
		$sql = 'SELECT  CONCAT(m.first_name,\' \', m.last_name) as merchant_name,
                        m.active_status,
		                merchant_id,
                        m.subscription_type,
                        DATEDIFF(\'' . date('Y-m-d') . '\', DATE_FORMAT(m.last_transaction_date, \'%Y-%m-%d\')) AS day_count_last_trans,
                        m.activation_date,
                        m.is_trial,
                        m.is_expires,
                        pack.package_id,
                        pack.package_name,
		                pack.trail_duration,
                        DATE_FORMAT(m.next_charge_date,\'%Y-%m-%d\') AS  next_charge_date,
                        pack.database_limit,
		                (
                            SELECT COUNT(p.product_row_id)
		                    FROM tbl_product p
                            WHERE p.merchant_row_id = m.merchant_row_id
                            AND p.active_status=1
							AND p.is_gift_certificate = 0
							AND p.is_editable = 1
                        ) AS product_count,
                        CASE cb.date_format
                             WHEN \'1\' THEN \'' . getDateFormat(1) . '\'
                             WHEN \'2\' THEN \'' . getDateFormat(2) . '\'
                             WHEN \'3\' THEN \'' . getDateFormat(3) . '\'
                             WHEN \'4\' THEN \'' . getDateFormat(4) . '\'
                             WHEN \'5\' THEN \'' . getDateFormat(5) . '\'
                             WHEN \'6\' THEN \'' . getDateFormat(6) . '\'
                             WHEN \'7\' THEN \'' . getDateFormat(7) . '\'
                             WHEN \'8\' THEN \'' . getDateFormat(8) . '\'
                             ELSE \'' . $this->config->item('show_mysql_timestamp_fmt') . '\'
                        END AS dateformat,
		                (
                            SELECT COUNT(o.order_id)
		                    FROM tbl_order o
                            WHERE o.merchant_row_id = m.merchant_row_id
                            AND o.deletion_status=0
                        ) AS customer_count
                        FROM tbl_merchant m
                        INNER JOIN tbl_package pack ON pack.package_id = m.package_id
                        INNER JOIN tbl_cart_basic cb ON cb.merchant_row_id = m.merchant_row_id
                        WHERE m.merchant_row_id = '.$merchant_row_id;

        $resultSet = $this->db->query ( $sql );
		return $resultSet->row ();
	}

	/**
	 * Get merchant billing information
	 *
	 * @param $merchant_row_id
	 * @return unknown
	 */
	function getMerchantBillingInfo($merchant_row_id) {
		$sql = 'SELECT *
                FROM tbl_merchant_billing
                WHERE merchant_row_id = ' . $merchant_row_id ;

		$resultSet = $this->db->query($sql);
		return $resultSet->row_array ();
	}

    function getMerchantBillingInfoWithCardNumber($merchant_row_id) {
        $sql = 'SELECT *
                FROM tbl_merchant_billing
                WHERE merchant_row_id = ' . $merchant_row_id ;

        $resultSet = $this->db->query($sql);
        $row = $resultSet->row_array ();

        if($row)
        {
            $row['card_number'] = decrypt($row['card_number']);
            $row['card_exp_month'] = decrypt($row['card_exp_month']);
            $row['card_exp_year'] = decrypt($row['card_exp_year']);
            $row['card_holder_contactname'] = decrypt($row['card_holder_contactname']);
            $row['card_number_1'] = decrypt($row['card_number_1']);
            $row['card_exp_month_1'] = decrypt($row['card_exp_month_1']);
            $row['card_exp_year_1'] = decrypt($row['card_exp_year_1']);
            $row['card_holder_contactname_1'] = decrypt($row['card_holder_contactname_1']);
        }
        return $row;
    }

	/**
	 * Update merchant billing information
	 *
	 * @param array $billingInformation
	 */
	function updateMerchantBillingInfo($billingInformation)
	{
        if(isset($billingInformation['card_exp_month']) && $billingInformation['card_exp_month'])
        {
            $billingInformation['card_exp_month'] = encrypt($billingInformation['card_exp_month']);
        }

        if(isset($billingInformation['card_exp_year']) && $billingInformation['card_exp_year'])
        {
            $billingInformation['card_exp_year'] = encrypt($billingInformation['card_exp_year']);
        }

        if(isset($billingInformation['card_holder_contactname']) && $billingInformation['card_holder_contactname'])
        {
            $billingInformation['card_holder_contactname'] = encrypt($billingInformation['card_holder_contactname']);
        }

        if(isset($billingInformation['card_number']) && is_number($billingInformation['card_number']))
        {
            $billingInformation['card_number'] = encrypt($billingInformation['card_number']);
        }
        else
        {
            unset($billingInformation['card_number']);
        }


        if(isset($billingInformation['card_exp_month_1']) && $billingInformation['card_exp_month_1'])
        {
           $billingInformation['card_exp_month_1'] = encrypt($billingInformation['card_exp_month_1']);
        }

        if(isset($billingInformation['card_exp_year_1']) && $billingInformation['card_exp_year_1'])
        {
            $billingInformation['card_exp_year_1'] = encrypt($billingInformation['card_exp_year_1']);
        }

        if(isset($billingInformation['card_holder_contactname_1']) && $billingInformation['card_holder_contactname_1'])
        {
            $billingInformation['card_holder_contactname_1'] = encrypt($billingInformation['card_holder_contactname_1']);
        }

        if(isset($billingInformation['card_number_1']) && is_number($billingInformation['card_number_1']))
        {
            $billingInformation['card_number_1'] = encrypt($billingInformation['card_number_1']);
        }

		$this->db->where ( 'merchant_row_id', $billingInformation ['merchant_row_id'] );
		$this->db->update ( 'tbl_merchant_billing', $billingInformation );
	}

	/**
	 * update merchant profile
	 *
	 * @param array $merchantData
	 */
	function updateProfile($merchantData)
	{
		$this->db->where ( 'merchant_row_id', $merchantData['merchant_row_id'] );
		return $this->db->update ( 'tbl_merchant', $merchantData );
	}

	/**
	 * get merchant infomation for charge the payment
	 *
	 * @param unknown_type $merchant_row_id
	 * @param unknown_type $is_account_expire
	 * @return unknown
	 */
	function merchantInfoForCharge($merchant_row_id, $is_account_expire)
	{
        if($is_account_expire)
        {
            $where = " AND ((m.is_trial='0' AND m.is_expires='1') OR (m.no_of_fail_transaction > 0))";
        }

        $sql = "SELECT m.merchant_row_id,
                       m.merchant_id,
                       m.first_name,
                       m.last_name,
                       m.package_id,
                       m.signup_amount,
                       m.last_due_date,
                       m.next_charge_date,
                       m.subscription_type,
                       mb.billing_name,
                       mb.billing_email,
                       mb.billing_phone,
                       mb.billing_company,
                       mb.billing_address,
                       mb.billing_country,
                       mb.billing_state,
                       mb.billing_city,
                       mb.billing_zip_code,
                       mb.card_type,
                       mb.card_number,
                       mb.card_exp_month,
                       mb.card_exp_year,
                       mb.card_holder_contactname
                       FROM tbl_merchant AS m
                       LEFT JOIN tbl_merchant_billing AS mb ON(m.merchant_row_id = mb.merchant_row_id)
                       WHERE m.merchant_row_id = {$merchant_row_id} AND
                       m.package_id != 5 AND
                       m.active_status = 1 {$where}";

        $query = $this->db->query($sql);
        $row = $query->row_array ();

        if($row)
        {
            $row['card_number'] = decrypt($row['card_number']);
            $row['card_exp_month'] = decrypt($row['card_exp_month']);
            $row['card_exp_year'] = decrypt($row['card_exp_year']);
            $row['card_holder_contactname'] = decrypt($row['card_holder_contactname']);
        }
        return $row;
	}

	/**
	 * Change merchant expires status
	 *
	 * @param unknown_type $merchantDetails
	 * @param unknown_type $isUpgrade
	 */
	function changeMerchantExpiresStatus($merchantDetails , $isUpgrade = 0)
	{
        if(isset($merchantDetails ['last_transaction_date']))
        {
		    $this->db->set ( 'last_transaction_date', $merchantDetails ['last_transaction_date'] );
        }

        if(isset($merchantDetails ['last_due_date']))
        {
            $this->db->set ( 'last_due_date', $merchantDetails ['last_due_date'] );
        }

        if(isset($merchantDetails ['next_charge_date']))
        {
            $this->db->set ( 'next_charge_date', $merchantDetails ['next_charge_date'] );
        }

		$this->db->set ( 'no_of_fail_transaction', 0 );
		$this->db->set ( 'is_expires', '0' );
		if($isUpgrade)
		{
            if(isset($merchantDetails ['is_trial']))
            {
                $this->db->set('is_trial', $merchantDetails ['is_trial']);
            }
            else
            {
			    $this->db->set('is_trial','0');
            }
			$this->db->set('package_id',$merchantDetails['package_id']);

            if(in_array($merchantDetails['package_id'], $this->config->item('gymminder_packages')))
               $this->db->set('white_label_id', 2);
            else 
               $this->db->set('white_label_id', 1); 
        
			$this->db->set('subscription_type',$merchantDetails['subscription_type']);
			$this->db->set('signup_amount',$merchantDetails['signup_amount']);
		}
		$this->db->where ( 'merchant_row_id', $merchantDetails ['merchant_row_id'] );
		$this->db->update ( 'tbl_merchant' );
	}

	/**
	 * Save merchant package information
	 *
	 * @param array $merchantDetails
	 */
	function saveMerchantPackage($merchantDetails)
	{
        $this->db->set('active_status','0');
		$this->db->set('finish_date',$merchantDetails ['renew_date']);
		$this->db->where('merchant_row_id',$merchantDetails['merchant_row_id']);
		$this->db->where('active_status','1');
		$this->db->update('tbl_merchant_package_history');

		$this->db->set('merchant_row_id',$merchantDetails['merchant_row_id']);
		$this->db->set('package_id',$merchantDetails['package_id']);
        
		$this->db->set('subscription_type',$merchantDetails['subscription_type']);
		if(isset($merchantDetails['is_trial']))
		{
			$this->db->set('is_trial',$merchantDetails['is_trial']);
		}
		$this->db->set ('renew_date', $merchantDetails ['renew_date']);
		$this->db->set('active_status','1');
		$this->db->insert('tbl_merchant_package_history');
	}

	function getMerchantPackageModules($package_id)
	{
		$this->db->select('*');
		$this->db->from('tbl_package_module');
		$this->db->where('package_id', $package_id);
		$result_set = $this->db->get();
		return $result_set->result();
	}

	/**
	 * check current password
	 *
	 * @param $merchant_row_id
	 * @param $currentPassword
	 * @return unknown
	 */
	function checkCurrentPassword($merchant_row_id, $currentPassword) {
		$this->db->select ( '*' );
		$this->db->from ( 'tbl_merchant' );
		$this->db->where ( 'merchant_row_id', $merchant_row_id );
		$this->db->where ( 'user_password', $currentPassword );
		$resulSet = $this->db->get ();
		return $resulSet->row ();
	}

	/**
	 * Change current password
	 *
	 * @param $merchant_row_id
	 * @param $user_password
	 */
	function changeCurrentPassword($merchant_row_id, $user_password) {
		$this->db->set ( 'user_password', $user_password );
		$this->db->where ( 'merchant_row_id', $merchant_row_id );
		$this->db->update ( 'tbl_merchant' );
	}

	/**
	 * check valid user
	 *
	 * @param $emailAddress
	 * @return object
	 */
	function checkValidUser($emailAddress) {
		$this->db->select ( '*' );
		$this->db->from ( 'tbl_merchant' );
		$this->db->where ( 'email_address ', $emailAddress );
		$this->db->where ( 'active_status ', 1);
		$resulSet = $this->db->get ();
		return $resulSet->row ();
	}

	/**
	 * save temp password
	 *
	 * @param $merchant_row_id
	 * @param $tempPassword
	 */
	function saveTempPassword($merchant_row_id, $tempPassword) {
		$this->db->set ( 'temp_password', $tempPassword );
		$this->db->set ( 'merchant_row_id', $merchant_row_id );
		$this->db->insert ( 'tbl_merchant_temp_password' );
	}

	/**
	 * Check valid link
	 *
	 * @param $enc_merchant_row_id
	 * @return object
	 */
	function checkValidLink($enc_merchant_row_id) {
		$this->db->select ( '*' );
		$this->db->from ( 'tbl_merchant_temp_password' );
		$this->db->where ( 'md5(merchant_row_id)', $enc_merchant_row_id );
		$resulSet = $this->db->get ();
		return $resulSet->row ();
	}

	/**
	 * Remove temp password
	 *
	 * @param $merchant_row_id
	 */
	function removeTempPassword($merchant_row_id) {
		$this->db->where ( 'merchant_row_id', $merchant_row_id );
		$this->db->delete ( 'tbl_merchant_temp_password' );
	}

	/**
	 * get merchant trial account lists for checking expire accounts
	 *
	 * @return list
	 */
	function getMerchantTrialAccounts()
	{
        $sql = 'SELECT  m.*,
                        pack.package_id,
	        			pack.package_name,
	        			pack.trail_duration,
	        			pack.database_limit,
	        			ADDDATE(mph.renew_date, INTERVAL pack.trail_duration DAY) AS expiresDate,
	        			DATEDIFF(CURDATE(), (ADDDATE(mph.renew_date, INTERVAL pack.trail_duration DAY))) AS number_of_days
                 FROM tbl_merchant m
        		 INNER JOIN tbl_package pack ON pack.package_id = m.package_id
        		 INNER JOIN tbl_merchant_package_history mph ON mph.package_id = m.package_id AND mph.merchant_row_id = m.merchant_row_id
        		 WHERE m.is_trial = \'1\'
	        	 AND m.is_expires != \'1\'
  	      		 AND m.active_status = 1
    	    	 AND (DATEDIFF(CURDATE(), (ADDDATE(mph.renew_date, INTERVAL pack.trail_duration DAY))) IN (-5, -3)
                 OR DATEDIFF(CURDATE(), (ADDDATE(mph.renew_date, INTERVAL pack.trail_duration DAY))) >= 1)';

		$resultSet = $this->db->query($sql);
		return $resultSet->result_array();

	}

    function getMerchantsCurrentPackageInfo()
    {
        $sql = "SELECT  pack.package_id,
                        pack.package_name,
                        m.renew_date,
                        m.subscription_type,
                        DATE_FORMAT(m.renew_date,'" . $this->config->item('show_datetime_fmt') . "') AS subscription_date,
                        DATE_FORMAT(m.finish_date,'" . $this->config->item('show_datetime_fmt') . "') AS completion_date,
                        m.active_status
                FROM tbl_merchant_package_history m
                INNER JOIN tbl_package pack ON pack.package_id = m.package_id
                WHERE m.merchant_row_id = '$merchant_row_id'";
        $query = $this->db->query($sql);
        return $query->row();
    }

	/**
	 * get merchant packages list
	 *
	 * @param unknown_type $merchant_row_id
	 * @return unknown
	 */
	function getMerchantPackages($merchant_row_id)
	{
		$sql = 'SELECT
				pack.package_id, pack.package_name,m.renew_date,
				(CASE WHEN m.subscription_type = \''.$this->config->item('monthly_subcription').'\' THEN \'Monthly\'
				WHEN m.subscription_type = \''.$this->config->item('annual_subcription').'\' THEN \'Annually\'
				ELSE \'Trial\' END) AS subscription_type,
				DATE_FORMAT(m.renew_date,\'' . $this->config->item('show_datetime_fmt') . '\') AS subscription_date,
				DATE_FORMAT(m.finish_date,\'' . $this->config->item('show_datetime_fmt') . '\') AS completion_date,
				(CASE WHEN m.active_status = 1 THEN \'Active\' ELSE \' - \' END) as active_status
				FROM tbl_merchant_package_history m, tbl_package pack
				WHERE m.merchant_row_id = '.$merchant_row_id.' and pack.package_id = m.package_id ORDER BY m.renew_date ASC';
		$sql = '(' . $sql . ' ) AS abc';

		$this->load->library ( 'rapyd' );
		$this->rapyd->load ( 'datagrid' );
		$grid = new DataGrid ( '', $sql );
		$grid->per_page = 10;
		$grid->column ( 'Package', 'package_name', 'package_name', 'align=\'left\'' );
		$grid->column ( 'Subscription Type', 'subscription_type', 'subscription_type', 'align=\'left\'' );
		$grid->column ( 'Subscription Date', 'subscription_date', 'subscription_date', 'align=\'left\'' );
		$grid->column ( 'Package completion date', 'completion_date', 'completion_date', 'align=\'left\'' );
		$grid->column ( 'Active Status', 'active_status', 'active_status', 'align=\'left\'' );
		$grid->build ();
		return $grid->output;
	}

	/**
	 * Get merchant payment history
	 *
	 * @param unknown_type $merchant_row_id
	 */
	function getPaymentHistory($merchant_row_id)
	{

        $sql = "(SELECT pd.ack,
                        pd.payment_id,
                        pd.merchant_row_id,
                        pd.transaction_id,
                        pd.is_refund,
                        CONCAT('$', IF(pd.amount, pd.amount, 0.0000)) AS charge_amount,
                        IF(pd.success = 1, (IF(pd.is_refund = 0, 'Refund', 'Refunded')), '') AS event_action,
                        IF(pd.success = 1, 'N/A', pd.error_text) AS error_text,
                        DATE_FORMAT(date_of_transaction,'".$this->config->item('show_datetime_fmt')."') AS date_of_transaction
                FROM tbl_payment_details pd
                WHERE pd.merchant_row_id = $merchant_row_id
                AND (pd.order_row_id = 0 OR pd.order_row_id IS NULL)) AS abc";

		$this->load->library ( 'rapyd' );
		$this->rapyd->load('datagrid');
		$grid = new DataGrid('', $sql);
		$grid->per_page = 25;
		$grid->order_by ( 'payment_id', 'DESC' );
		$grid->column('Charge Date', 'date_of_transaction', 'date_of_transaction', 'align=\'left\'');
		$grid->column('Charge Amount', 'charge_amount', 'align=\'left\'');
		$grid->column ('Payment Status', 'ack', 'align=\'left\'');
		$grid->column('Transaction Id', 'transaction_id', 'align=\'left\'');
		$grid->column ('Error', 'error_text', 'align=\'left\'');
		$grid->column_detail('Action ','event_action','administration/merchant/showRefundByTransactionId/<#merchant_row_id#>/<#transaction_id#>/<#is_refund#>', 'align="left"',false,'class="submodal-520-380"',true);
		$grid->build();
		return $grid->output;
	}

	function getMerchantPackagesGrid($merchant_row_id)
	{
		$sql = 'SELECT
				pack.package_id, pack.package_name,
				(CASE WHEN m.subscription_type = \''.$this->config->item('monthly_subcription').'\' THEN \'Monthly\'
				WHEN m.subscription_type = \''.$this->config->item('annual_subcription').'\' THEN \'Annually\'
				ELSE \'Trial\' END) AS subscription_type,
				DATE_FORMAT(m.renew_date,\'' . $this->config->item('show_datetime_fmt') . '\') AS subscription_date,
				DATE_FORMAT(m.finish_date,\'' . $this->config->item('show_datetime_fmt') . '\') AS completion_date,
				(CASE WHEN m.active_status = 1 THEN \'Active\' ELSE \' - \' END) as active_status
				FROM tbl_merchant_package_history m, tbl_package pack
				WHERE m.merchant_row_id = '.$merchant_row_id.' and pack.package_id = m.package_id';

		$resultSet = $this->db->query($sql);
		return $resultSet->result_array();
	}
	/**
	 * @author Shafiul alam
	 * This function return payment information for refund
	 *
	 * @param unknown_type $merchant_row_id
	 * @param unknown_type $transaction_id
	 * @return unknown
	 * @version PWC1.2 bug solved
	 */
	function getRefundInfoByTransactionId($merchant_row_id,$transaction_id)
	{
		$this->db->select('DATE_FORMAT(date_of_transaction,\'' . $this->config->item('show_datetime_fmt') . '\')as date_of_transaction');
		$this->db->select('pd.payment_id');
		$this->db->select('pd.customer_id ');
		$this->db->select('pd.ack ');
		$this->db->select('pd.amount ');
		$this->db->select('pd.is_refund');
		$this->db->select('pd.transaction_id');
		$this->db->select('pd.merchant_row_id');

		$this->db->from('tbl_payment_details pd');
		$this->db->where('merchant_row_id', $merchant_row_id);
		$this->db->where('transaction_id', $transaction_id);
		$resultSet = $this->db->get();
        return $resultSet->result();
	}
	/**
	 * @author Shafiul alam
	 * This function return refund information
	 *
	 * @param unknown_type $merchant_row_id
	 * @param unknown_type $transaction_id
	 * @return unknown
	 * @version PWC1.2 bug solved
	 */
	function getRefundedInfoByTransactionId($merchant_row_id,$transaction_id)
	{
		$this->db->select('DATE_FORMAT(created_on,\'' . $this->config->item('show_datetime_fmt') . '\')as created_on');
		$this->db->select('ro.refund_total ');
		$this->db->select('ro.refund_coments');
		$this->db->select('ro.transaction_id');
		$this->db->select('ro.merchant_row_id');

		$this->db->from('tbl_refund_order ro');
		$this->db->where('merchant_row_id', $merchant_row_id);
		$this->db->where('transaction_id', $transaction_id);
		$resultSet = $this->db->get();
        return $resultSet->result();
	}
	function getContactFooterForMerchant($merchant_row_id)
	{
		$contact_profile = $this->getMerchant($merchant_row_id);

		$footerText = $contact_profile['first_name'].' '.$contact_profile['last_name'].'<br/>';
		$footerText .= $contact_profile['company_name'].'<br/>';
		$footerText .= $contact_profile['merchant_contact_phone'].'<br/>';
		$footerText .= $contact_profile['merchant_address'].'<br/>';
		$footerText .= $contact_profile['merchant_city'].'<br/>';
		if($contact_profile['merchant_country'] == 'US')
		{
            $footerText .= getStateFullName($contact_profile['state_province_name']).'<br/>';
		}
		else
		{
			$footerText .= $contact_profile['state_province_name'].'<br/>';
		}
		$footerText .= getCountryFullName($contact_profile['merchant_country']).'<br/>';
		$footerText .= $contact_profile['website_url'];

		$mail_footer['email_address'] = $contact_profile['email_address'];
		$mail_footer['company_name'] = $contact_profile['company_name'];
		$mail_footer['first_name'] = $contact_profile['first_name'];
		$mail_footer['last_name'] = $contact_profile['last_name'];
		$mail_footer['footer_text'] = $footerText;

		return $mail_footer;
	}

    function addMerchant ($merchant_signup_data)
	{
		/**
		 * insert into tbl_merchant table
		 */
		$this->db->set('first_name',$merchant_signup_data['first_name']);
		$this->db->set('last_name',$merchant_signup_data['last_name']);
		$this->db->set('company_name',$merchant_signup_data['company_name']);
		$this->db->set('email_address',$merchant_signup_data['email_address']);
		$this->db->set('public_email',$merchant_signup_data['email_address']);
		$this->db->set('user_password',$merchant_signup_data['user_password']);
		$this->db->set('merchant_contact_phone',$merchant_signup_data['merchant_contact_phone']);
		$this->db->set('merchant_address',$merchant_signup_data['merchant_address']);
		$this->db->set('merchant_city',$merchant_signup_data['merchant_city']);
		$this->db->set('state_province_name',$merchant_signup_data['state_province_name']);
		$this->db->set('merchant_zip_code',$merchant_signup_data['merchant_zip_code']);
		$this->db->set('merchant_postal_code',$merchant_signup_data['merchant_postal_code']);
		$this->db->set('merchant_country',$merchant_signup_data['merchant_country']);
		$this->db->set('website_url',$merchant_signup_data['website_url']);
		$this->db->set('package_id',$merchant_signup_data['package_id']);
        
        if(in_array($merchant_signup_data['package_id'], $this->config->item('gymminder_packages')))
           $this->db->set('white_label_id', 2);
        else 
           $this->db->set('white_label_id', 1);
            
		$this->db->set('is_trial',$merchant_signup_data['is_trial']);
		$this->db->set('subscription_type',$merchant_signup_data['subscription_type']);
		$this->db->set('signup_amount',$merchant_signup_data['signup_amount']);
		$this->db->set('active_status',$merchant_signup_data['active_status']);
		$this->db->set('activation_code',$merchant_signup_data['activation_code']);
		$this->db->set('activation_date',$merchant_signup_data['activation_date']);
		$this->db->set('last_transaction_date',$merchant_signup_data['last_transaction_date']);
        $this->db->set('next_charge_date',$merchant_signup_data['next_charge_date']);
		$this->db->set('created_on', getCurrentDateTimeForDB());
		$this->db->insert('tbl_merchant');

		$merchant_row_id = $this->db->insert_id();
        //////////////////////////////////////////
		//update merchant id
		$getInstance = &get_instance();
		$getInstance->load->model('administration/basic_setup_model','Basic_Setup_model',TRUE);
		// here admin_user_id is given 1 (for super admin) because
		// there will be only one super admin at a time (upto version 1.2)
		$basicData = $getInstance->Basic_Setup_model->getAdminBasicSetup(1);
		if($basicData->merchant_id_prefix)
		{
			$merchant_id_prefix = $basicData->merchant_id_prefix;
		}
		else
		{
			$merchant_id_prefix = $this->config->item('default_merchant_id_prefix');
		}

		$this->load->library('Application_Utility');
		//here 'PRO'=>prefix for product id will be taken from basic setup table
		$merchant_id = $this->application_utility->generateId($merchant_id_prefix,$merchant_row_id);

		$this->db->set('merchant_id',$merchant_id);
		$this->db->where('merchant_row_id',$merchant_row_id);
		$this->db->update('tbl_merchant');
		/////////////////////////////////////////

		$this->db->set('merchant_row_id',$merchant_row_id);
		$this->db->set('billing_name',$merchant_signup_data['first_name'].' '.$merchant_signup_data['last_name']);
		$this->db->set('billing_email',$merchant_signup_data['email_address']);
		$this->db->set('billing_phone',$merchant_signup_data['merchant_contact_phone']);
		$this->db->set('billing_company',$merchant_signup_data['company_name']);
		$this->db->set('billing_address',$merchant_signup_data['merchant_address']);
		$this->db->set('billing_country',$merchant_signup_data['merchant_country']);
		$this->db->set('billing_state',$merchant_signup_data['state_province_name']);
		$this->db->set('billing_city',$merchant_signup_data['merchant_city']);
		$this->db->set('billing_zip_code',$merchant_signup_data['merchant_zip_code']);

        $card_type= $this->config->item('friends_and_family_card_type');
        $card_number= $this->config->item('friends_and_family_card_number');

        $this->db->set('card_type',$card_type);
		$this->db->set('card_number', encrypt($card_number));
        $this->db->set('card_exp_month', encrypt(date('m')));
		$this->db->set('card_exp_year', encrypt(date('Y')+5));
		$this->db->set('card_holder_contactname', encrypt($merchant_signup_data['first_name'].' '.$merchant_signup_data['last_name']));

		$this->db->insert('tbl_merchant_billing');

		/***save basic setup to tbl_cart_basic****/
		$currency = 'USD';
		$currency_symbol = '$';
		$thankyou_url = BASEURL . 'thank_you/thank_you_url/' . md5($merchant_row_id);
		$data1['merchant_row_id'] = $merchant_row_id;
		$data1['primary_destination'] = $merchant_signup_data['email_address'];
		$data1['from_address'] = $merchant_signup_data['email_address'];
		$data1['catalog_url'] = $merchant_signup_data['website_url'];
		$data1['currency'] = $currency;
		$data1['currency_symbol'] = $currency_symbol;
		$data1['thankyou_url'] = $thankyou_url;

		/*setting auto-generated id prefix*/
		$data1['product_id_prefix'] = $this->config->item('default_product_id_prefix');//'PRO';
		$data1['order_id_prefix'] = $this->config->item('default_order_id_prefix');//'ORD';
		$data1['affiliate_id_prefix'] = $this->config->item('default_affiliate_id_prefix');//'AFF';

		$this->db->insert('tbl_cart_basic', $data1);


		$merchantInfo['merchant_row_id'] = $merchant_row_id;
		/**
		 * added by Jilani Jidni
		 * insert data to look & feel table
		 */
		$this->db->insert('tbl_look_and_feel', $merchantInfo);
		/**
		 * added by Jilani Jidni
		 * insert data to Gateway setup table
		 */
		$this->db->insert('tbl_gateway_setup', $merchantInfo);
		/**
		 * added by Jilani Jidni
		 * insert data to Gateway setup table
		 */
		$this->db->insert('tbl_advanced_setup', $merchantInfo);
		/**
		 * added by Jilani Jidni
		 * insert data to Auto Responder mail list setup table
		 */
		#$this->db->insert('tbl_autoresponder', $merchantInfo);

		return $merchant_row_id;
    }

    function getPackageInfoByPackageId ($merchant_row_id,$package_id)
    {
        $this->db->select ( '*' );
		$this->db->from ( 'tbl_package' );
		$this->db->where ( 'package_id', $package_id );
		$resultSet = $this->db->get ();
		return $resultSet->row_array ();
    }

    /**
     * For backwordCompatibility for merchant default Notification setup
     * @author Shafiul Alam
     * date: 28/02/09
     */
    function getMerchantInfoForNotification()
    {
		$sql= '(select merchant_row_id,email_address,website_url
                 FROM tbl_merchant m
                 WHERE merchant_row_id not in(
                                              select merchant_row_id
                                              from tbl_aff_notification_setup
                                             )
                )';
		$resultSet = $this->db->query($sql);
        return $resultSet->result_array ();
	}

    function saveOrderPlaceEmailDefaultText($mailManager_data)
    {
       $mailManager_data['modified_on'] = getCurrentDateTimeForDB();
       $this->db->insert(' tbl_email_manager ',$mailManager_data);
    }

    function getAllMerchant($fields = '*', $orderBy = '')
    {
        $this->db->select ( $fields );
		$this->db->from ( 'tbl_merchant' );
        $this->db->where ( 'parent_merchant_row_id', 0 );
        if($orderBy)
        {
            $this->db->order_by($orderBy);
        }
        $resultSet = $this->db->get();
        return $resultSet->result_array ();
    }
    function getMercnantInformationByMerchantRowId($merchant_row_id)
    {
        $sql = "SELECT *
                FROM tbl_merchant
                WHERE merchant_row_id = '$merchant_row_id'";

        $query = $this->db->query($sql);
        return $query->result_array();
    }

    function getMerchantInfoByEncRowId($enc_merchant_row_id)
    {
        $sql = "SELECT *
                FROM tbl_merchant
                WHERE MD5(merchant_row_id) = '$enc_merchant_row_id'";

        $resource = $this->db->query($sql);
        $result = $resource->row();
        return $result;

    }

    function getMerchantForLookUp()
    {
        $sql = 'SELECT  merchant_row_id,
                        CONCAT(first_name, \' \', last_name) AS merchant_name,
                        merchant_id
                FROM tbl_merchant
                WHERE active_status = 1 AND parent_merchant_row_id = 0
                ORDER BY first_name';

        $query = $this->db->query($sql);
        return $query->result_array();
    }

    function upgradeMerchantFromTrial($merchantData, $upgradeToPackage, $bySuperAdmin = false)
    {
        $data = array();
        $data['merchantBilling'] = $this->getMerchantBillingInfoWithCardNumber($merchantData['merchant_row_id']);

        $CI =& get_instance();
        $CI->load->model ( 'administration/package_model', 'Package_model', TRUE );

        $data ['packageList'] = $CI->Package_model->getActivePackages ();

        $packageInfo = $CI->Package_model->getPackage($upgradeToPackage);
        $descriptionText = 'Merchant account upgrading to '.$packageInfo['package_name'];

        if($merchantData['subscription_type'] == '0' || $merchantData['subscription_type'] == $this->config->item('monthly_subcription'))
        {
            $merchantData['subscription_type'] = $this->config->item('monthly_subcription');
            $data['merchantBilling']['signup_amount'] = $packageInfo['monthly_price'] != 0.00 ? $packageInfo['monthly_price'] : 0.01;
            $descriptionText .= ' as monthly subscription';
            $nextBillingDate = date('Y-m-d H:i:s', time() + 2592000);
        }
        else
        {
            $merchantData['subscription_type'] = $this->config->item('annual_subcription');
            $data['merchantBilling']['signup_amount'] = $packageInfo['annual_price'] != 0.00 ? $packageInfo['annual_price'] : 0.01;
            $descriptionText .= ' as annual subscription';
            $nextBillingDate = date('Y-m-d H:i:s', time() + 31536000);
        }

        $descriptionText .= ' on '.$this->config->item('project_name');
        $data['merchantBilling']['description'] = $descriptionText;

        $CI->load->model ( 'administration/admin_user_model', 'Admin_user_model', TRUE );
        $gatewaySetup = $CI->Admin_user_model->getAdminGatewaySetup();

        $CI->load->model ( 'paymentModel/Payment_model', 'Payment_model', TRUE );
        $paymentDetails = $CI->Payment_model->chargeForMerchantSignUp($data['merchantBilling'], $gatewaySetup);

        $paymentDetails['merchant_row_id'] = $merchantData['merchant_row_id'];
        $paymentDetails['date_of_transaction'] = getCurrentDateTimeForDB();
        $CI->load->model('scheduleJob/Recurring_Payment_model', 'Recurring_Payment_model', TRUE);
        $CI->Recurring_Payment_model->savePaymentDetails($paymentDetails);
        
        if(!$paymentDetails['success'])
        {
            if(!$bySuperAdmin)
            {
                $this->expiresMerchantAccount($merchantData['merchant_row_id'], 1);
                
                $CI->load->model('api/Notification_model', '', true);
                $info = array('merchant_row_id' => $merchantData['merchant_row_id'],
                              'package_id' => $merchantData['package_id'],
                              'subscription_type' => $merchantData['subscription_type'],
                              'active_or_not' => 0);

                if($this->config->item('enable_crm_notification')){
                    $CI->Notification_model->sendMerchantPackageChangeNotificationToCRM($info);
                }

                if($this->config->item('enable_project_notification')){
                    $CI->Notification_model->sendMerchantPackageChangeNotificationToProject($info);
                }

                if($this->config->item('enable_member_pro_notification')){
                    $CI->Notification_model->sendMerchantPackageChangeNotificationToMembersPro($info);
                }
            }
            $return = 'Transaction does not completed for the following error: '.$paymentDetails['error_text'];
        }
        else
        {
            $CI->load->model('mailData/Mailer_model', 'Mailer_model', TRUE);

            $data ['merchantBilling']['renew_date']
                = $data ['merchantBilling']['last_transaction_date']
                = $data ['merchantBilling']['last_due_date']
                = $paymentDetails['date_of_transaction'];
            $data ['merchantBilling']['package_id'] = $upgradeToPackage;
            $data ['merchantBilling']['subscription_type'] = $merchantData['subscription_type'];
            $data ['merchantBilling']['next_charge_date'] = $nextBillingDate;

            $this->changeMerchantExpiresStatus($data['merchantBilling'],1);
            $this->saveMerchantPackage($data['merchantBilling']);
            /**
             * Get super admin public profile information
             */
            $this->load->model('administration/contact_profile_model','Contact_Profile_model',TRUE);
            $emailData['contact_profile_admin'] = $CI->Contact_Profile_model->getSuperAdminContactDetails();

            $merchantData['packageInfoByPackageId'] = $packageInfo;
            $merchantData['currency_symbol'] = '$';
            $merchantData['from_address'] = $emailData['contact_profile_admin']['email_address'];
            $merchantData['full_name'] = $emailData['contact_profile_admin']['full_name'];
            $merchantData['to_address'] = $merchantData['email_address'];
            $merchantData['subject'] = $this->lang->line('MERCHANT_ACCOUNT_PAYMENT_SUCCESS');
            $CI->Mailer_model->sendMails($merchantData, 'payment_success_to_merchant');

            $merchantData['from_address'] = $this->config->item('adminNotifyEmail');
            $merchantData['full_name'] = $this->config->item('adminNotifyEmail');
            $merchantData['to_address'] = $emailData['contact_profile_admin']['email_address'];
            $merchantData['subject'] = $this->lang->line('MERCHANT_ACCOUNT_PAYMENT_SUCCESS_TO_ADMIN');
            $CI->Mailer_model->sendMails($merchantData, 'payment_success_to_admin');

            $CI->load->model('api/Notification_model', '', true);
            $info = array('merchant_row_id' => $merchantData['merchant_row_id'],
                            'package_id' => $upgradeToPackage,
                            'subscription_type' => $merchantData['subscription_type']);

            if($this->config->item('enable_crm_notification')){
                $CI->Notification_model->sendMerchantPackageChangeNotificationToCRM($info);
            }

            if($this->config->item('enable_project_notification')){
                $CI->Notification_model->sendMerchantPackageChangeNotificationToProject($info);
            }

            if($this->config->item('enable_member_pro_notification')){
                $CI->Notification_model->sendMerchantPackageChangeNotificationToMembersPro($info);
            }

            $return = 'Upgrade successful';
        }

        log_merchant_charges($return);
        return $return;
    }

    function upgradeMerchant($merchantData, $upgradeToPackage, $bySuperAdmin = false)
    {
        $updateBillingDate = $merchantData['package_id'] == $this->config->item('friend_family_package') || $merchantData['is_trial'];
        $data = array();
        $data['merchantBilling'] = $this->getMerchantBillingInfoWithCardNumber($merchantData['merchant_row_id']);

        $CI =& get_instance();
        $CI->load->model ( 'administration/package_model', 'Package_model', TRUE );

        $data ['packageList'] = $CI->Package_model->getActivePackages ();

        $packageInfo = $CI->Package_model->getPackage($upgradeToPackage);

        if($merchantData['subscription_type'] == '0' || $merchantData['subscription_type'] == $this->config->item('monthly_subcription'))
        {
            $merchantData['subscription_type'] = $this->config->item('monthly_subcription');
            $data['merchantBilling']['signup_amount'] = $packageInfo['monthly_price'] != 0.00 ? $packageInfo['monthly_price'] : 0.01;
            $nextBillingDate = date('Y-m-d H:i:s', time() + 2592000);
        }
        else
        {
            $merchantData['subscription_type'] = $this->config->item('annual_subcription');
            $data['merchantBilling']['signup_amount'] = $packageInfo['annual_price'] != 0.00 ? $packageInfo['annual_price'] : 0.01;
            $nextBillingDate = date('Y-m-d H:i:s', time() + 31536000);
        }

        $CI->load->model('mailData/Mailer_model', 'Mailer_model', TRUE);

        $data ['merchantBilling']['renew_date'] = getCurrentDateTimeForDB();
        $data ['merchantBilling']['package_id'] = $upgradeToPackage;
        $data ['merchantBilling']['subscription_type'] = $merchantData['subscription_type'];
        $data ['merchantBilling']['is_trial'] = $packageInfo['is_trial'];

        if($updateBillingDate)
        {
            $data ['merchantBilling']['last_due_date'] = $data ['merchantBilling']['renew_date'];
            $data ['merchantBilling']['next_charge_date'] = $nextBillingDate;
        }

        $this->changeMerchantExpiresStatus($data['merchantBilling'],1);
        $this->saveMerchantPackage($data['merchantBilling']);
        /**
         * Get super admin public profile information
         */
        $this->load->model('administration/contact_profile_model','Contact_Profile_model',TRUE);
        $emailData['contact_profile_admin'] = $CI->Contact_Profile_model->getSuperAdminContactDetails();

        $merchantData['packageInfoByPackageId'] = $packageInfo;
        $merchantData['currency_symbol'] = '$';
        $merchantData['from_address'] = $emailData['contact_profile_admin']['email_address'];
        $merchantData['full_name'] = $emailData['contact_profile_admin']['full_name'];
        $merchantData['to_address'] = $merchantData['email_address'];
        $merchantData['subject'] = $this->lang->line('MERCHANT_ACCOUNT_PAYMENT_SUCCESS');
        $CI->Mailer_model->sendMails($merchantData, 'payment_success_to_merchant');

        $merchantData['from_address'] = $this->config->item('adminNotifyEmail');
        $merchantData['full_name'] = $this->config->item('adminNotifyEmail');
        $merchantData['to_address'] = $emailData['contact_profile_admin']['email_address'];
        $merchantData['subject'] = $this->lang->line('MERCHANT_ACCOUNT_PAYMENT_SUCCESS_TO_ADMIN');
        $CI->Mailer_model->sendMails($merchantData, 'payment_success_to_admin');

        return true;
    }

    function getTotalMerchantCount()
    {
        $sql = $_SESSION['merchant_list_sql'];
                unset($_SESSION['merchant_list_sql']);
                $res = $this->db->query($sql);
                $count = $res->num_rows();
        return $count;

    }

    function updateMerchantTablePackage($data)
    {
            if(in_array($data['package_id'], $this->config->item('cloudnet360_packages_only')))
               $white_label_id = 4;
            elseif(in_array($data['package_id'], $this->config->item('gymminder_packages')))
               $white_label_id = 2;
            else 
               $white_label_id = 1;

        $sql = "UPDATE tbl_merchant
                 SET package_id = " . $data['package_id'] . ",
                     white_label_id = '" . $white_label_id . "',
                     subscription_type = '" . $data['subscription_type'] . "',
                     signup_amount = " . $data['signup_amount'] . ",
                     is_trial = '" . $data['is_trial'] . "'
                 WHERE merchant_row_id = " . $data['merchant_row_id'];

        $this->db->query($sql);
    }

    function changeExistingPackageStatus($merchant_row_id)
    {
        $sql = " UPDATE tbl_merchant_package_history
                 SET active_status = '0' ,
                 finish_date = '" . getCurrentDateTimeForDB() . "'
                 WHERE merchant_row_id = ".$merchant_row_id ."
                 AND active_status='1'";
        $this->db->query($sql);
    }

    function saveNewpackage($data)
    {
        return $this->db->insert('tbl_merchant_package_history', $data);
    }

    function getMerchantDetailsWithPackageInfo($merchant_row_id)
    {
        $sql = "SELECT m.merchant_row_id,
                m.enc_merchant_row_id,
                m.merchant_id,
                m.first_name,
                m.last_name,
                m.company_name,
                m.email_address,
                m.public_email,
                m.user_password,
                m.merchant_contact_phone,
                m.merchant_address,
                m.merchant_city,
                m.state_province_name,
                m.merchant_zip_code,
				m.hear_about_us,
                m.merchant_postal_code,
                m.merchant_country,
                m.website_url,
                m.package_id,
                m.is_trial,
                m.subscription_type,
                m.signup_amount,
                m.active_status,
                m.last_transaction_date,
                m.no_of_fail_transaction,
                m.activation_code,
                m.activation_date,
                m.is_expires,
                m.created_by,
                m.created_on,
                m.modified_by,
                m.modified_on,
                m.merchant_referrer_id,
                m.merchant_headers_content,
                m.admin_id ,
                m.white_label_id,
                m.super_admin_note,
                p.package_name,
                p.package_number,
                p.monthly_price,
                p.monthly_price_to_show,
                p.annual_price,
                p.database_limit,
                p.client_limit,
                p.is_trial AS package_is_trial,
                p.trail_duration,
                p.trial_amount,
                p.package_description,
                p.active_status AS package_active_status,
                p.is_visible,
                p.is_chargeable
            FROM tbl_merchant AS m
            JOIN tbl_package AS p ON(m.package_id = p.package_id)
            WHERE merchant_row_id = ".$merchant_row_id;

            $result = $this->db->query($sql);
            return $result->row();
    }

    function getMerchantAPIInfo($merchantRowId, $signature = '')
    {
        $sql = 'SELECT merchant_id,
                    email_address,
                    wlm_notification_url,
                    stores_notification_url,
                    ipn_url,
                    api_signature
                FROM tbl_merchant
                WHERE merchant_row_id = ' . $merchantRowId;

        if($signature)
        {
            $sql .= ' AND api_signature = ' . $this->db->escape($signature);
        }
        $query = $this->db->query($sql);
        return $query->row();
    }

    function getMerchantInfoForAPIAuthentication($merchantId, $merchantEmail)
    {
        $sql = 'SELECT  merchant_row_id,
                        merchant_id,
                        first_name,
                        last_name,
                        company_name,
                        email_address,
                        is_expires,
                        active_status
                FROM tbl_merchant
                WHERE merchant_id = ' . $this->db->escape($merchantId) .
                'AND email_address=' . $this->db->escape($merchantEmail);

        $query = $this->db->query($sql);
        return $query->row();
    }

    function getMerchantInfoForAPIAuthenticationURL($merchantRowId)
    {
        $sql = 'SELECT  merchant_row_id,
                        merchant_id,
                        first_name,
                        last_name,
                        company_name,
                        email_address,
                        is_expires,
                        active_status,
                        package_id,
                        subscription_type,
						user_password
                FROM tbl_merchant
                WHERE merchant_row_id = ' . $this->db->escape($merchantRowId);

        $query = $this->db->query($sql);
        return $query->row();
    }

    function generateAPIInfo($merchantRowId)
    {
        $continue = true;

        do
        {
            $sign = api_encrypt($merchantRowId);

            $sql = "SELECT merchant_row_id
                    FROM tbl_merchant
                    WHERE api_signature = ". $this->db->escape( $sign );
            $q = $this->db->query($sql);
            $row = $q->row();

            if(!$row)
            {
                $this->db->where('merchant_row_id', $merchantRowId);
                $this->db->update('tbl_merchant', array('api_signature' => $sign));
                return $sign;
            }
        }while($continue);

        return '';
    }

    function getMerchantEncryptedRowId($merchantRowId)
    {
        $sql = "SELECT enc_merchant_row_id FROM tbl_merchant WHERE merchant_row_id='$merchantRowId'";
        $query = $this->db->query($sql);
        $row = $query->row();

        if($row && $row->enc_merchant_row_id)
        {
            return $row->enc_merchant_row_id;
        }
        return '';
    }

    function getMerchantRowId($encMerchantRowId)
    {
        $sql = 'SELECT merchant_row_id FROM tbl_merchant WHERE enc_merchant_row_id=' . $this->db->escape($encMerchantRowId);
        $query = $this->db->query($sql);
        $row = $query->row();

        if($row && $row->merchant_row_id)
        {
            return $row->merchant_row_id;
        }
        return 0;
    }

    function addToAutoresponder($name, $email)
    {
        if($_SERVER['HTTP_HOST'] == 'localhost')
        {
            return false;
        }

        if(empty($name) || empty($email))
        {
            return false;
        }

        $requestString = 'meta_web_form_id=1755882324'
                        . '&meta_split_id='
                        . '&listname=pwc-merchant'
                        . '&redirect=http://clients.premiumar.com/thankyou.htm?m=default'
                        . '&meta_adtracking=' . urlencode('PWC_-_Merchant_Web_Form')
                        . '&meta_message=1'
                        . '&meta_required=name,email'
                        . '&meta_tooltip='
                        . '&name=' . urlencode($name)
                        . '&email=' . urlencode($email)
                        . '&submit=Submit';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://clients.premiumar.com/scripts/addlead.pl');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $requestString);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_VERBOSE, 0);
        $headers = array("Cache-Control: no-cache", "Pragma: no-cache");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($ch);
        curl_close($ch);

        return true;
    }

    function getMerchantsCRMCharge($merchant)
    {
        if($merchant['package_id'] == $this->config->item('elite_package')
            || $merchant['package_id'] == $this->config->item('platinum_package')
            || ($merchant['package_id'] == $this->config->item('professional_package') && $merchant['subscription_type'] == $this->config->item('annual_subcription')))
        {
            $sql = 'SELECT app_key
                      FROM tbl_api_modules
                      WHERE app_id = 10011';
            $query = $this->db->query($sql);
            $row = $query->row();

            $startDate = explode(' ', $merchant['last_due_date']);
            $startDate = $startDate[0] . ' 00:00:00';

            $endDate = explode(' ', $merchant['next_charge_date']);
            $endDate = $endDate[0] . ' 23:59:59';

            $request = 'apikey=' . urlencode($row->app_key) . '&core_merchant_id=' . urlencode($merchant['merchant_id'])
                                 . '&core_start_date=' . urlencode($startDate) . '&core_end_date=' . urlencode($endDate);

            log_merchant_charges("@= Sending request to CRM for usage charge \n@= Start Date: $startDate \n@= End Date: $endDate\n@=RequestString:" . $request);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://pwccrm.com/billing/crm_package_billing.php');
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 20);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $response = curl_exec($ch);

            log_merchant_charges('CRM CHARGE RESPONSE:' . $response);

            if(curl_errno($ch))
            {
                $debugText = 'A merchants CRM charge could not be fetched due to the followin problem:' . curl_error($ch) . '(CURL Error: ' . curl_errno($ch) . ")\n@MerchantID:" . $merchant['merchant_id'];
                log_email($debugText);
                log_merchant_charges($debugText);
                return array('customers' => 0, 'emails' => 0, 'amount' => 0, 'error' => 1);
            }
            else
            {
                if(!empty($response))
                {
                    $response = explode('|', trim($response, "\n"));

                    $return = array();
                    $return['customers'] = empty($response[0]) ? 0 : $response[0];
                    $return['emails'] = empty($response[1]) ? 0 : $response[1];
                    $return['amount'] = (float) (empty($response[2]) ? 0 : $response[2]);
                    $return['start'] = $startDate;
                    $return['end'] = $endDate;
                    return $return;
                }
            }
        }
        return array('customers' => 0, 'emails' => 0, 'amount' => 0);
    }

    function saveCRMUsage($info)
    {
        $this->db->insert('tbl_crm_usage', $info);
    }

    function getMerchantForCharge($merchantRowId)
    {
        if($merchantRowId)
        {
            $sql = "SELECT  m.merchant_row_id,
                            m.merchant_id,
                            m.first_name,
                            m.last_name,
                            m.company_name,
                            mb.billing_name,
                            mb.billing_email,
                            mb.billing_phone,
                            mb.billing_company,
                            mb.billing_address,
                            mb.billing_country,
                            mb.billing_state,
                            mb.billing_city,
                            CASE mb.billing_zip_code
                            WHEN ''
                            THEN mb.billing_postal_code
                            ELSE mb.billing_zip_code
                            END AS billing_zip_code,
                            mb.card_type,
                            mb.card_number,
                            mb.card_exp_month,
                            mb.card_exp_year,
                            mb.card_holder_contactname
                    FROM tbl_merchant m
                    INNER JOIN tbl_merchant_billing mb ON mb.merchant_row_id = m.merchant_row_id
                    WHERE m.merchant_row_id = $merchantRowId";
            $query = $this->db->query($sql);
            return $query->row_array();
        }
    }
  function saveUserProfile($merchantUserInfo)
  {
      if($merchantUserInfo['merchant_row_id'] > 0)
      {
          $this->db->where('merchant_row_id', $merchantUserInfo['merchant_row_id']);
          $this->db->update('tbl_merchant', $merchantUserInfo);
      }
      else
      {

         $this->db->insert('tbl_merchant', $merchantUserInfo);
         $merchantUserInfo['merchant_row_id'] = $this->db->insert_id();
      }
      return $merchantUserInfo['merchant_row_id'];
  }

  function getMerchantByRowId($merchant_row_id, $isCoach = null)
  {
   $sql = 'SELECT m.merchant_row_id,
                       m.merchant_id,
                       m.first_name,
                       m.last_name,
                       m.email_address,
                       m.is_expires,
                       m.subscription_type,
                       m.package_id,
                       m.parent_merchant_row_id,
                       p.is_chargeable,
                       DATEDIFF(\'' . date('Y-m-d') . '\', DATE_FORMAT(m.last_transaction_date, \'%Y-%m-%d\')) AS day_count_last_trans,
                       m.no_of_fail_transaction,
                       m.show_system_message,
                       m.free_charge_product_row_id,
                       m.stores_site_url,
                       m.white_label_id,
                       m.user_type,
                       m.access_staff_view,
                       m.access_crm,
                       m.access_project_manager,
                       m.access_ticket_system,
                       m.access_live_chat,
                       m.access_members_pro,
                       m.access_pwc,
                       m.time_zone
               FROM tbl_merchant AS m JOIN
               tbl_package AS p ON(p.package_id = m.package_id)
               WHERE m.merchant_row_id =' . $merchant_row_id.'';
        $resultSet = $this->db->query ( $sql );
        return $resultSet->row ();

  }
 function checkBackupCardExist($merchant_row_id)
 {
   if($merchant_row_id)
   {
        $sql = "SELECT card_type_1, card_number_1, card_exp_month_1, card_exp_year_1, card_holder_contactname_1 FROM tbl_merchant_billing
        WHERE merchant_row_id = $merchant_row_id";

       $result = $this->db->query($sql);
       $row = $result->row();

       if($row->card_type_1 && $row->card_type_1 && $row->card_exp_month_1 && $row->card_exp_year_1 && $row->card_holder_contactname_1)
       {
            return true;
       }
   }
   return false;
 }

 function saveUpgradePackage_billInfoForm($billingInformation)
 {
 	$this->db->where ( 'merchant_row_id', $billingInformation ['merchant_row_id'] );
 	$this->db->update ( 'tbl_merchant_billing', $billingInformation );
 }

 function getUserLists()
 {
     if($_SESSION['user_type'] == 1)
     {
       $sql = 'SELECT  merchant_row_id, 
                       first_name, 
                       last_name, 
                       email_address, 
                       user_password_normal, 
                       CASE user_type WHEN 1 THEN "Super Admin"  WHEN 2 THEN "Admin" WHEN 3 THEN "User" WHEN 4 THEN "Coach" END as userType, 
                       CASE active_status  WHEN 1 THEN "Active" WHEN 0 THEN "Inactive" END as activeStatus,
                       CASE user_type
                       WHEN 1 THEN \'\'
                       ELSE \'' . GRID_DELETE_IMG . '\'
                       END AS delete_icon,
                       CASE user_type
                       WHEN 1 THEN \'' . GRID_PASSWORD_IMG . '\'
                       ELSE \'\'
                       END AS password_icon
                       FROM tbl_merchant WHERE parent_merchant_row_id = ' . getCurrentMerchantId() . ' OR merchant_row_id = ' . getCurrentMerchantId() . ' ORDER BY user_type, first_name' ;
    }
    else
    {
       $sql = 'SELECT  merchant_row_id, 
                       first_name, 
                       last_name, 
                       email_address, 
                       user_password_normal, 
                       CASE user_type WHEN 1 THEN "Super Admin"  WHEN 2 THEN "Admin" WHEN 3 THEN "User" WHEN 4 THEN "Coach" END as userType, 
                       CASE active_status  WHEN 1 THEN "Active" WHEN 0 THEN "Inactive" END as activeStatus, 
                       CASE user_type
                       WHEN 1 THEN \'\'
                       ELSE \'' . GRID_DELETE_IMG . '\'
                       END AS delete_icon,
                       CASE user_type
                       WHEN 1 THEN \'' . GRID_PASSWORD_IMG . '\'
                       ELSE \'\'
                       END AS password_icon
                       FROM tbl_merchant WHERE created_by = ' . $_SESSION['merchant_child_id'] . ' ORDER BY user_type, first_name';
    }
    $sql = '('.$sql.' ) AS abc';
    $this->load->library ( 'rapyd' );
    $this->rapyd->load('datagrid');
    $grid = new DataGrid('', $sql);
    $grid->removeHash = true;
    $grid->per_page = $this->config->item('rows_per_page');
    $grid->column('First Name', 'first_name', 'align="left" width="150"');
    $grid->column('Last Name', 'last_name', 'align="left" width="150"');
    $grid->column('Email Address', 'email_address', 'align="left" ');
    $grid->column('User Type', 'userType', 'align="left" width="90"');
    $grid->column('Active Status', 'activeStatus', 'align="left" width="90"');
    $grid->column_detail('Action', GRID_EDIT_IMG , 'merchant/userProfile/<#merchant_row_id#>', 'align="center" width="30"', false, 'class="block_page"', true, 'colspan="3" width="15" align="center"');
    $grid->column_detail('Delete', '<#delete_icon#>', 'merchant/deleteUser/<#merchant_row_id#>.html"', 'align="left" width="15"', false, 'onclick = "return checkDelete();"', false);         
    $grid->column_detail('Change Password', '<#password_icon#>', 'merchant/userProfile/<#merchant_row_id#>/0/changePassword.html"', 'align="left" width="16"', false, '', false, '', false);         
    
    $grid->build();
    return $grid->output;
 }

 function deleteUser($merchantRowId) {

     if(!$merchantRowId)
     return false;
     $sql = "DELETE FROM tbl_merchant WHERE merchant_row_id = " . $merchantRowId . " AND user_type != 1";
     $this->db->query($sql);
 }

 function isValidAccount($account_row_id, $merchant_row_id) {

     if($account_row_id && $merchant_row_id) {
        $sql = 'SELECT merchant_row_id FROM tbl_merchant WHERE merchant_row_id = ' . $account_row_id . ' AND parent_merchant_row_id = ' . $merchant_row_id;
        $query = $this->db->query($sql);
        if($query->num_rows())
        return true;
     }

     return false;
 }
 
 function addBlackListIP()
 {
     $data['ip_address'] = $_SERVER['REMOTE_ADDR'];
     $data['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
     $data['added_on']   = date('Y-m-d H:i:s');
     $this->db->insert('tbl_signup_blacklist_ip', $data);
 }
                                                                       
 function getBlackListByIP($ipAddress)
 {
     $sql = "SELECT *FROM tbl_signup_blacklist_ip WHERE ip_address = '{$ipAddress}'";
     $query = $this->db->query($sql);
     return $query->result_array();
 }
 
    function createWePayMerchantAccount($merchant)
    {                                                                  
        $getInstance = &get_instance();
        $getInstance->load->model('paymentModel/Payment_model', 'Payment_model', TRUE);
        $getInstance->load->model('carts/Cart_Setup_model', 'Cart_Setup_model', true);
        $processor = $getInstance->Payment_model->getPaymentProcessor($this->config->item('payment_gateway_wepay'));
        $processor->setFirstName($merchant['first_name']);
        $processor->setLastName($merchant['last_name']);
        $processor->setEmail($merchant['email_address']);
        $processor->setIPAddress($getInstance->Payment_model->ipAddress);

        if($this->config->item('test_mode'))
            $processor->enableTestMode();

        $response = $processor->processor->registerAccount();

        if(!$response->access_token)
        {
           log_general('createWePayMerchantAccount::' . print_r($response, 1));
           return false;
        }
        $processor->processor->token = $access_token = $response->access_token;
        $userId = $response->user_id;
        $processor->setNote('This merchant account is associated with shopping cart(CloudNet360/PWC).'); 
        $response  = $processor->processor->createAccount();
        
        if($response->success)
        {
            $accountId = $response->account_id;
            $gatewaySetupData['merchant_row_id'] = $merchant['merchant_row_id'];
            $gatewaySetupData['nick_name'] = 'WePay'; 
            $gatewaySetupData['real_time_gateway'] = $this->config->item('payment_gateway_wepay');
            $gatewaySetupData['real_time_currency'] = 'USD';
            $gatewaySetupData['cvv2_required'] = 1;
            $gatewaySetupData['authorize_api_login_key'] = $accountId;
            $gatewaySetupData['authorize_api_transaction_key'] = $access_token;
            $getInstance->Cart_Setup_model->savePaymentGatewaySetup($gatewaySetupData, true);
            //$getInstance->Cart_Setup_model->activatePaymentGateway($merchant['merchant_row_id'], $gatewaySetupData['real_time_gateway'], 2, 1);  
            $processor->processor->sendMerchantAccountConfirmation();        
        }
    }

}
?>