<?php
class Signup extends MY_Controller {

    var $trialPackage = 34;
    public function __construct()
    {
        /*
        parent::__construct();
        $this->load->model ( 'merchant/Merchant_model', 'Merchant_model', TRUE );
        
        if(count($this->Merchant_model->getBlackListByIP($_SERVER['REMOTE_ADDR'])) >= 2)
        {
            if(isPostBack() && $this->input->post('card_number'))
               die('BLACKLIST;BLACKLIST');
            else   
               external_redirect('http://www.premiumwebcart.com/main/signup_error.html');
        }
        */
    }

    function index()
    {                                                 
       die('here I am Sir');
    }                                                                                        

    function showPackageList()
    {
        external_redirect('http://www.premiumwebcart.com/try-it-today.html');
        $this->load->model ( 'administration/package_model', 'Package_model', TRUE );
        $data ['packageList'] = $this->Package_model->getActivePackages();
        $data['content'] = $this->load->view ( 'package_list', $data, true);
        $this->load->view('template_front', $data);
    }
    
    function getFreeTrial($fromSales)
    {
        $_SESSION['free_trial'] = true;
        $_SESSION['popup_displayed'] = true;
        if($fromSales)
           redirect('signup/showSignupForm/' . $this->trialPackage); 
    }

    function showSignupForm($package_id = null)
    {
        $this->load->model ( 'administration/package_model', 'Package_model', TRUE );
        $whiteLabelId = $_SESSION['white_label_id'];   
        $_SESSION['white_label_id'] = $this->input->post('white_label_id') ? $this->input->post('white_label_id') : 1;
        
        if(!$package_id)
        {
            $package_id = $this->input->post ( 'package_id', TRUE );
        }

        if($package_id)
        {
            $data['packageInfo'] = $this->Package_model->getPackage ( $package_id );
        }
        if($data ['packageInfo'])
        {
            $data['subscription_type'] = $this->input->post ( 'subscription_type', TRUE );
            $this->load->model ( 'administration/admin_user_model', 'Admin_user_model', TRUE );

            $data ['first_name'] = '';
            $data ['last_name'] = '';
            $data ['company_name'] = '';
            $data ['email_address'] = '';
            $data ['login_password'] = '';
            $data ['merchant_contact_phone'] = '';
            $data ['merchant_address'] = '';
            $data ['merchant_city'] = '';
            $data ['merchant_zip_code'] = '';
            $data ['merchant_postal_code'] = '';
            $data ['website_url'] = '';
            $data ['active_status'] = '';
            $data ['created_by'] = '';
            $data ['created_on'] = '';
            $data ['modified_by'] = '';
            $data ['modified_on'] = '';
            $data ['merchant_country'] = '';
            $data ['state_province_name'] = '';
            $data ['is_sign_up_page'] = 1;

            if($data['packageInfo']['is_trial'] && $data['packageInfo']['trial_amount'] > 0)
            {
                $data['price'] = $data['packageInfo']['trial_amount'];
                $data['package_name'] = $data['packageInfo']['package_name'];
            }
            else if($data['subscription_type'] == 1)
            {
                $data['price'] = $data['packageInfo']['monthly_price'] + $data['packageInfo']['setup_fee'];
                $data['package_name'] = $data['packageInfo']['package_name'] . ' - Monthly';
            }
            else if($data['subscription_type'] == 2)
            {
                $data['price'] = $data['packageInfo']['annual_price'] + $data['packageInfo']['setup_fee'];
                $data['package_name'] = $data['packageInfo']['package_name'] . ' - Annually';
            }
            $data['content'] = $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/signup_step_1', $data, true );
            $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/template_signup', $data );
        }
        else
        {
            if ($whiteLabelId == 2)
                external_redirect('http://www.gymminder.com/pricing.html');
            else if ($whiteLabelId == 4)
                external_redirect('http://cloudnet360.com/try-it-today.html');
            else
                external_redirect('http://www.premiumwebcart.com/try-it-today.html');     
        }
    }

    function showCheckout()
    {
        $data['first_name']          = $this->input->post ( 'first_name', TRUE );
        $data['last_name']           = $this->input->post ( 'last_name', TRUE );
        $data['company_name']        = $this->input->post ( 'company_name', TRUE );
        $data['merchant_address']    = $this->input->post ( 'merchant_address', TRUE );
        $data['merchant_city']       = $this->input->post ( 'merchant_city', TRUE );
        $data['merchant_country']    = $this->input->post ( 'merchant_country', TRUE );
        $data['state_province_name'] = $this->input->post ( 'state_province_name', TRUE );
        $data['merchant_zip_code']      = $this->input->post ( 'merchant_zip_code', TRUE );
        $data['email_address']          = $this->input->post ( 'email_address', TRUE );
        $data['login_password']         = $this->input->post ( 'login_password', TRUE );
        $data['confirm_password']       = $this->input->post ( 'confirm_password', TRUE );
        $data['merchant_contact_phone'] = $this->input->post ( 'merchant_contact_phone', TRUE );
        $data['address_location']       = $this->input->post ( 'address_location', TRUE );
        $data['phone_type']             = $this->input->post ( 'phone_type', TRUE );
        $data['website_url']            = $this->input->post ( 'website_url', TRUE );
        $data['hear_about_us']          = $this->input->post ( 'hear_about_us', TRUE );

        $this->load->library ( 'validation' );
        $rules ['first_name'] = "trim|required";
        $rules ['last_name'] = "trim|required";
        $rules ['email_address'] = "trim|required|valid_email";
        $rules ['login_password'] = "trim|required|min_length[6]";
        $rules ['confirm_password'] = "trim|required|min_length[6]";
        $rules ['merchant_contact_phone'] = "trim|required";
        $rules ['merchant_address'] = "trim|required|max_length[200]";
        $rules ['merchant_city'] = "trim|required";
        $rules ['merchant_country'] = "trim|required";
        $this->validation->set_rules ( $rules );

        $fields ['first_name'] = "First name";
        $fields ['last_name'] = "Last name";
        $fields ['email_address'] = "Email";
        $fields ['login_password'] = "Password";
        $fields ['confirm_password'] = "Confirm Password";
        $fields ['merchant_contact_phone'] = "Contact Phone";
        $fields ['merchant_address'] = "Address";
        $fields ['merchant_city'] = "City";
        $fields ['merchant_country'] = "Country";

        $this->validation->set_fields ( $fields );
        $this->validation->set_error_delimiters ( '<div class="error">', '</div>' );

        $this->load->model ( 'administration/package_model', 'Package_model', TRUE );
        $data['package_id'] = $this->input->post ( 'package_id', TRUE );
        $data['subscription_type'] = $this->input->post ( 'subscription_type', TRUE );
        $data ['packageInfo'] = $this->Package_model->getPackage ( $data['package_id'] );

        $this->load->model ( 'administration/admin_user_model', 'Admin_user_model', TRUE );
        $paymentGateway = $this->Admin_user_model->getAdminGatewaySetup();
        $data['credit_cards_selected'] = $paymentGateway->credit_cards_selected;

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

        if ($this->validation->run () == FALSE)
        {
            exception($this->validation->error_string);
            $data['content'] = $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/signup_step_1', $data, true );
            $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/template_signup', $data );
            return ;
        }

        $this->load->model ( 'Merchant_Signup_model', 'Merchant_Signup_model', TRUE );

        if ($this->Merchant_Signup_model->checkDuplicateEmail ( $this->input->post ( 'email_address', true ) ))
        {
            exception('This user is already registered');
            $data['content'] = $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/signup_step_1', $data, true );
            $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/template_signup', $data );
            return ;
        }

        $data['content'] = $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/signup_step_2', $data, true );
        $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/template_signup', $data );
    }


    function getAutoSignUpAffInfo($data)
    {
        $info['affiliate_name']       = $data['first_name'] . ' ' . $data['last_name'];
        $info['affiliate_company']    = $data['company_name'];
        $info['affiliate_email']      = $data['email_address'];
        $info['affiliate_password']   = $this->input->post ( 'login_password', true );
        $info['affiliate_home_phone'] = $data['merchant_contact_phone'];
        $info['affiliate_address1']   = $data['merchant_address'];
        $info['affiliate_city']       = $data['merchant_city'];
        $info['affiliate_state']      = $data['state_province_name'];
        $info['affiliate_zip']        = $data['merchant_zip_code'];
        $info['affiliate_country']    = $data['merchant_country'];
        $info['affiliate_country']    = $data['merchant_country'];
        $info['admin_user_id']        = 1;
        $info['join_status']          = 2;
        return $info;
    }

    function optSaveMerchant()
    {
        $this->load->model ( 'Merchant_Signup_model', 'Merchant_Signup_model', TRUE );
        $this->load->library ( 'validation' );

        $rules ['card_type'] = "trim|required";
        $rules ['card_number'] = "trim|required";
        $rules ['card_exp_month'] = "trim|required";
        $rules ['card_exp_year'] = "trim|required";
        $rules ['card_holder_contactname'] = "trim|required";

        $rules['billing_address']   = 'trim|required';
        $rules['billing_city']      = 'trim|required';
        $rules['billing_country']   = 'trim|required';
        $rules['billing_state']     = 'trim|required';
        $rules['billing_zip_code']  = 'trim|required';

        $this->validation->set_rules ( $rules );

        $fields ['card_type'] = "Card Type";
        $fields ['card_number'] = "Card Number";
        $fields ['card_exp_month'] = "Expiration (Month)";
        $fields ['card_exp_year'] = "Expiration (Year)";
        $fields ['card_holder_contactname'] = "Name on Card";

        $fields['billing_address']   = 'Billing Address';
        $fields['billing_city']      = 'Billing City';
        $fields['billing_country']   = 'Billing Country';
        $fields['billing_state']     = 'Billing State';
        $fields['billing_zip_code']  = 'Billing Zip Code';

        $this->validation->set_fields ( $fields );
        $this->validation->set_error_delimiters ( '<div class="error">', '</div>' );
        $this->load->helper ( 'security' );

        $data['first_name']          = $this->input->post ( 'first_name', TRUE );
        $data['last_name']           = $this->input->post ( 'last_name', TRUE );
        $data['merchant_address']    = $this->input->post ( 'merchant_address', TRUE );
        $data['merchant_city']       = $this->input->post ( 'merchant_city', TRUE );
        $data['merchant_country']    = $this->input->post ( 'merchant_country', TRUE );
        $data['state_province_name'] = $this->input->post ( 'state_province_name', TRUE );
        $data['merchant_zip_code']      = $this->input->post ( 'merchant_zip_code', TRUE );
        $data['email_address']          = $this->input->post ( 'email_address', TRUE );
        $data['login_password']         = $this->input->post ( 'login_password', TRUE );
        $data['confirm_password']       = $this->input->post ( 'confirm_password', TRUE );
        $data['merchant_contact_phone'] = $this->input->post ( 'merchant_contact_phone', TRUE );

        $data ['first_name'] = $this->input->post ( 'first_name', TRUE );
        $data ['last_name'] = $this->input->post ( 'last_name', TRUE );
        $data ['company_name'] = $this->input->post ( 'company_name', TRUE );
        $data ['email_address'] = $this->input->post ( 'email_address', TRUE );
        $userPassword = $this->input->post ( 'login_password', true );
        $data ['user_password'] = dohash ( $userPassword, 'md5' );
        $data ['merchant_contact_phone'] = $this->input->post ( 'merchant_contact_phone', TRUE );
        $data ['merchant_address'] = $this->input->post ( 'merchant_address', TRUE );
        $data ['merchant_city'] = $this->input->post ( 'merchant_city', TRUE );
        $data ['state_province_name'] = $this->input->post ( 'state_province_name', TRUE );
        $data ['merchant_zip_code'] = $this->input->post ( 'merchant_zip_code', TRUE );
        $data ['phone_type']             = $this->input->post ( 'phone_type', TRUE );
        $data ['address_location']       = $this->input->post ( 'address_location', TRUE );
        $data ['website_url']            = $this->input->post ( 'website_url', TRUE );
        $data ['hear_about_us']          = $this->input->post ( 'hear_about_us', TRUE );

        $data ['merchant_country'] = $this->input->post ( 'merchant_country', TRUE );
        $data ['package_id'] = $this->input->post ( 'package_id', TRUE );
        $data ['is_trial'] = $this->input->post ( 'is_trial', TRUE );
        $data ['activation_code'] = dohash ( rand ( 22334, 98765 ), 'md5' );
        $data ['admin_id'] = 1; //for Gary only

        $data ['subscription_type'] = $this->input->post ( 'subscription_type', true );
        $data ['card_type'] = $this->input->post ( 'card_type', true );
        $data ['card_number'] = $this->input->post ( 'card_number', true );
        $data ['card_exp_month'] = $this->input->post ( 'card_exp_month', true );
        $data ['card_exp_year'] = $this->input->post ( 'card_exp_year', true );
        $data ['card_holder_contactname'] = $this->input->post ( 'card_holder_contactname', true );

        $data['billing_address']   = $this->input->post ( 'billing_address', TRUE );
        $data['billing_city']      = $this->input->post ( 'billing_city', TRUE );
        $data['billing_country']   = $this->input->post ( 'billing_country', TRUE );
        $data['billing_state']     = $this->input->post ( 'billing_state', TRUE );
        $data['billing_zip_code']  = $this->input->post ( 'billing_zip_code', TRUE );

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

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

        $this->load->model ( 'administration/package_model', 'Package_model', TRUE );
        $packageInfo = $this->Package_model->getPackage ( $data ['package_id'] );
        $data['packageInfo'] = $packageInfo ;
        if($data['packageInfo']['is_trial'] && $data['packageInfo']['trial_amount'] > 0)
        {
            $data['price'] = $data['packageInfo']['trial_amount'];
            $data['package_name'] = $data['packageInfo']['package_name'];
        }
        else if($data['subscription_type'] == 1)
        {
            $data['price'] = $data['packageInfo']['monthly_price'] + $data['packageInfo']['setup_fee'];
            $data['package_name'] = $data['packageInfo']['package_name'] . ' - Monthly';
        }
        else if($data['subscription_type'] == 2)
        {
            $data['price'] = $data['packageInfo']['annual_price'] + $data['packageInfo']['setup_fee'];
            $data['package_name'] = $data['packageInfo']['package_name'] . ' - Annually';
        }

        if ($this->validation->run () == FALSE)
        {
            exception($this->validation->error_string);
            die('ERROR;'.'VALIDATION;'.$this->validation->error_string);
            $data ['packageInfo'] = $packageInfo;
            $data['content'] = $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/signup_step_2', $data, true );
            $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/template_signup', $data );
            return ;
        }

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

        if ($isCardNumberValid == NULL || $isExpired == NULL)
        {
            if (! $isCardNumberValid && ! $isExpired)
            {
                exception($error_text);
                die('ERROR;'.'ERROR;'.$error_text);
            }
            elseif (! $isExpired)
            {
                exception($this->lang->line ( 'EXPIRE_DATE' ));
                die('ERROR;'.'ERROR;'.$this->lang->line ( 'EXPIRE_DATE' ));
            }
            else
            {
                exception($error_text);
                die('ERROR;'.'ERROR;'.$error_text);
            }
            $data ['packageInfo'] = $packageInfo;
            $data['content'] = $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/signup_step_2', $data, true );
            $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/template_signup', $data );
            return;
        }
        else
        {
            if(($packageInfo['is_trial']))
            {
                $data ['signup_amount'] = $signupAmount = ($packageInfo['trial_amount'] > 0 && !$_SESSION['free_trial']) ? $packageInfo['trial_amount'] : '0.01';
                $data ['subscription_type'] = '0';
                $nextBillingDate = date('Y-m-d H:i:s', time() + 2592000);
            }
            else
            {
                if ($data ['subscription_type'] == $this->config->item ( 'monthly_subcription' ))
                {
                    $data ['signup_amount'] = $signupAmount = $packageInfo ['monthly_price'] + $packageInfo['setup_fee'];
                    
                    if($_SESSION['free_trial'])
                       $data ['signup_amount'] = '0.01'; 
                       
                    $nextBillingDate = date('Y-m-d H:i:s', time() + 2592000);
                }
                else
                {
                    $data ['signup_amount'] = $signupAmount = $packageInfo ['annual_price'] + $packageInfo['setup_fee'];
                    $nextBillingDate = date('Y-m-d H:i:s', time() + 31536000);
                }
            }
            $data['description'] = 'Merchant Signup fee on '.$this->config->item('project_name');

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


            $merchantData['merchant_address'] = $data['billing_address'];
            $merchantData['billing_city'] = $data['billing_city'];
            $merchantData['billing_country'] = $data['billing_country'];
            $merchantData['billing_state'] = $data['billing_state'];
            $merchantData['billing_zip_code'] = $data['billing_zip_code'];
            $paymentDetails = $this->Payment_model->chargeForMerchantSignUp($merchantData, $paymentGateway, 1);

            if (! $paymentDetails ['success'])
            {
                $this->Merchant_model->addBlackListIP();
                if(count($this->Merchant_model->getBlackListByIP($_SERVER['REMOTE_ADDR'])) >= 2)
                {
                   die('BLACKLIST;'.$paymentDetails ['error_text']);
                }        
                $debugText = 'Merchant Sign Up Failed.<br />
                              Reason:' . $paymentDetails ['error_text'];
                log_email($debugText);

                exception($paymentDetails ['error_text']);
                die('ERROR;'.'ERROR;'.$paymentDetails ['error_text']);
                $data ['packageInfo'] = $packageInfo;
                $data['content'] = $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/signup_step_2', $data, true );
                $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/template_signup', $data );
                return;
            }
            else
            {
                $data['active_status'] = 1;
                $data ['renew_date'] = $data ['last_transaction_date']
                                     = $data ['last_due_date']
                                     = $paymentDetails ['date_of_transaction']
                                     = getCurrentDateTimeForDB();
                $data['next_charge_date'] = $nextBillingDate;
            }
        }

        $data['activation_date'] = $data ['last_transaction_date'];

        $this->load->helper('cookie');
        $cookieString = 'admin_affiliate_cookie_'.md5($data['admin_id']);
        $affiliate_cookie = unserialize(stripslashes($this->input->cookie($cookieString)));
        $enc_affiliate_row_id = $affiliate_cookie[0];
        $this->load->model('administration/Admin_affiliate_signup_model', 'admin_affiliate_signup_model', TRUE);
        $affiliateInfo = $this->admin_affiliate_signup_model->getAdminAffDetailsByEncAffRowId($enc_affiliate_row_id);
        $data['merchant_referrer_id'] = $affiliateInfo['admin_affiliate_row_id'];

        $data['white_label_id'] = $_SESSION['white_label_id'];
        $data ['signup_amount'] = $signupAmount - $packageInfo['setup_fee'];
        $data ['merchant_row_id'] = $paymentDetails ['merchant_row_id'] = $this->Merchant_Signup_model->saveMerchant ( $data );

        //Saving Payment Details
        $this->load->model('scheduleJob/Recurring_Payment_model', 'Recurring_Payment_model', TRUE );
        $this->Recurring_Payment_model->savePaymentDetails ( $paymentDetails );

        $_SESSION['affiliate_info'] = $this->getAutoSignUpAffInfo($data);

        $this->load->model ( 'merchant/Merchant_model', 'Merchant_model', TRUE );
        $this->Merchant_model->updateProfile(array('merchant_row_id' => $data ['merchant_row_id'],
                                                    'enc_merchant_row_id' => md5($data ['merchant_row_id'])));

        //Add Default Affiliate Program for Merchant(Added by Alauddin)
        $this->load->model('affiliateAdmin/Affiliate_Setup_model', 'affiliate_setup_model', TRUE);
        $info['program_name']        = 'Default Affiliate Program';
        $info['program_description'] = 'Default Affiliate Program';
        $info['merchant_row_id'] = $data['merchant_row_id'];
        $info['is_default'] = 1;
        $merchant_aff_program_row_id = $this->affiliate_setup_model->saveMerchantAffiliateProgram($info);

        //Insert program specific affiliate link(tbl_ads_program_specific_affiliate_link) Added By Alauddin
        $progam_name = $info['program_name'];
        $temp  = explode(' ',$progam_name);
        $count = count($temp);
        $name  = '';
        for($i = 0; $i < $count; $i++)
        {
            if($i != 0)
                $name .= '-' . $temp[$i];
            else
                $name .= $temp[$i];
        }
        $generated_link = BASEURL.'affProgram/'.$name.'/';
        $programData['merchant_row_id'] = $data['merchant_row_id'];
        $programData['merchant_aff_program_row_id'] = $merchant_aff_program_row_id;
        $programData['generated_link'] = $generated_link;
        $programData['created_on'] = getCurrentDateTimeForDB();
        $this->affiliate_setup_model->saveProgramSpecificLink($programData);
        //End here

        /* Saving Affiliate Manager Profile */
        $this->affiliate_setup_model->copyToAffiliateManagerProfile($data ['merchant_row_id']);

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

        //add to auto responder
        $merchantFullName = $data ['first_name'] . ' ' . $data ['last_name'];
        $this->Merchant_model->addToAutoresponder($merchantFullName, $data ['email_address']);

        #-----------------------------------Save Default Approval and Notification setup--------------------------------
        $notification_data['merchant_row_id']=$data['merchant_row_id'];

        $notification_data['aff_signup_url'] = BASEURL . 'affSignUp/'.$notification_data['merchant_row_id'].'.html';
        $notification_data['aff_login_url']  = BASEURL . 'affLogin/'.$notification_data['merchant_row_id'].'.html';
        $notification_data['default_destination_url'] = $data ['website_url'] ? $data ['website_url'] : $this->config->item('project_url');
        $notification_data['aff_admin_url'] = $data ['email_address'];
        $notification_data['sales_notification'] = 1;
        $notification_data['zero_commision_sales_notification'] = 0;
        $notification_data['signup_notification'] = 1;
        $notification_data['show_client_info'] = 1;

        $this->load->model('affiliateAdmin/Affiliate_Setup_model', 'affiliate_setup_model', TRUE);
        $this->affiliate_setup_model->saveNotificationForDefault($notification_data);
        #-----------------------------------End Default Approval and Notification setup-------------------------------------
        #-----------------------------------Save Default Email setup-------------------------------------------------------
        $this->load->model('Mail_Manager_model', 'Mail_Manager_model', TRUE);
        $this->Mail_Manager_model->copyMailsForNewMerchant($data['merchant_row_id']);
        #-----------------------------------End Default Email setup-------------------------------------------------------

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

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

        #********************************Sends mail to PremiumAR************************************
        $this->load->model('administration/basic_setup_model','Basic_Setup_model',TRUE);
        $adminBasicData = $this->Basic_Setup_model->getAdminBasicSetup(1);

        if($adminBasicData->merchant_autoresponder_email)
        {
            $data['from_address'] = $this->config->item('autoresponder_form_email_address');
            $data['to_address'] = $adminBasicData->merchant_autoresponder_email;
            $data['subject'] = 'Add email to Auto Responder';
            $this->Mailer_model->sendMails($data, 'merchant_ar');
        }
        #********************************Sends mail to PremiumAR************************************
        #****************************Super Admin Affiliate Commission Calculation-start*******************#

        $this->load->model('administration/Admin_affiliate_program_setup_model', 'admin_affiliate_program_setup_model', true);
        $this->admin_affiliate_program_setup_model->saveAdminAffiliateCommission($data['merchant_row_id'], $data ['package_id']);
        #****************************Super Admin Affiliate Commission Calculation-end*********************#

        #******************************** Notifying Merchant PRO Starts ************************************#
        $enableMembersPro = $this->config->item('enable_member_pro_notification');
        //$enableMembersLite = $this->config->item('enable_member_lite_notification');
        $enableAdvertising = $this->config->item('enable_advertising_notification');
        $enableCRM = $this->config->item('enable_crm_notification');
        $enableProject = $this->config->item('enable_project_notification');

        $this->load->model('products/category_model', 'Category_model', true);

        /*
        //Add scheduling category for merchant
        $cat = array('merchant_row_id' => $data['merchant_row_id'],
                    'category_description' => 'Scheduling System',
                    'level' => 1,
                    'is_editable' => 0,
                    'create_date' => getCurrentDateTimeForDB());
        $scheduleCategory = $this->Category_model->addCategory($cat);*/
        //Add Scheduling Product
        $this->load->model('products/Product_model', 'product', TRUE);
        $product['product_description'] = 'Scheduling Product - Edit Please';
        $product['product_price']  = 10;
        $product['redirect_to_cp'] = 1;
        $product['unit_credit']    = 1;
        $product['category_id'] = $this->config->item('schedule_category_id');
        $product['merchant_row_id'] = $data['merchant_row_id'];
        $product['created_by'] =  $data['merchant_row_id'];
        $this->product->saveProduct($product);

        $cat = array('merchant_row_id' => $data['merchant_row_id'],
                    'category_description' => 'Membership Pro',
                    'level' => 1,
                    'is_editable' => 0,
                    'create_date' => getCurrentDateTimeForDB());
        $memberShipProCategory = $this->Category_model->addCategory($cat);
        /*
        $cat = array('merchant_row_id' => $data['merchant_row_id'],
                    'category_description' => 'Membership Lite',
                    'level' => 1,
                    'is_editable' => 0,
                    'create_date' => getCurrentDateTimeForDB());
        $memberShipLiteCategory = $this->Category_model->addCategory($cat);
        */
        $cat = array('merchant_row_id' => $data['merchant_row_id'],
                            'category_description' => 'Task Manager',
                            'level' => 1,
                            'is_editable' => 0,
                            'create_date' => getCurrentDateTimeForDB());
        $taskManagerCategory = $this->Category_model->addCategory($cat);

        if($enableMembersPro || $enableAdvertising || $enableCRM || $enableProject)
        {
            $merchant = $this->Merchant_model->getMerchant($data['merchant_row_id']);

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

            $this->load->model('api/notification_model', 'Notification_model', true);

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

            if($enableCRM)
            {
                $this->Notification_model->sendMerchantSignUpNotificationToCRM($notification);
            }

            if($enableProject)
            {
                $this->Notification_model->sendStaffProfileNotification($data['merchant_row_id']);
            }
            
        }
        //Create WePay Merchant Account
        $this->Merchant_model->createWePayMerchantAccount($data);
        #******************************** Notifying Merchant PRO Ends   ************************************#

        // ADDED BY ATC FOR ADDING DEFAULT FULFILLMENT COMPANY TO MERCHANT STARTS//
        $this->load->model('shipping/Shipping_model','shipping_model',TRUE);
        $company_id = $this->shipping_model->insert_fulfillment_company_data($data['merchant_row_id']);
        $this->shipping_model->insert_fulfillment_user_data($data['merchant_row_id'], $company_id);

        // ADDED BY ATC ENDS//

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

        if($paymentDetails)
        {
            $_SESSION['p_w'] = $userPassword; // password
            $_SESSION['m_i'] = $data['merchant_row_id'];
            unset($_SESSION['exception']);
            die('OK;'.'SUCCESS;'.'SUCCESS');
        }
        else
        {
            $this->Mailer_model->sendActivationEmail ( $data );
            unset($_SESSION['exception']);
            die('OK;'.'ACTIVATION;'.'ACTIVATION');
        }
    }

    function account_success()
    {
        //$_SESSION['p_w'] = 'foobar';
        //$_SESSION['m_i'] = 6308;
        if(isset($_SESSION['p_w']))
        {
            $merchant_row_id = $_SESSION['m_i'];

            if($merchant_row_id)
            {
                $data = $this->premiumSuiteUserCreate($merchant_row_id);

                $data['merchantDetails'] = $this->Merchant_model->getMerchantDetails($merchant_row_id);
                $data['merchantDetails']->user_password = $_SESSION['p_w'];

                unset($_SESSION['p_w']);

                $this->load->model('administration/contact_profile_model','Contact_Profile_model',TRUE);
                $data['contact_profile'] = $this->Contact_Profile_model->getSuperAdminContactDetails();

                $data['from_address'] = $data['contact_profile']['email_address'];
                $data['full_name'] = $data['contact_profile_admin']['full_name'];
                $data['to_address'] = $data['merchantDetails']->email_address;
                $data['first_name'] = $data['merchantDetails']->first_name;
                $data['user_name'] = $data['merchantDetails']->email_address;
                $data['user_password'] = $data['merchantDetails']->user_password;

                $this->load->model ( 'mailData/Mailer_model', 'Mailer_model', TRUE );
                $emailInfo = $this->Mailer_model->getAdminCustomEmailInfo(1017);
                $data['subject'] = $emailInfo['email_subject'];
                $data['body'] = $this->Mailer_model->getMailBody($data, $emailInfo['email_body']);
                $this->Mailer_model->sendCustomizedMails($data);

                switch($_SESSION['white_label_id'])
                {
                   case 1 : 
                     $data['login_url'] = 'showLogin';
                     break;
                   case 2 : 
                     $data['login_url'] = 'showGymminderLogin';
                     break;
                   case 3 : 
                     $data['login_url'] = 'showMMGLogin';
                     break;
                   case 4 : 
                     $data['login_url'] = 'showcn360Login';
                     break;
                }
                $data['content'] = $this->load->view('account_success',$data, true);
                $data['useConvertionScripts'] = 1;
                
                if($_SESSION['white_label_id'] == 1)
                   $this->load->view('template_front_1',$data);
                else 
                   $this->load->view ( 'white_label/' . $_SESSION['white_label_id'] . '/template_signup', $data );
            }
            else
            {
                redirect('login');
            }
        }
        else
        {
            redirect('login','location');
        }
    }

    // Author : Shafiul Alam
    // Description : Activate the merchant And call for send activation successfull email
    function activateAccount($merchant_row_id, $activationCode)
    {
        if(!($merchant_row_id && $activationCode))
        {
            redirect('login');
        }

        $this->load->model ( 'Merchant_Signup_model', 'merchant', TRUE );
        $merchant = $this->merchant->getMerchant_row_id ( $merchant_row_id, $activationCode );

        if ($merchant)
        {
            if ($merchant ['active_status'] == 1) {
                message($this->lang->line ( 'ACCOUNT_ALREADY_ACTIVATED' ));
                $data['activated'] = 1;
            }
            else
            {
                $this->load->model ( 'merchant/Merchant_model', 'merchantodel', TRUE );
                $merchant_data = $this->merchantodel->getMerchantDetails ( $merchant_row_id );

                $data['first_name'] = $merchant_data->first_name;
                $data['to_address'] = $merchant_data->email_address;
                $data['from_address'] = $this->config->item('emailFromAddress');

                //get customized email
                $emailInfo = $this->Mailer_model->getAdminCustomEmailInfo(1019);
                $data['subject'] = $emailInfo['email_subject'];
                $data['body'] = $this->Mailer_model->getMailBody($data, $emailInfo['email_body']);
                $this->Mailer_model->sendCustomizedMails($data);
                $this->merchant->activateAccount ( $merchant_row_id, $activationCode );
            }
        }
        else
        {
            exception('INVALID URL.');
            $data['error'] = 1;
        }
        //}
        $data['content'] = $this->load->view ( 'email_template/account_activation_successful', $data, true);
        $this->load->view ( 'template_front', $data );
    }

    /**
     * @author Jilani Jidni
     *
     */
    function premiumSuiteUserCreate($merchant_row_id)
    {
        $this->load->model('merchant/Merchant_model', 'Merchant_model', TRUE);

        $data['merchantDetails'] = $this->Merchant_model->getMerchantDetails($merchant_row_id);
        $data['merchantDetails']->user_password = $_SESSION['p_w']; 
        /**
         * create user on others product by web service
         */
        $this->load->config('web-service');

        $packageModules = $this->Merchant_model->getMerchantPackageModules($data['merchantDetails']->package_id);

        $responseData = array();

        foreach ($packageModules as $aModule)
        {
            switch ($aModule->module_id)
            {
                /**
                 * user create from premiumwebcart to PR & PWT
                 */
                case $this->config->item('premium_response_module_id'):

                    if($data['merchantDetails']->is_trial)
                    {
                        $data['merchantDetails']->pr_package_id = $this->config->item('premium_response_trial_package_id');
                    }
                    else
                    {
                        $data['merchantDetails']->pr_package_id = $this->config->item('premium_response_paid_package_id');
                    }

                    $this->load->model ( 'web-service/user_create_client_model', 'UserCreateClientModel', TRUE );
                    $responseData['prCredential'] = $this->UserCreateClientModel->premiumResponseUser($data['merchantDetails']);
                    break;

                case $this->config->item('premium_web_tracking_module_id'):

                    $this->load->model ( 'web-service/user_create_client_model', 'UserCreateClientModel', TRUE );
                    $responseData['pwtCredential'] = $this->UserCreateClientModel->premiumWebTrackingUser($data['merchantDetails']);
                    break;
            }
        }
        return $responseData;
    }

    function showActivation() 
    {
        switch($_SESSION['white_label_id'])
        {
           case 1 : 
             $data['login_url'] = 'showLogin';
             break;
           case 2 : 
             $data['login_url'] = 'showGymminderLogin';
             break;
           case 3 : 
             $data['login_url'] = 'showMMGLogin';
             break;
           case 4 : 
             $data['login_url'] = 'showcn360Login';
             break;
        }

        $data['content'] = $this->load->view ( 'email_template/activation_message', $data, true);
        
        if($_SESSION['white_label_id'] == 1)
           $this->load->view ( 'template_front_1', $data );
        else 
           $this->load->view('white_label/'. $_SESSION['white_label_id'] .'/template_signup', $data); 
    }

    function showRetrievePassword() {
        $data['white_label_id'] = 1;
        $data['login_url'] = 'showLogin';
        $whiteLabel = $this->config->item('white_label');
        $data['white_label'] = $whiteLabel[1];
        $data['content'] = $this->load->view('forgotPassword', $data, true);
        $this->load->view('template_front_1', $data);
    }

    function showGymminderRetrievePassword() {
        $data['white_label_id'] = 2;
        $data['login_url'] = 'showGymminderLogin';
        $whiteLabel = $this->config->item('white_label');
        $data['white_label'] = $whiteLabel[2];
        $data['content'] = $this->load->view('forgotPassword', $data, true);
        $this->load->view('template_front_2', $data);
    }

    function showMMGRetrievePassword() {
        $data['white_label_id'] = 3;
        $data['login_url'] = 'showMMGLogin';
        $whiteLabel = $this->config->item('white_label');
        $data['white_label'] = $whiteLabel[3];
        $data['content'] = $this->load->view('forgotPassword', $data, true);  
        $this->load->view('template_front_3', $data);
    }
    function showCN360RetrievePassword() {
        $data['white_label_id'] = 4;
        $data['login_url'] = 'showcn360Login';
        $whiteLabel = $this->config->item('white_label');
        $data['white_label'] = $whiteLabel[4];
        $data['content'] = $this->load->view('forgotPassword', $data, true);  
        $this->load->view('template_front_4', $data);
    }

    function sendPasswordRetrivalMail()
    {
        $this->load->helper ( 'security' );
        $this->load->model ( 'merchant/Merchant_model', 'Merchant_model', TRUE );
        $emailAddress = $this->input->post ( 'email_address', TRUE );
        $merchantData = $this->Merchant_model->checkValidUser ( $emailAddress );

        if ($merchantData)
        {
            $mailData ['from_address'] = $this->config->item ( 'emailFromAddress' );
            $mailData ['to_address'] = $merchantData->email_address;
            $mailData ['first_name'] = $merchantData->first_name;
            $mailData ['last_name'] = $merchantData->last_name;
            $mailData ['user_name'] = $merchantData->email_address;
            $mailData ['new_password'] = $this->generateNewPassword();
            $whiteLabelId = $this->input->post('white_label_id');
            $mailData['retrievalLink'] = base_url () . 'signup/activateNewPassword/' . dohash ( $merchantData->merchant_row_id, 'md5' ) . '/' . $whiteLabelId;
            $this->load->model ( 'mailData/Mailer_model', 'Mailer_model', TRUE );
            $emailInfo = $this->Mailer_model->getAdminCustomEmailInfo(1018);
            $mailData['subject'] = $emailInfo['email_subject'];
            $mailData['body'] = $this->Mailer_model->getMailBody($mailData, $emailInfo['email_body']);

            $this->Mailer_model->sendCustomizedMails ( $mailData);

            $this->Merchant_model->saveTempPassword ( $merchantData->merchant_row_id,  dohash ($mailData ['new_password'],'md5') );

            message('Please check your mailbox. Read the instruction in the mail to change your password.');
        }
        else
        {
            exception('Sorry, the email address you have provided does not match any record.');
        }

        if($this->input->post('coach_merchant_row_id'))
            redirect('coach/login/showRetrievePassword/' . $this->input->post('coach_merchant_row_id'));
        switch($this->input->post('white_label_id'))
        {
            case 1 : 
                redirect('signup/showRetrievePassword');
                break;
            case 2 :
                redirect('signup/showGymminderRetrievePassword');
                break; 
            case 3 :
                redirect('signup/showMMGRetrievePassword');
                break; 
            case 4 :
                redirect('signup/showCN360RetrievePassword');
                break; 
        }
    }

    function activateNewPassword($enc_merchant_row_id, $whiteLabelId = 0) {

        $this->load->model ( 'merchant/Merchant_model', 'Merchant_model', TRUE );
        $merchantData = $this->Merchant_model->checkValidLink ( $enc_merchant_row_id );

        if ($merchantData)
        {

            $this->Merchant_model->changeCurrentPassword($merchantData->merchant_row_id,$merchantData->temp_password);
            $this->Merchant_model->removeTempPassword($merchantData->merchant_row_id);
            $data ['retrieveMessage'] = 'Your Password Has Been Changed Successfully !';
            $data ['success'] = 1;
        }
        else
        {
            $data ['retrieveMessage'] = 'Sorry! This Link Has Been Expired!';
            $data ['success'] = 0;

        }
        
        $data['white_label_id'] = $whiteLabelId;
        switch($whiteLabelId)
        {
           case 1 : 
             $data['login_url'] = 'showLogin';
             break;
           case 2 : 
             $data['login_url'] = 'showGymminderLogin';
             break;
           case 3 : 
             $data['login_url'] = 'showMMGLogin';
             break;
           case 4 : 
             $data['login_url'] = 'showcn360Login';
             break;
        }
        $data['content'] = $this->load->view ( 'retrievePassword', $data, true);
        $this->load->view( 'template_front_' . $whiteLabelId , $data );
    }

    function generateNewPassword() {

        $alpha = array ('A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j', '@', '1', '2', '3', '4', '5', '7', '8', '9', '0' );

        $passwordLength = 8;
        $password = '';

        for($i = 0; $i < $passwordLength; $i ++) {
            $rand = mt_rand ( 0, 29 );
            $password .= $alpha [$rand];
        }

        return $password;
    }

    function tellFriend()
    {
        $info = $_SESSION['affiliate_info'];
        if($_SERVER['REQUEST_METHOD'] != 'POST' || !$info['affiliate_email'])
        {
            redirect('signup/account_success');
        }
        $this->load->model('administration/Admin_affiliate_signup_model', 'admin_affiliate_signup_model', true);
        $this->load->model('administration/Admin_affiliate_program_setup_model', 'admin_affiliate_program_setup_model', true);
        $this->load->model('mailData/Mailer_model', 'Mailer_model', true);

        $affiliate = $this->admin_affiliate_signup_model->getAffiliateByEmail($info['affiliate_email']);
        if($affiliate)
           $admin_affiliate_row_id = $affiliate['admin_affiliate_row_id'];
        else
           $admin_affiliate_row_id = $this->admin_affiliate_signup_model->saveAdminAffiliate($info);
        $standardInfo = $this->admin_affiliate_program_setup_model->getTellFriendSpecificLinkInfo();
        $firstNames = $this->input->post('first_name', true);
        $emails     = $this->input->post('email', true);

        $info['link']    = $standardInfo['generated_link'] . '100' . $admin_affiliate_row_id;
        $info['subject'] = 'Cool Suggestion From ' . $info['affiliate_name'];
        foreach($firstNames as $key => $value)
        {
            if(trim($emails[$key]) && trim($value))
            {
                $info['first_name'] = $value;
                $info['email']      = $emails[$key];
                $info['body']       = $this->load->view('administration/mails/10005', $info, true);
                $this->Mailer_model->tellFriend($info);
            }
        }
        message('Tell a friend notification email has been sent successfully.');
        redirect('signup/tellFriendSuccess');
    }

    function tellFriendSuccess()
    {
        $data['content'] = $this->load->view('tell_friend_success',$_SESSION['affiliate_info'], true);

        if($_SESSION['white_label_id'] == 1)
           $this->load->view ( 'template_front_1', $data );
        else 
           $this->load->view('white_label/'. $_SESSION['white_label_id'] .'/template_signup', $data); 
    }
    
    function loadAnalyticsCode()
    {
        $this->load->view('merchant_signup_analytics');
    }
}
?>