<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
ini_set('display_errors', 0);
#error_reporting(E_ALL ^ E_NOTICE);
//magazine
if ($_SERVER['HTTP_HOST'] == 'localhost') {
    require_once $_SERVER['DOCUMENT_ROOT']."/magazine/PHPExcel/Classes/PHPExcel.php";
    require_once $_SERVER['DOCUMENT_ROOT']."/magazine/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php";
} elseif($_SERVER['HTTP_HOST'] == 'nurturecraftmagazines.com') {
    require_once $_SERVER['DOCUMENT_ROOT']."/magazine/PHPExcel/Classes/PHPExcel.php";
    require_once $_SERVER['DOCUMENT_ROOT']."/magazine/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php";
} else {
    require_once $_SERVER['DOCUMENT_ROOT']."/magazine/smsystem/PHPExcel/Classes/PHPExcel.php";
    require_once $_SERVER['DOCUMENT_ROOT']."/magazine/smsystem/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php";
}
class Subscriber extends CI_Controller {

    /**
     * Function index
     * default functionality for the user.
     * Controllers default method.
     *
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function index()
    {
        $this->load->view('welcome_message');
    }

    /**
     * Function subscriber_list
     * Listing of added subscriber.
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function subscriber_list($offset = 1)
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectpath = base_url().'index.php/users/login';
            redirect($strRedirectpath);
        }

        #Load required models and libraries.
        $this->load->model('subscribers');
        $this->load->library('pagination');
        $this->load->library('Backend_pagination');
        # check for the search value
        $strSearchKey = "";
        if (isset($_GET['search_value'])) {
            $strSearchKey = strtolower($_GET['search_value']);
            $offset = 1;
        }

        /** Pagination patch start **/

        # Call the model for taking count
        $arrCountArray = $this->subscribers->fnGetDetailsForSubscribers('subscriber', '', $strSearchKey);

        # Functionality of pagination.
        $custom_config['uri_segment'] = 3;
        $this->backend_pagination->setup_pagination($custom_config);
        $this->backend_pagination->arr_data = $arrCountArray;
        $this->backend_pagination->offset = $offset;
        $this->backend_pagination->url = 'index.php/subscriber/subscriber_list/';
        $this->backend_pagination->setup_pagination();
        $arrData['pagination']  = $this->backend_pagination->strpagination;
        $arrDetails = $this->subscribers->fnGetSubscribers('subscriber', $this->backend_pagination->limit,$this->backend_pagination->offsetPage, $strSearchKey);
        //echo "<pre>";print_r($arrDetails);exit;
        /** Pagination patch end **/

        # Add the middle content to the template.
        $arrData['middle'] = 'subscriber/subscriber_list';
        $arrData['details'] = $arrDetails;
        $arrData['strSearchKey'] = $strSearchKey;
        $arrData['cust_Pagination'] = $this->pagination->create_links();
        $arrData['current_page'] = $offset;
        $this->load->view('admin/templates/template', $arrData);
    } // Function  subscriber_list ends

function fnUpdateTransaction(){
        # set form fields rules.
        $this->load->helper(array('form', 'url'));
        $this->form_validation->set_rules('trp_data', 'Data', 'trim|required');
        
        # Check whether the validation turns true.
        if ($this->form_validation->run() == TRUE) {
            
            $trp_data   = (string)trim($_POST['trp_data']);
            $status_     = (int)trim($_POST['status']);
            $comment    = (string)trim($_POST['comment']);
            
            if($status_ == 2){
                $status = '2';
            }else if($status_ == 0){
                $status = '0';
            }

            $TrpData = explode('---', $trp_data);
$TrpData2 = base64_decode($TrpData[0]);
            if($TrpData2 != '' && $TrpData2 != '0'){
                $this->load->model('subscribers');
                if($comment != ''){
                    $arrUpdatedInfo = array('is_active'=>$status,'additional_comment'=>$comment);
                }else{
                    $arrUpdatedInfo = array('is_active'=>$status);
                }
                $this->subscribers->fnUpdateSubscriptionDetails($TrpData2,$arrUpdatedInfo);
                echo json_decode(1);
            }else{
                echo json_decode(0);
            }
        }else{
            echo json_decode(0);
        }
    }

    /**
     * Function Preview.
     * To preview the requested subscriber.
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function preview($offset = 1)
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectpath = base_url().'index.php/users/login';
            redirect($strRedirectpath);
        }

        # Check for the given id.
        $intDecUserId = (int) base64_decode($_GET['user_id']);
        if ($intDecUserId == 0) {
            $strRedirectpath = base_url().'index.php/subscriber/subscriber_list';
            redirect($strRedirectpath);
        }


        $strStartDate = "";
        $strEndDate = "";

        if ($_GET['from_date'] != "") {
            $strStartDate = DateTime::createFromFormat('d/m/Y', $_GET['from_date'])->format('Y-m-d');
        }

        if ($_GET['to_date'] != "") {
            $strEndDate = DateTime::createFromFormat('d/m/Y', $_GET['to_date'])->format('Y-m-d');
        }

        # Call the model for taking count
        $this->load->model('subscribers');
        $this->load->library('pagination');
        $this->load->library('Backend_pagination');

        $arrCountArray = $this->subscribers->fnGetDetails('subscriber', $intDecUserId);
        # Get the subscribers already subscribed magazines Transactions.
        $arrSubscribedMagazine = $this->subscribers->fnGetRequiredDetails($intDecUserId);
        //echo "<pre>";print_r($arrSubscribedMagazine);exit;

        # get the address related details
        $arrDetails =  $arrCountArray[0];
        $arrCountry = $this->subscribers->fnGetDetails('country', $arrCountArray[0]['country']);
        $strCountry = $arrCountry[0]['name'];

        #$arrExpiredMagazines = $this->subscribers->fnGetLatestSubscription("", 1, $intDecUserId);
        $arrExpiredMagazines = $this->subscribers->fnGetExpiredTransactionsLogs("", 1, $intDecUserId);
        $arrExpiredMagazineList = array();
        foreach($arrExpiredMagazines as $magazine) {
            #$arrExpiredMagazineList[] = $magazine['magazine_code'];
            $arrExpiredMagazineList[] = $magazine['trans_id'];
        }

        #Get the transaction history for the Given Subscriber.
        //$arrSubscriberTransaction = $this->subscribers->fnGetTransactionInfoForIndividual($intDecUserId);

        /** @var Pagination part Start */

        $arrAllRecords = $this->subscribers->fnGetIndividualTransactionPagination($intDecUserId, 1);
        $custom_config['uri_segment'] = 3;
        $this->backend_pagination->setup_pagination($custom_config);
        $this->backend_pagination->arr_data = $arrAllRecords;
        $this->backend_pagination->offset = $offset;
        $this->backend_pagination->url = 'index.php/subscriber/preview/';
        $this->backend_pagination->per_page = 10;
        $this->backend_pagination->setup_pagination();
        $arrData['pagination']  = $this->backend_pagination->strpagination;
        $arrGetSubscribedMagazine = $this->subscribers->fnGetIndividualTransactionPagination($intDecUserId, 1, $this->backend_pagination->limit,$this->backend_pagination->offsetPage);
        /*echo "<pre>";print_r($arrGetSubscribedMagazine);exit;*/
        /** @var  Pagination ends */


        $arrSentNotifications = $this->subscribers->fnGetSubscriberNotification($intDecUserId, "", $strStartDate, $strEndDate);
        $arrCity = $this->subscribers->fnGetDetails('city', $arrCountArray[0]['city']);
        $strCity = $arrCity[0]['name'];
        $arrData['middle'] = 'subscriber/preview';
        $arrData['arrUser'] = $arrCountArray[0];
        $arrData['country_name'] = $strCountry;
        $arrData['city_name'] = $strCity;
        $arrData['current_user_id'] = $intDecUserId;
        $arrData['notifications'] = $arrSentNotifications;
        $arrData['subscribed_product'] = $arrGetSubscribedMagazine;
        $arrData['start_date'] = $_GET['from_date'];
        $arrData['end_date'] = $_GET['to_date'];
        $arrData['expired_magazines'] = $arrExpiredMagazineList;
        $arrData['arrSubscriberTransaction'] = $arrGetSubscribedMagazine;
        $arrData['cust_Pagination'] = $this->pagination->create_links();
        $arrData['current_page'] = $offset;
        $this->load->view('admin/templates/template', $arrData);
    } // Function preview ends

    /**
     * Function add_subscriber.
     * To add subscriber.
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function add_subscriber()
    {
        # Load the required model.
        $this->load->model('subscribers');

        # set form fields rules.
        $this->load->helper(array('form', 'url'));
        #$this->form_validation->set_rules('sub_salution', 'Salution', 'required|xss_clean');

        # Set the form validation rule for the personal information such as name, email, phone,mobile, gender, NRIC
        /**$this->form_validation->set_rules('sub_first_name', 'First Name', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('sub_last_name', 'Last Name', 'trim|required|max_length[100]|xss_clean');**/

        if ($_POST['sub_dob'] != "" ) {
            $this->form_validation->set_rules('sub_dob', 'Date of birth', 'trim|required');
        }

        if ($_POST['sub_nric'] != "" ) {
            $this->form_validation->set_rules('sub_nric', 'NRIC', 'trim|required|xss_clean');
        }
        if ($_POST['sub_dob'] != "" ) {
            $this->form_validation->set_rules('sub_dob', 'Date of birth', 'trim|required');
        }
        /*if ($_POST['sub_email'] != "" ) {
            $this->form_validation->set_rules('sub_email', 'Email', 'trim|required|valid_email|is_unique[subscriber.email]|xss_clean');
        }
        if ($_POST['sub_phonno'] != "" ) {
            $this->form_validation->set_rules('sub_phonno', 'Phone number', 'trim|required|xss_clean');
        }
        if ($_POST['country_code'] != "" ) {
            $this->form_validation->set_rules('country_code', 'Country code', 'trim|required');
        }
        if ($_POST['gender'] != "" ) {
            $this->form_validation->set_rules('gender', 'Gender', 'trim|required|numeric|xss_clean');
        }
        if ($_POST['mobile_number'] != "" ) {
            $this->form_validation->set_rules('mobile_number', 'Mobile Number', 'trim|required|xss_clean');
        }
        if ($_POST['sub_type'] != "" ) {
            $this->form_validation->set_rules('sub_type', 'Subscriber Type', 'trim|required');
        }*/

        # Check whether the validation turns true.
        if ($this->form_validation->run() == TRUE)
        {
            $arrPostedData = $_POST;
            $strUploadedFileName = NULL;
            # Check whether the file get uploaded or not.
            if ($_FILES['sub_image']['name'] != '')
            {
                # Set the file upload configuration.
                if ($_SERVER['HTTP_HOST'] == 'localhost') {
                    $config['upload_path'] = $_SERVER['DOCUMENT_ROOT']."/smsystem/uploads/users";
                } else {
                    $config['upload_path'] = $_SERVER['DOCUMENT_ROOT']."/magazine/uploads/users";
                }
                $config['allowed_types'] = 'png|jpeg|jpg';
                $config['max_size']	= '2000';
                $this->load->library('upload', $config);

                # Check whether the uploaded file does have any errors.
                if (! $this->upload->do_upload('sub_image'))
                {
                    # if found redirect to the form.
                    $this->session->set_flashdata('error', $this->upload->display_errors());
                    redirect(base_url().'index.php/subscriber/add_subscriber');
                } else {
                    $data = array('upload_data' => $this->upload->data());
                    $strUploadedFileName = $data['upload_data']['file_name'];
                }
            }

            #get the values of all fields.
            $arrMagazine = array();
            $arrMagazine['photo'] = $strUploadedFileName;
            $arrMagazine['first_name'] = $arrPostedData['sub_first_name'];
            $arrMagazine['last_name'] = $arrPostedData['sub_last_name'];
            if ($this->input->post('sub_dob') != "") {
                $arrMagazine['dob'] = DateTime::createFromFormat('d-m-Y', $this->input->post('sub_dob'))->format('Y-m-d');
            } else {
                $arrMagazine['dob'] = null;
            }
            $arrMagazine['email'] = $arrPostedData['sub_email'];
            $arrMagazine['country_code'] = $arrPostedData['country_code'];
            $arrMagazine['country_code_mobile'] = $arrPostedData['country_code_mobile'];
            $arrMagazine['phone'] = $arrPostedData['sub_phonno'];
            $arrMagazine['mobile'] = $arrPostedData['mobile_number'];
            $arrMagazine['subscriber_type'] = $arrPostedData['sub_type'];
            $arrMagazine['mailing_block'] = ($arrPostedData['sub_block'] != "") ? $arrPostedData['sub_block'] : null ;
            $arrMagazine['mailing_unit_no'] = ($arrPostedData['sub_unit_no'] != '' ) ? $arrPostedData['sub_unit_no'] : null;
            $arrMagazine['mailing_street_name'] = ($arrPostedData['sub_street'] != '' ) ? $arrPostedData['sub_street'] : null;
            $arrMagazine['mailing_country'] = $arrPostedData['sub_country'];
            $arrMagazine['mailing_city'] = $arrPostedData['sub_city'];
            $arrMagazine['mailing_postal_code'] = ($arrPostedData['sub_code'] != '' ) ? $arrPostedData['sub_code'] : null;
            $arrMagazine['nric'] = $arrPostedData['sub_nric'];
            $arrMagazine['home_block'] = ($arrPostedData['sub_home_block'] != '' ) ? $arrPostedData['sub_home_block'] : null;
            $arrMagazine['home_unit_no'] = ($arrPostedData['sub_home_unit_no'] != '' ) ? $arrPostedData['sub_home_unit_no'] : null;
            $arrMagazine['home_street_name'] = ($arrPostedData['sub_home_street'] != '' ) ? $arrPostedData['sub_home_street'] : null;
            $arrMagazine['home_country'] = $arrPostedData['sub_home_country'];
            $arrMagazine['home_city'] = $arrPostedData['sub_home_city'];
            $arrMagazine['home_postal_code'] = ($arrPostedData['sub_home_code'] != '' ) ? $arrPostedData['sub_home_code'] : null;
            $arrMagazine['campaign_id'] = $arrPostedData['campaign'];
            $arrMagazine['sales_agent'] = $arrPostedData['sales_agent'];
            $arrMagazine['gender'] = $arrPostedData['gender'];
            $arrMagazine['building_name_home'] = ($arrPostedData['sub_home_build'] != '') ? $arrPostedData['sub_home_build'] : null;
            $arrMagazine['building_name_mail'] = ($arrPostedData['sub_build'] != '') ? $arrPostedData['sub_build'] : null;
            $arrMagazine['address_1'] = ($arrPostedData['address_1'] != "") ? $arrPostedData['address_1'] : null;
            $arrMagazine['address_2'] = ($arrPostedData['address_2'] != "") ? $arrPostedData['address_2'] : null;
            $arrMagazine['is_overseas'] = ($arrPostedData['sub_country' ] > 1) ? '1' : '0';

            # Get the Last memberId.
            $arrMemberInfo = $this->subscribers->fnGetLastMemberId();
            $strMemberId = $arrMemberInfo[0]['memberId'];
            if ($strMemberId == null || $strMemberId == "") {
                $arrMagazine['memberId'] = 14000;
            } else {
                $strNewId = $strMemberId + 1;
                $arrMagazine['memberId'] = $strNewId;
            }


            # If user type is company then get its company name
            if (isset($arrPostedData['cname']) && $arrPostedData['cname'] != "") {
                $arrMagazine['company_name'] = $arrPostedData['cname'];
            }

            # If user type is student then get its guardian name
            if (isset($arrPostedData['gname']) && $arrPostedData['gname'] != "") {
                $arrMagazine['guardian_name'] = $arrPostedData['gname'];
                $arrMagazine['guardian2_name'] = $arrPostedData['gname2'];
            }

            if (isset($arrPostedData['sname']) && $arrPostedData['sname'] != "") {
                $arrMagazine['school_name'] = $arrPostedData['sname'];
                $arrMagazine['teacher_name'] = $arrPostedData['tname'];
            }

            #If the subscriber type is other then add other details
            if (isset($arrPostedData['other_details']) && $arrPostedData['other_details'] != "") {
                $arrMagazine['other_details'] = $arrPostedData['other_details'];
            }
            $intNewSubscriberId = $this->subscribers->fnSaveSubscriber('subscirber', $arrMagazine);

            $this->session->set_flashdata('success', 'New subscriber has been added');
            $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.base64_encode($intNewSubscriberId);
            redirect($strRedirectPath);

        } else {
            # Load the required model.
            $this->load->model('subscribers');
            $arrCountryArray = $this->subscribers->fnGetDetails('country_codes');
            $arrCountryCode = array();
            $intCounter = 0;
            if (count($arrCountryArray) > 0) {
                foreach($arrCountryArray as $countryCode) {
                    $arrCountryCode[$countryCode['area_code']] = $countryCode['country_name'];
                    $intCounter++;
                }
            }
            asort($arrCountryCode);
            /** if validation errors found then redirect  **/
            $strValidationErrors = validation_errors();
            if ($strValidationErrors != "" ) {
                $this->session->set_flashdata('error', $strValidationErrors);
                $strRedirectpath = base_url().'index.php/subscriber/add_subscriber';
                redirect($strRedirectpath);
            } else {
                # get the campaign details for the option of cash payment.
                $arrCampaign = $this->subscribers->fnGetDetails("campaigns");
                $arrAgent = $this->subscribers->fnGetDetails("agent");
                $arrData['middle']   = 'subscriber/add_subscriber';
                $arrData['arrCampaign']   = $arrCampaign;
                $arrData['arrAgent']   = $arrAgent;
                $arrData['country_code']   = $arrCountryCode;
                $strValidationErrors = validation_errors();
                $this->session->set_flashdata('error', $strValidationErrors);
                echo $this->load->view('subscriber/add_subscriber', $arrData, true);
            }
        }
    } // Function add_subscriber ends

    /**
     * Function edit_subscriber.
     * To edit subscriber.
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function edit_subscriber()
    {
        # Check whether the session is set or not.
        if (!$this->session->userdata('username')) {
            $strRedirectPath = base_url() . 'index.php/users/login';
            redirect($strRedirectPath);
        }

        # Check for the given id.
        $intDecUserId = (int)base64_decode($_REQUEST['user_id']);
        if ($intDecUserId == 0) {
            $strRedirectPath = base_url() . 'index.php/subscriber/subscriber_list';
            redirect($strRedirectPath);
        }
        # Load the required model.
        $this->load->model('subscribers');
        $arrCountArray = $this->subscribers->fnGetDetails('subscriber', $intDecUserId);

        # Get the country codes.
        $arrCountryArray = $this->subscribers->fnGetDetails('country_codes');
        $arrCountryCode = array();
        $intCounter = 0;
        if (count($arrCountryArray) > 0) {
            foreach ($arrCountryArray as $countryCode) {
                $arrCountryCode[$countryCode['area_code']] = $countryCode['country_name'];
                $intCounter++;
            }
        }

        # Set the form validation rule for the personal information such as name, email, phone,mobile, gender, NRIC
        /*$this->form_validation->set_rules('sub_first_name', 'First Name', 'trim|required|max_length[100]|xss_clean');*/
        $this->form_validation->set_rules('sub_last_name', 'Last Name', 'trim|required|max_length[100]|xss_clean');
        if ($_POST['sub_dob'] != "") {
            $this->form_validation->set_rules('sub_dob', 'Date of birth', 'trim|required');
        }

        if ($_POST['sub_nric'] != "") {
            $this->form_validation->set_rules('sub_nric', 'NRIC', 'trim|required|xss_clean');
        }
        /*if ($_POST['sub_email'] != "") {
            if ($_POST['sub_email'] == $arrCountArray[0]['email']) {
                $this->form_validation->set_rules('sub_email', 'Email', 'required|valid_email');
            } else
                $this->form_validation->set_rules('sub_email', 'Email', 'required|valid_email');
        }*/


        if ($_POST['sub_phonno'] != "") {
            $this->form_validation->set_rules('sub_phonno', 'Phone number', 'trim|required|xss_clean');
        }

        /*8$this->form_validation->set_rules('country_code', 'Country code', 'trim|required|numeric');
        $this->form_validation->set_rules('gender', 'Gender', 'trim|required|numeric|xss_clean');
        $this->form_validation->set_rules('mobile_number', 'Mobile Number', 'trim|required|numeric|xss_clean');
        $this->form_validation->set_rules('sub_type', 'Subscriber Type', 'trim|required');

        # Set the form validation rule for the Subscription References such as Campaign and Sales Agent
        $this->form_validation->set_rules('campaign', 'Campaign', 'required|xss_clean');
        $this->form_validation->set_rules('sales_agent', 'Sales Agent', 'required|xss_clean'); **/

        # Set the form validation rule for the mailing address
        /*$this->form_validation->set_rules('sub_block', 'Block For Mailing Address', 'required');
        $this->form_validation->set_rules('sub_unit_no', 'unit number For Mailing Address', 'required');
        $this->form_validation->set_rules('sub_street', 'Street For Mailing Address', 'required');
        $this->form_validation->set_rules('sub_country', 'Country For Mailing Address', 'required');
        $this->form_validation->set_rules('sub_city', 'City For Mailing Address', 'required');
        $this->form_validation->set_rules('sub_code', 'Code For Mailing Address', 'required');*/

        # Set the form validation rule for the Home address
        /**$this->form_validation->set_rules('sub_home_block', 'Block For Home Address', 'required');
        $this->form_validation->set_rules('sub_home_unit_no', 'unit number For Home Address', 'required');
        $this->form_validation->set_rules('sub_home_street', 'Street For Home Address', 'required');
        $this->form_validation->set_rules('sub_home_country', 'Country For Home Address', 'required');
        $this->form_validation->set_rules('sub_home_city', 'City For Home Address', 'required');
        $this->form_validation->set_rules('sub_home_code', 'Code For Home Address', 'required'); **/

        # Check whether the validation turns true.
        if ($this->form_validation->run() == TRUE)
        {
            $arrPostedData = $_POST;

            #get the values of all fields.
            $arrMagazine = array();
            # Check whether the file get uploaded or not.
            if ($_FILES['sub_image']['name'] != '')
            {
                # Set the file upload configuration.
                if ($_SERVER['HTTP_HOST'] == 'localhost') {
                    $config['upload_path'] = $_SERVER['DOCUMENT_ROOT']."/smsystem/uploads/users";
                } else {
                    $config['upload_path'] = $_SERVER['DOCUMENT_ROOT']."/magazine/uploads/users";
                }
                $config['allowed_types'] = 'png|jpeg|jpg';
                $config['max_size']	= '2000';
                $this->load->library('upload', $config);

                # Check whether the uploaded file does have any errors.
                if (! $this->upload->do_upload('sub_image'))
                {
                    # if found redirect to the form.
                    $this->session->set_flashdata('error', $this->upload->display_errors());
                    redirect(base_url().'index.php/subscriber/edit_subscriber/?user_id='.$_REQUEST['user_id']);
                } else {
                    $data = array('upload_data' => $this->upload->data());
                    $strUploadedFileName = $data['upload_data']['file_name'];
                    #$arrMagezine['sub_image'] = $strUploadedFileName;
                    $arrMagazine['photo'] = $strUploadedFileName;
                }
            }
            $arrMagazine['first_name'] = $arrPostedData['sub_first_name'];
            $arrMagazine['last_name'] = $arrPostedData['sub_last_name'];
            if ($_POST['sub_dob'] != "") {
                $arrMagazine['dob'] = DateTime::createFromFormat('d-m-Y', $this->input->post('sub_dob'))->format('Y-m-d');
            } else {
                $arrMagazine['dob'] = null;
            }
            $arrMagazine['email'] = $arrPostedData['sub_email'];
            $arrMagazine['country_code'] = $arrPostedData['country_code'];
            $arrMagazine['country_code_mobile'] = $arrPostedData['country_code_mobile'];
            $arrMagazine['phone'] = $arrPostedData['sub_phonno'];
            $arrMagazine['mobile'] = $arrPostedData['mobile_number'];
            $arrMagazine['subscriber_type'] = $arrPostedData['sub_type'];
            $arrMagazine['mailing_block'] = ($arrPostedData['sub_block'] != "") ? $arrPostedData['sub_block'] : null;
            $arrMagazine['mailing_unit_no'] = ($arrPostedData['sub_unit_no'] != "") ? $arrPostedData['sub_unit_no'] : null;
            $arrMagazine['mailing_street_name'] = ($arrPostedData['sub_street'] != "") ? $arrPostedData['sub_street'] : null;
            $arrMagazine['mailing_country'] = $arrPostedData['sub_country'];
            $arrMagazine['mailing_city'] = $arrPostedData['sub_city'];
            $arrMagazine['mailing_postal_code'] = ($arrPostedData['sub_code'] != "") ? $arrPostedData['sub_code'] : null;
            $arrMagazine['nric'] = $arrPostedData['sub_nric'];
            $arrMagazine['home_block'] = ($arrPostedData['sub_home_block'] != "") ? $arrPostedData['sub_home_block'] : null;
            $arrMagazine['home_unit_no'] = ($arrPostedData['sub_home_unit_no'] != "") ? $arrPostedData['sub_home_unit_no'] : null;
            $arrMagazine['home_street_name'] = ($arrPostedData['sub_home_street'] != "") ? $arrPostedData['sub_home_street'] : null ;
            $arrMagazine['home_country'] = $arrPostedData['sub_home_country'];
            $arrMagazine['home_city'] = $arrPostedData['sub_home_city'];
            $arrMagazine['home_postal_code'] = ($arrPostedData['sub_home_code'] != "") ? $arrPostedData['sub_home_code'] : null;
            $arrMagazine['campaign_id'] = $arrPostedData['campaign'];
            $arrMagazine['sales_agent'] = $arrPostedData['sales_agent'];
            $arrMagazine['gender'] = $arrPostedData['gender'];
            $arrMagazine['building_name_home'] = $arrPostedData['sub_home_build'];
            $arrMagazine['building_name_mail'] = $arrPostedData['sub_build'];
            $arrMagazine['address_1'] = ($arrPostedData['address_1'] != "") ? $arrPostedData['address_1'] : null;
            $arrMagazine['address_2'] = ($arrPostedData['address_2'] != "") ? $arrPostedData['address_2'] : null;
            $arrMagazine['is_overseas'] = ($arrPostedData['sub_country' ] > 1) ? '1' : '0';

            # If user type is company then get its company name
            if (isset($arrPostedData['cname']) && $arrPostedData['cname'] != "") {
                $arrMagazine['company_name'] = $arrPostedData['cname'];
            }
            # If no guardian name is available then set it as NULL.
            if ($arrPostedData['cname'] == "" || !(isset($arrPostedData['cname']))) {
                $arrMagazine['company_name'] = NULL;
            }

            # If no guardian name is available then set it.
            if (isset($arrPostedData['gname']) && $arrPostedData['gname'] != "") {
                $arrMagazine['guardian_name'] = $arrPostedData['gname'];
                $arrMagazine['guardian2_name'] = $arrPostedData['gname2'];
            }

            # If no guardian name is available then set it as NULL.
            if ($arrPostedData['gname'] == "" || !(isset($arrPostedData['gname']))) {
                $arrMagazine['guardian_name'] = NULL;
                $arrMagazine['guardian2_name'] = NULL;
                $arrMagazine['school_name'] = NULL;
                $arrMagazine['teacher_name'] = NULL;
            }

            $arrMagazine['school_name'] = NULL;
            if (isset($arrPostedData['sname']) && $arrPostedData['sname'] != "") {
                $arrMagazine['school_name'] = $arrPostedData['sname'];
                $arrMagazine['teacher_name'] = $arrPostedData['tname'];
            }

            $arrMagazine['other_details'] = NULL;
            #If the subscriber type is other then add other details
            if (isset($arrPostedData['other_details']) && $arrPostedData['other_details'] != "") {
                $arrMagazine['other_details'] = $arrPostedData['other_details'];
            }
            # Update the subscriber.
            $this->subscribers->fnUpdateSubscriber($arrMagazine, $intDecUserId);

            $this->session->set_flashdata('success', 'Subscriber has been updated successfully');
            redirect(base_url().'index.php/subscriber/subscriber_list');
        } else {

            /** if validation errors found then redirect  **/
            $strValidationErrors = validation_errors();
             
            if ($strValidationErrors != "" ) {
                $this->session->set_flashdata('error', $strValidationErrors);
                $strRedirectPath = base_url().'index.php/subscriber/edit_subscriber/?user_id='.$_REQUEST['user_id'];
                redirect($strRedirectPath);
            } else {
                $arrCampaign = $this->subscribers->fnGetDetails("campaigns");
                $arrAgent = $this->subscribers->fnGetDetails("agent");
                $arrData['middle']   = 'subscriber/edit_subscriber';
                $arrData['details']   = $arrCountArray[0];
                $arrData['arrAgent']   = $arrAgent;
                $arrData['arrCampaign']   = $arrCampaign;
                $arrData['country_code']   = $arrCountryCode;
                $arrData['user_id']   = $_REQUEST['user_id'];
                echo $this->load->view('subscriber/edit_subscriber', $arrData, true);
            }
        }
    } // Function edit_subscriber ends.

    /**
     * Function to subscribe the magazine.
     * @Author : Himanshu Charegaonkar
     * @Access : Public
     */
    public function subscribe_product()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectpath = base_url().'index.php/users/login';
            redirect($strRedirectpath);
        }

        # Check for the given id.
        $intDecUserId = (int) base64_decode($_GET['user_id']);
        if ($intDecUserId == 0) {
            $strRedirectpath = base_url().'index.php/subscriber/subscriber_list';
            redirect($strRedirectpath);
        }
        # Load the required model.
        $this->load->model('subscribers');

        $arrUserInfo = $this->subscribers->fnGetDetails('subscriber', $intDecUserId);
        $strSubscriberName = $arrUserInfo[0]['first_name']." ".$arrUserInfo[0]['last_name'];

        $arrCountArray = $this->subscribers->fnGetMagazineWithSubscription($intDecUserId);
        $intCounter = 0;
        foreach($arrCountArray as $arrMagazine) {
            $arrmagazineDetails = $this->subscribers->fnGetSubscriptionDetails($arrMagazine['id']);
            $arrAvalPromotions = $this->subscribers->fnGetAvalPromo($arrMagazine['id']);
            $arrCountArray[$intCounter]['subscription_option'] = $arrmagazineDetails;
            $arrCountArray[$intCounter]['available_promo'] = $arrAvalPromotions;
            $intCounter++;
        }
        $arrData['middle']   = 'subscriber/subscribe_multiple_magazines';
        $arrData['magazine_details'] = $arrCountArray;
        $arrData['strUserId'] = $intDecUserId;
        $arrData['strGivenSubId'] = $_GET['user_id'];
        $arrData['strUserName'] = $strSubscriberName;
        $this->load->view('admin/templates/template', $arrData);
    } // Function subscribe_product ends

    /**
     *  Function to subscribe magazine
     * @Author : Himanshu Charegaonkar
     * @Access : Public
     */
    public function subscribe_magazine()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }
        # Load the required model.
        $this->load->model('subscribers');
        $this->load->model('promotions');
        $this->load->model('magezines');

        # Check for the given id.
        $intDecUserId = (int) base64_decode($_POST['subscriber_id']);

        # this previous Id is used for Renewal of magazine subscription.
        #Current scenario of renewal is to create new transaction entry of renewal and then remove old transaction record using prev transaction id.
        $intPreviousTransactionId = (int) base64_decode($_POST['transaction_id']);

        #Check whether we get the subscriber Id
        if ($intDecUserId == 0) {
            $this->session->set_flashdata('error', "Please provide valid Subscriber Id");
            $strRedirectPath = base_url().'index.php/subscriber/subscriber_list';
            redirect($strRedirectPath);
        }
        # Check whether the given user Id is present in database or not.
        $arrSubscriberInfo = $this->promotions->fnGetDetailsOfTable('subscriber', 'id', $intDecUserId);

        if (empty($arrSubscriberInfo)) {
            $strRedirectPath = base_url().'index.php/subscriber/subscribe_product/?user_id='.base64_encode($intDecUserId);
            redirect($strRedirectPath);
        }
        $strSubscriberName = $arrSubscriberInfo[0]['first_name']." ".$arrSubscriberInfo[0]['last_name'];

        #Declare array to store skipped id magazine. i.e. Skipped due to error.
        $arrMagazineCodeError = array();
        $arrPostedData = $_POST;
        #Declare related array for magazine code and amount and start issue and end issue.
        $arrMagazineCode = $arrPostedData['magezine_code'];
        $arrStartIssue = $arrPostedData['camp_start_issue'];
        $arrEndIssue = $arrPostedData['camp_end_issue'];
        $arrStartDate = $arrPostedData['camp_start_date'];
        $arrEndDate = $arrPostedData['camp_end_end'];
        $arrAmount = $arrPostedData['camp_amount'];
        $arrTotalIssue = $arrPostedData['camp_total_issue'];
        $arrDuration = $arrPostedData['camp_no_of_year'];
        $arrCopies = $arrPostedData['camp_no_of_copies'];

        $intArrCounter = 0;
        #Create a unique Transaction Id
        /**$strTransactionPrefix = date("y").date("m");
        $strTransactionId = substr(number_format(time() * rand(),0,'',''),0,6);
        $strUniqueTransactionKey = $strTransactionPrefix.$strTransactionId; **/
        $strUniqueTransactionKey = $this->fnCheckForUniqueTransactionKey();
        foreach ($arrMagazineCode as $details) {
            $intCounter = 0;
            # Check for the given magazine id.
            $intDecMagId = $arrMagazineCode[$intArrCounter];
            $arrCheckMagazine = $this->promotions->fnGetDetailsOfTable('magazine', 'magezine_id', $intDecMagId);
            if (empty($arrCheckMagazine)) {
                array_push($arrMagazineCode[$intArrCounter],$arrMagazineCodeError);
                $intCounter++;
            }
            $intDecMagId = $arrCheckMagazine[0]['id'];

            # If user has entered the promotional code then check whether the promotional code has associate with it.
            if ($arrPostedData['promo_code'] != "") {
                $boolCheck = $this->promotions->fnGetCampaignMagazineDetails($arrMagazineCode[$intArrCounter], $arrPostedData['promo_code']);
                if (empty($boolCheck)) {
                    array_push($arrMagazineCode[$intArrCounter],$arrMagazineCodeError);
                    $intCounter++;
                }
            }
            if ($intCounter == 0) {
                # Create a array of records.
                $arrInsertArray = array();
                $arrInsertArray['transaction_date'] = date("Y-m-d");
                $arrInsertArray['subscriber_id'] = $intDecUserId;
                $arrInsertArray['subscriber_name'] = $strSubscriberName;
                $arrInsertArray['product_id'] = $intDecMagId;
                $arrInsertArray['period'] = $arrDuration[$intArrCounter];
                $arrInsertArray['totalNCopies'] = $arrCopies[$intArrCounter];
                $arrInsertArray['subscribed_on'] = date("Y-m-d", strtotime($arrStartDate[$intArrCounter]));
                $arrInsertArray['subscription_end_on'] = date("Y-m-d", strtotime($arrEndDate[$intArrCounter]));
                $arrInsertArray['promo_code'] = ($arrPostedData['promo_code'] == "")? null:$arrPostedData['promo_code'];
                $arrInsertArray['status'] = 1;
                $arrInsertArray['start_issue'] = $arrStartIssue[$intArrCounter];
                $arrInsertArray['end_issue'] = $arrEndIssue[$intArrCounter];
                $arrInsertArray['amount'] = $arrAmount[$intArrCounter];
                $arrInsertArray['total_amount'] = $arrAmount[$intArrCounter];;
                $arrInsertArray['mode_of_payment'] = 1;
                $arrInsertArray['currency_of_payment'] = 1;
                $arrInsertArray['no_of_issue'] = $arrTotalIssue[$intArrCounter];
                $arrInsertArray['transaction_id'] = $strUniqueTransactionKey;

                # Save the Transaction details.
                $this->subscribers->fnSave('transaction', $arrInsertArray);
            }
            $intArrCounter++;
        }
        # Put the comment If this subscription is regarding the transfer
        $this->fnTransferMagazineSessionDetails($intDecMagId, $intDecUserId);

        if($this->input->post('tr_id') != ''){
            $tr_id = (int)base64_decode($this->input->post('tr_id'));
            $arrUdpArray = array('is_active' => '5');
            $this->subscribers->fnUpdateTransactionPh($arrUdpArray, $tr_id);
        }

        # Redirect with the success message.
        $this->session->set_flashdata('success', 'subscribed magazine has been added');
        $strRedirectPath = base_url().'index.php/subscriber/make_payment/?sub_id='.base64_encode($intDecUserId)."&transaction_id=".base64_encode($strUniqueTransactionKey);
        redirect($strRedirectPath);
    } // Function subscribe_magazine ends

    /**
     * Function fnSubscribe multiple magazines.
     */
    public function subscribe_multiple_magazines()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }
        # Load the required model.
        $this->load->model('subscribers');
        $this->load->model('promotions');

        $arrPostedData = $_POST;
        # Check for the given id.
        $intDecUserId = (int)base64_decode($arrPostedData['subscriber_id']);
        if ($intDecUserId == 0) {
            $this->session->set_flashdata('error', "Please provide valid Subscriber Id");
            $strRedirectPath = base_url().'index.php/subscriber/subscriber_list';
            redirect($strRedirectPath);
        }

        $arrSubscriberInfo = $this->promotions->fnGetDetailsOfTable('subscriber', 'id', $intDecUserId);
        if (count($arrSubscriberInfo) == 0 || empty($arrSubscriberInfo)) {
            $this->session->set_flashdata('error', "Please provide valid Subscriber Id");
            $strRedirectPath = base_url().'index.php/subscriber/subscriber_list';
            redirect($strRedirectPath);
        }
        $strSubscriberName = $arrSubscriberInfo[0]['first_name']." ".$arrSubscriberInfo[0]['last_name'];
        # Check whether the any subscription year has been selected or not.
        if ((int)$arrPostedData['numberOfYear'] == 0) {
            $this->session->set_flashdata('error', "Select any year package for subscription");
            $strRedirectPath = base_url().'index.php/subscriber/subscribe_product/?user_id='.base64_encode($_POST['subscriber_id']);
            redirect($strRedirectPath);
        }


        #Declare array to store skipped id magazine. i.e. Skipped due to error.
        $arrMagazineCodeError = array();

        #Declare related array for magazine code and amount and start issue and end issue.
        $arrMagazineCode = $arrPostedData['magezine_code'];
        $arrStartIssue = $arrPostedData['camp_start_issue'];
        $arrEndIssue = $arrPostedData['camp_end_issue'];
        $arrStartDate = $arrPostedData['camp_start_date'];
        $arrEndDate = $arrPostedData['camp_end_date'];
        $arrAmount = $arrPostedData['amount'];
        $arrTotalIssue = $arrPostedData['camp_total_issue'];
        $arrNumberOfYear = $arrPostedData['numberOfYear'];

        $intArrCounter = 0;
        #Create a unique Transaction Id
        /**$strTransactionPrefix = date("y").date("m");
        $strTransactionId = substr(number_format(time() * rand(),0,'',''),0,6);
        $strUniqueTransactionKey = $strTransactionPrefix.$strTransactionId;*/
        $strUniqueTransactionKey = $this->fnCheckForUniqueTransactionKey();
        foreach ($arrMagazineCode as $details) {
            $intCounter = 0;
            # Check for the given magazine id.
            $intDecMagId = $arrMagazineCode[$intArrCounter];
            $arrCheckMagazine = $this->promotions->fnGetDetailsOfTable('magazine', 'magezine_id', $intDecMagId);
            if (empty($arrCheckMagazine)) {
                array_push($arrMagazineCode[$intArrCounter],$arrMagazineCodeError);
                $intCounter++;
            }
            $intDecMagId = $arrCheckMagazine[0]['id'];

            # If user has entered the promotional code then check whether the promotional code has associate with it.
            if ($arrPostedData['promo_code'] != "") {
                $boolCheck = $this->promotions->fnGetCampaignMagazineDetails($arrMagazineCode[$intArrCounter], $arrPostedData['promo_code']);
                if (empty($boolCheck)) {
                    array_push($arrMagazineCode[$intArrCounter],$arrMagazineCodeError);
                    $intCounter++;
                }
            }
            if ($intCounter == 0) {
                # Create a array of records.
                $arrInsertArray = array();
                $arrInsertArray['transaction_date'] = date("Y-m-d");
                $arrInsertArray['subscriber_id'] = $intDecUserId;
                $arrInsertArray['subscriber_name'] = $strSubscriberName;
                $arrInsertArray['product_id'] = $intDecMagId;
                $arrInsertArray['period'] = $arrNumberOfYear[$intArrCounter];
                $arrInsertArray['subscribed_on'] = date("Y-m-d", strtotime($arrStartDate[$intArrCounter]));
                $arrInsertArray['subscription_end_on'] = date("Y-m-d", strtotime($arrEndDate[$intArrCounter]));
                $arrInsertArray['promo_code'] = ($arrPostedData['promo_code'] == "")? null:$arrPostedData['promo_code'];
                $arrInsertArray['status'] = 1;
                $arrInsertArray['start_issue'] = $arrStartIssue[$intArrCounter];
                $arrInsertArray['end_issue'] = $arrEndIssue[$intArrCounter];
                $arrInsertArray['amount'] = $arrAmount[$intArrCounter];
                $arrInsertArray['total_amount'] = $arrAmount[$intArrCounter];;
                $arrInsertArray['mode_of_payment'] = 1;
                $arrInsertArray['currency_of_payment'] = 1;
                $arrInsertArray['no_of_issue'] = $arrTotalIssue[$intArrCounter];

                $arrInsertArray['transaction_id'] = $strUniqueTransactionKey;

                # Save the Transaction details.
                $this->subscribers->fnSave('transaction', $arrInsertArray);
            }
            $intArrCounter++;
        }

        if($this->input->post('tr_id') != ''){
            $tr_id = (int)base64_decode($this->input->post('tr_id'));
            $arrUdpArray = array('is_active' => '5');
            $this->subscribers->fnUpdateTransactionPh($arrUdpArray, $tr_id);
        }

        # Put the comment If this subscription is regarding the transfer
        $this->fnTransferMagazineSessionDetails($intDecMagId, $intDecUserId);
        # Redirect with the success message.
        $this->session->set_flashdata('success', 'subscribed magazine has been added');
        $strRedirectPath = base_url().'index.php/subscriber/make_payment/?sub_id='.base64_encode($intDecUserId)."&transaction_id=".base64_encode($strUniqueTransactionKey);
        redirect($strRedirectPath);
    }



    /**
     *  Function to update the subscription.
     * @Author : Himanshu Charegaonkar
     * @Access : Public
     */
    public function edit_subscribed_magazine()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }

        # Check for the given subscriber id.
        $intDecUserId = (int)base64_decode($_GET['user_id']);
        if ($intDecUserId == 0) {
            $this->session->set_flashdata('error', 'Please provide valid subscriber Id');
            $strRedirectPath = base_url().'index.php/subscriber/subscriber_list';
            redirect($strRedirectPath);
        }

        # Check for the given magazine id.
        $intTransactionId = (int) base64_decode($_GET['id']);
        if ($intTransactionId == 0) {
            $this->session->set_flashdata('error', 'Please provide valid subscription Id');
            $strRedirectPath = base_url().'index.php/subscriber/subscribe_product/?user_id='.$_POST['subscriber_id'];
            redirect($strRedirectPath);
        }

        # Load the required model.
        $this->load->model('subscribers');
        //$arrResultSet = $this->subscribers->fnGetRequiredDetails($intDecUserId, $intDecMagId);
        $arrTransactionDetails = $this->subscribers->fnGetDetails("transaction", $intTransactionId);

        #Check whether the given subscription Id is valid or not.
        if (count($arrTransactionDetails) == 0) {
            $this->session->set_flashdata('error', 'Given subscription Id is not valid');
            $strRedirectPath = base_url().'index.php/subscriber/subscribe_product/?user_id='.$_POST['subscriber_id'];
            redirect($strRedirectPath);
        }

        #Now get the Magazine code to display.
        $arrMagazineInfo = $this->subscribers->fnGetDetails("magazine", $arrTransactionDetails[0]['product_id']);
        $arrMagazineDetails[0]['magazine_code'] = $arrMagazineInfo[0]['magezine_id'];
        $arrMagazineDetails[0]['magazineId'] = $arrMagazineInfo[0]['id'];

        # Get the Subscribers Name.
        $arrSubscriberName = $this->subscribers->fnGetDetails("subscriber", $intDecUserId);
        $arrMagazineDetails[0]['subscriber_name'] = ucwords($arrSubscriberName[0]['first_name']." ".$arrSubscriberName[0]['last_name']);
        # set form fields rules.
        $this->load->helper(array('form', 'url'));
        $this->form_validation->set_rules('start_issue', 'Start Issue', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('end_issue', 'End Issue', 'trim|required|max_length[100]|xss_clean');
        # Check whether the validation turns true.
        if ($this->form_validation->run() == TRUE) {
            $arrPostedData = $_POST;
            $intTransactionId = (int)base64_decode($arrPostedData['transaction_id']);
            $intSubscriberId = (int)base64_decode($arrPostedData['subscriber_id']);

            if ($intTransactionId == 0 || $intSubscriberId == 0) {
                $this->session->set_flashdata('error', 'please provide valid information');
                $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$arrPostedData['subscriber_id'];
                redirect($strRedirectPath);
            }

            $arrUpdatedInfo = array();
            $arrUpdatedInfo['period'] = $arrPostedData['number_of_year'];
            $arrUpdatedInfo['totalNCopies'] = $arrPostedData['number_of_copies'];
            $arrUpdatedInfo['subscribed_on'] = date("Y-m-d", strtotime($arrPostedData['start_date']));
            $arrUpdatedInfo['subscription_end_on'] = date("Y-m-d", strtotime($arrPostedData['end_date']));
            $arrUpdatedInfo['start_issue'] = $arrPostedData['start_issue'];
            $arrUpdatedInfo['end_issue'] = $arrPostedData['end_issue'];
            $arrUpdatedInfo['amount'] = $arrPostedData['amount'];
            $arrUpdatedInfo['total_amount'] = $arrPostedData['amount'];
            $arrUpdatedInfo['no_of_issue'] = $arrPostedData['no_issues'];
            $this->subscribers->fnUpdateSubscriptionDetails($intTransactionId,  $arrUpdatedInfo);

            $this->session->set_flashdata('success', 'subscribed magazine details has been updated');
            $strRedirectpath = base_url().'index.php/subscriber/preview/?user_id='.$arrPostedData['subscriber_id'];
            redirect($strRedirectpath);

        } else {
            /** if validation errros found then redirect  **/
            $strValidationErrors = validation_errors();
            if ($strValidationErrors != "" ) {
                $this->session->set_flashdata('error', $strValidationErrors);
                $strRedirectpath = base_url().'index.php/subscriber/preview/?user_id=='.$_GET['user_id'];
                redirect($strRedirectpath);
            } else {
                $arrData['middle']   = 'subscriber/edit_subscribe_product';
                $arrData['arrResultSet'] = $arrTransactionDetails[0];
                $arrData['arrMagazineDetails'] = $arrMagazineDetails[0];
                $arrData['intTransactionId'] = $intTransactionId;
                $this->load->view('admin/templates/template', $arrData);
            }
        }
    } // Function edit_subscribed_magazine ends.

    /**
     * Function to delete requested subscription.
     * @Author : Himanshu Charegaonkar
     * @Access : Public
     */
    public function delete_subscribed_magazine()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }

        # Check for the given subscriber id.
        $intDecUserId = (int)base64_decode($_GET['user_id']);
        if ($intDecUserId == 0) {
            $strRedirectPath = base_url().'index.php/subscriber/preview';
            redirect($strRedirectPath);
        }

        # Check for the given transaction primary id.
        $intSubscriptionId = (int) base64_decode($_GET['id']);
        if ($intSubscriptionId == 0) {
            $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$_GET['user_id'];
            redirect($strRedirectPath);
        }
        # Load the required model.
        $this->load->model('subscribers');

        # delete requested subscription
        $arrResultSet = $this->subscribers->fnDeleteSubscription($intSubscriptionId);

        # Redirect with success message.
        $this->session->set_flashdata('success', 'Subscription has been deleted');
        $strRedirectpath = base_url().'index.php/subscriber/preview/?user_id='.$_GET['user_id'];
        redirect($strRedirectpath);
    } // Function delete_subscribed_magazine ends.

    /*
     * Function make_payment
     * Function to make the initial payment
     * @author	Himanshu Charegaonkar
     * @access	public
     *
     */
    public function make_payment()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }

        # Load the required model.
        $this->load->model('subscribers');
        $arrGetData = $_GET;
        $encSubscriberId =  $arrGetData['sub_id'];
        $encTransactionId = $arrGetData['transaction_id'];
        $strDecodedSubscriberId = base64_decode($encSubscriberId);
        $intTransactionId = base64_decode($encTransactionId);

        # now check whether the given user id is valid or not.
        $arrUserDetails = $this->subscribers->fnGetAllDetails('subscriber', 'id', $strDecodedSubscriberId);
        if (count($arrUserDetails) == 0 || empty($arrUserDetails)) {
            $this->session->set_flashdata('error', "Given subscriber Id dosen't exist");
            $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$encSubscriberId;
            redirect($strRedirectPath);
        }

        # Proceed to get require Information.

        #1. Get the Subscriber's Name.
        $strSubscriberName = $arrUserDetails[0]['first_name']." ".$arrUserDetails[0]['last_name'];


        #2.  now check whether the given magazine id is valid or not And get the Details of it
        $arrTransactionDetails = $this->subscribers->fnAddAllMagazineToCart($intTransactionId);
        if (count($arrTransactionDetails) == 0 || empty($arrTransactionDetails)) {
            $this->session->set_flashdata('error', "Given transaction code dosen't exist");
            $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$encSubscriberId;
            redirect($strRedirectPath);
        }

        $arrMagazineDetails = array();

        foreach($arrTransactionDetails as $key => $transaction) {
            $arrMagazineDetails = $this->subscribers->fnGetAllDetails('magazine', 'id', $transaction['product_id']);
            $arrTransactionDetails[$key]['magazine_code'] = $arrMagazineDetails[0]['magezine_id'];
            $arrCurrency = $this->subscribers->fnGetAllDetails('currency', 'id', $transaction['currency_of_payment']);
            $arrTransactionDetails[$key]['currency'] = $arrCurrency[0]['name'];

        }

        #5. Get the Available Agents.
        $arrAgent = $this->subscribers->fnGetDetails('agent');

        $arrPaymentMethods = $this->subscribers->fnGetDetails('payment_mode');

        $arrData['middle']   = 'subscriber/make_payment';
        $arrData['transaction_details'] = $arrTransactionDetails;
        $arrData['strName'] = $strSubscriberName;
        $arrData['strTransactionId'] = $encTransactionId;
        $arrData['strSubscriberId'] = $encSubscriberId;
        $arrData['agent_details'] = $arrAgent;
        $arrData['arrPaymentMethods'] = $arrPaymentMethods;

        //echo "<pre>";print_r($arrData);exit;
        #$arrData['arrAllMagazines']   = $arrAllMagazines;


        $this->load->view('admin/templates/template', $arrData);

    }

    /**
     *   Function to proceed towards finalize payment.
     * @Author : Himanshu Charegaonkar
     * @Access : Public
     */
    public function proceed_payment()
    {

        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }

        # get the posted data.
        $arrPostedData = $_POST;
        $strPaymentMethod = $arrPostedData['payment_type'];
        if ($strPaymentMethod == "" || $strPaymentMethod == 0) {
            $this->session->set_flashdata('error', "Select a proper payment method");
            $strRedirectPath = base_url().'index.php/subscriber/make_payment';
            redirect($strRedirectPath);
        }
        # Get the transaction Id
        $intTransactionId = base64_decode($arrPostedData['en_Transaction_id']);

        
        if ($intTransactionId == 0) {
            $this->session->set_flashdata('error', "Please provide valid information");
            $strRedirectPath = base_url().'index.php/subscriber/make_payment';
            redirect($strRedirectPath);
        }
        # get the subscriber name.
        $this->load->model('subscribers');

        # get the currency id
        $strCurrency = $_POST['currency'];
        $arrCurrency = $this->subscribers->fnGetAllDetails('currency', 'name', $strCurrency);
        $intCurrency = $arrCurrency[0]['id'];

        # Now get all the related information with the help of transaction Id.
        $arrTransactionDetails = $this->subscribers->fnAddAllMagazineToCart($intTransactionId);
        if (count($arrTransactionDetails) == 0 || empty($arrTransactionDetails)){
            $this->session->set_flashdata('error', "Please provide valid transaction Id");
            $strRedirectPath = base_url().'index.php/subscriber/subscriber_list';
            redirect($strRedirectPath);
        }
        $arrAllTransactionPrimeId = array();
        foreach($arrTransactionDetails as $indDetails) {
            $arrAllTransactionPrimeId[] = $indDetails['id'];
        }
        $strAllPrimeIds =  implode(',', $arrAllTransactionPrimeId);
        # IF current transaction status is Not Paid then only update the status of the transaction to processing.
        if ($arrTransactionDetails[0]['status'] == 1) {
            # create transaction array to Update
            $arrUpdateValue = array();
            $arrUpdateValue['mode_of_payment'] = $strPaymentMethod;
            $arrUpdateValue['status'] = 2;
            $arrUpdateValue['currency_of_payment'] = $intCurrency;
            $arrUpdateValue['is_suspended'] = '0';

            # Get the Agent information.
            $intAgentId = ($arrPostedData['cname'])?$arrPostedData['cname']:null;
            $strOtherDetails = ($arrPostedData['other_details'])?$arrPostedData['other_details']:null;
            # now if payment method is cash or 1.
            $strCampName = NULL;
            $strLocation = NULL;
            if ($strPaymentMethod == 1) {
                # Save the cash payment details in respective Table.
                foreach($arrTransactionDetails as $trans_Details) {
                    $intCashArray = array();
                    $intCashArray['transaction_id'] = $trans_Details['id'];
                    $intCashArray['agent_id'] = $intAgentId;
                    $intCashArray['other_details'] = $strOtherDetails;
                    #insert the transaction.
                    $this->subscribers->fnSaveAllDetails('payment_cash', $intCashArray);
                }
            }

            # now check if payment method is cheque
            if ($strPaymentMethod == 2) {
                $strChequeDate =  $arrPostedData['cheque_date'];
                $strChequeNumber =  $arrPostedData['cheque_num'];
                $strChequeBankName =  $arrPostedData['bank_num'];
                $strCheckDate = preg_match("^\\d{1,2}/\\d{2}/\\d{4}^", $strChequeDate );
                if ($strChequeDate == " " || $strCheckDate == 0) {
                    $this->session->set_flashdata('error', "Give date in proper format");
                    $strRedirectPath = base_url().'index.php/subscriber/make_payment';
                    redirect($strRedirectPath);
                } elseif ($strChequeNumber == "") {
                    $this->session->set_flashdata('error', "Given cheque number is not valid");
                    $strRedirectPath = base_url().'index.php/subscriber/make_payment';
                    redirect($strRedirectPath);
                } elseif($strChequeBankName == "") {
                    $this->session->set_flashdata('error', "Given cheque number is not valid");
                    $strRedirectPath = base_url().'index.php/subscriber/make_payment';
                    redirect($strRedirectPath);
                }

                # Save cheque related details in subsequent tables.
                foreach($arrTransactionDetails as $trans_Details) {
                    $intChequeArray = array();
                    $intChequeArray['transaction_id'] = $trans_Details['id'];
                    $intChequeArray['cheque_date'] = DateTime::createFromFormat('d/m/Y', $strChequeDate)->format('Y-m-d');
                    $intChequeArray['cheque_number'] = $strChequeNumber;
                    $intChequeArray['issued_bank'] = $strChequeBankName;
                    $intChequeArray['agent_id'] = $intAgentId;
                    $intChequeArray['other_details'] = $strOtherDetails;

                    #insert the transaction.
                    $this->subscribers->fnSaveAllDetails('payment_cheque', $intChequeArray);
                }
            }

            # now check if payment method is credit card.
            if ($strPaymentMethod == 3) {
                # Getting the Credit Card information and create an array of records.
                $strCCardName =  $arrPostedData['cc_name'];
                $strCCardNumber =  $arrPostedData['cc_number1'].$arrPostedData['cc_number2'].$arrPostedData['cc_number3'].$arrPostedData['cc_number4'];
                $strCCardExpiry =  $arrPostedData['credit_card_exp_month']."-".$arrPostedData['credit_card_exp_year'];
                $strCCardBank =  $arrPostedData['issue_bank_num'];
                if ($strCCardName == "") {
                    $this->session->set_flashdata('error', "Give credit card name");
                    $strRedirectPath = base_url().'index.php/subscriber/make_payment';
                    redirect($strRedirectPath);
                }
                /*elseif($strCCardNumber == "" || strlen(trim($strCCardNumber)) != 16) {
                $this->session->set_flashdata('error', "Credit card number is of 16 digit");
                $strRedirectPath = base_url().'index.php/subscriber/make_payment';
                redirect($strRedirectPath);
                }
                elseif($strCCardExpiry == "") {
                    $this->session->set_flashdata('error', "Give credit card expiry");
                    $strRedirectPath = base_url().'index.php/subscriber/make_payment';
                    redirect($strRedirectPath);
                } elseif ($strCCardBank == "") {
                    $this->session->set_flashdata('error', "Give name of bank which issued credit card");
                    $strRedirectPath = base_url().'index.php/subscriber/make_payment';
                    redirect($strRedirectPath);
                }*/
                # Save credit Card related details in subsequent tables.
                foreach($arrTransactionDetails as $trans_Details) {
                    $intCCArray = array();
                    $intCCArray['transaction_id'] = $trans_Details['id'];
                    $intCCArray['card_number'] = $strCCardNumber;
                    $intCCArray['card_name'] = $strCCardName;
                    $intCCArray['card_expiry'] = $strCCardExpiry;
                    $intCCArray['card_bank'] = $strCCardBank;
                    $intCCArray['agent_id'] = $intAgentId;
                    $intCCArray['other_details'] = $strOtherDetails;
                    #insert the transaction.
                    $this->subscribers->fnSaveAllDetails('payment_credit_card', $intCCArray);
                }
            }

            # now check if the payment mode is online transfer.
            if ($strPaymentMethod == 4) {
                $strOlBankName =  $arrPostedData['bank_name'];
                $strOlTransactionId = $arrPostedData['transaction_id'];
                $strOlTransactionDate = $arrPostedData['transaction_date'];
                $strCheckDate = preg_match("^\\d{1,2}/\\d{2}/\\d{4}^", $strOlTransactionDate );

                if ($strOlBankName == "") {
                    $this->session->set_flashdata('error', "Give name of bank which used for online transfer");
                    $strRedirectPath = base_url().'index.php/subscriber/make_payment';
                    redirect($strRedirectPath);
                } elseif ($strOlTransactionId == "") {
                    $this->session->set_flashdata('error', "Give transaction id");
                    $strRedirectPath = base_url().'index.php/subscriber/make_payment';
                    redirect($strRedirectPath);
                } /**elseif ($strOlTransactionDate == "" || $strCheckDate == 0 ){
                $this->session->set_flashdata('error', "Give proper transaction id");
                $strRedirectPath = base_url().'index.php/subscriber/make_payment';
                redirect($strRedirectPath);
                } **/

                # Save online transfer related details in subsequent tables.
                foreach($arrTransactionDetails as $trans_Details) {
                    $intCCArray = array();
                    $intCCArray['transaction_id'] = $trans_Details['id'];
                    $intCCArray['online_transaction_id'] = $strOlTransactionId;
                    $intCCArray['isseud_bank_name'] = $strOlBankName;
                    $intCCArray['transaction_date'] = DateTime::createFromFormat('d/m/Y', $strOlTransactionDate)->format('Y-m-d');
                    $intCCArray['agent_id'] = $intAgentId;
                    $intCCArray['other_details'] = $strOtherDetails;

                    #insert the transaction.
                    $this->subscribers->fnSaveAllDetails('payment_online', $intCCArray);
                }
            }

            # If payment method is 5 :- Club Membership
            if ($strPaymentMethod == 5) {
                # Save online transfer related details in subsequent tables.
                foreach($arrTransactionDetails as $trans_Details) {
                    $intCCArray = array();
                    $intCCArray['transaction_id'] = $trans_Details['id'];
                    $intCCArray['agent_id'] = $intAgentId;
                    $intCCArray['other_details'] = $strOtherDetails;

                    #insert the transaction as Club membership.
                    $this->subscribers->fnSaveAllDetails('payment_club_membership', $intCCArray);
                }
            }

            # If payment method is 6 :- Complementary
            if ($strPaymentMethod == 6) {
                # Save online transfer related details in subsequent tables.
                foreach($arrTransactionDetails as $trans_Details) {
                    $intCCArray = array();
                    $intCCArray['transaction_id'] = $trans_Details['id'];
                    $intCCArray['agent_id'] = $intAgentId;
                    $intCCArray['other_details'] = $strOtherDetails;

                    #insert the transaction as Club membership.
                    $this->subscribers->fnSaveAllDetails('payment_complementary', $intCCArray);
                }
            }

            # If payment method is 7 :- payment_replacement
            if ($strPaymentMethod == 7) {
                # Save online transfer related details in subsequent tables.
                foreach($arrTransactionDetails as $trans_Details) {
                    $intCCArray = array();
                    $intCCArray['transaction_id'] = $trans_Details['id'];
                    $intCCArray['agent_id'] = $intAgentId;
                    $intCCArray['other_details'] = $strOtherDetails;

                    #insert the transaction as Club membership.
                    $this->subscribers->fnSaveAllDetails('payment_replacement', $intCCArray);
                }
            }

            # If payment method is 8 :- payment_invoice
            if ($strPaymentMethod == 8) {
                # Save online transfer related details in subsequent tables.
                foreach($arrTransactionDetails as $trans_Details) {
                    $intCCArray = array();
                    $intCCArray['transaction_id'] = $trans_Details['id'];
                    $intCCArray['agent_id'] = $intAgentId;
                    $intCCArray['other_details'] = $strOtherDetails;

                    #insert the transaction as Club membership.
                    $this->subscribers->fnSaveAllDetails('payment_invoice', $intCCArray);
                }
            }
            # If payment method is 9 :- NETS_invoice
            if ($strPaymentMethod == 9) {
                # Save online transfer related details in subsequent tables.
                foreach($arrTransactionDetails as $trans_Details) {
                    $intCCArray = array();
                    
                    $intCCArray['nets_transaction_id'] = $arrPostedData['NETS_transaction_id'];
                    $intCCArray['transaction_id'] = $trans_Details['id'];
                    $intCCArray['agent_id'] = $intAgentId;
                    $intCCArray['transaction_date'] = DateTime::createFromFormat('d/m/Y', $arrPostedData['NETS_transaction_date'])->format('Y-m-d');
                    if($strOtherDetails != null){$intCCArray['other_details'] = $strOtherDetails;}
                    

                    #insert the transaction as Club membership.
                    $this->subscribers->fnSaveAllDetails('payment_nets', $intCCArray);
                }
            }

            # If payment method is 10 :- Paynow
            if ($strPaymentMethod == 10) {
                # Save online transfer related details in subsequent tables.
                foreach($arrTransactionDetails as $trans_Details) {
                    $intCCArray = array();
                    
                    //$intCCArray['purchase_code'] = $arrPostedData['purchase_code'];
                    $intCCArray['transaction_id'] = $trans_Details['id'];
                    $intCCArray['agent_id'] = $intAgentId;
                    $intCCArray['purchase_date'] = date('Y-m-d');
                    if($strOtherDetails != null){$intCCArray['other_details'] = $strOtherDetails;}
                    
                    #insert the transaction as Club membership.
                    $this->subscribers->fnSaveAllDetails('payment_paynow', $intCCArray);
                }
            }

            # If payment method is 11 :- Voucher
            if ($strPaymentMethod == 11) {
                # Save online transfer related details in subsequent tables.
                foreach($arrTransactionDetails as $trans_Details) {
                    $intCCArray = array();
                    
                    $intCCArray['transaction_id'] = $trans_Details['id'];
                    $intCCArray['agent_id'] = $intAgentId;
                    $intCCArray['purchase_date'] = date('Y-m-d');
                    if($strOtherDetails != null){$intCCArray['other_details'] = $strOtherDetails;}
                    
                    #insert the transaction as Club membership.
                    $this->subscribers->fnSaveAllDetails('payment_voucher', $intCCArray);
                }
            }

            # After insertion if payment details Add comment to subscriber profile with transaction id.
            if (trim($_POST['message_desc']) != '') {
                $arrCommentRecord = array();
                $arrCommentRecord['subscriber_id'] = (int)base64_decode($_POST['encSubscriberId']);
                $arrCommentRecord['comment'] =  trim($_POST['message_desc']);
                $arrCommentRecord['comment_by'] = $this->session->userdata('id');
                $arrCommentRecord['comment_date_time'] = strtotime(Date("Y-m-d H:i:s"));
                $arrCommentRecord['comment_type'] = 'transaction';
                $arrCommentRecord['transaction_id'] = $intTransactionId;
                $this->subscribers->fnSave('subscriber_comment', $arrCommentRecord);
            }

            //adding 
            $otherData['payment_date'] = $this->input->post('payment_date');
            $otherData['reference_no'] = $this->input->post('reference_no');
            //$otherData['voucher'] = $this->input->post('voucher');
            $otherData['discount_rate'] = $this->input->post('discount_rate');
       
               
                 
           # After successful submission of the child payment details, Update the transaction details.
            $this->subscribers->fnUpdateMagazinePayStatus($strAllPrimeIds, $arrUpdateValue['mode_of_payment'], $arrUpdateValue['currency_of_payment'],$otherData);
            $this->session->set_flashdata('success', 'Your payment is under process');
            $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$_POST['encSubscriberId'];
            redirect($strRedirectPath);
        } else {
            # IF payment already done, then without performing any activity redirect it to the preview page.
            $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$_POST['encSubscriberId'];
            redirect($strRedirectPath);
        }

    }


    /**
     * Function to generate the invoice pdf.
     * @param string $arrData
     * @param string $filename
     * @param string $location
     * return none
     * @Author : Himanshu Charegaonkar
     * @Access : Public
     */
    function generate_invoice_pdf()
    {
        $strEncodedData = base64_decode($_GET['data']);
        $strDecodeData = (array)json_decode($strEncodedData);
        $arr_data = $strDecodeData;
        $this->load->library('common');
        $arr_data['list'] = $list;
        $arrData['arrData']   = $arr_data;
        $arr_data['heading'] = array('Case#', 'Submission Date', 'Status');
        $this->common->getPDFReport_common($arr_data, 'case.pdf', 'subscriber/demo');exit;
    }

    /**
     *  Function to send an email.
     */
    function fnSendEmail()
    {
        $intTransactionId = $_POST['transaction_id'];

        # get the subscriber name.
        $this->load->model('subscribers');

        $arrTransactionInfo = $this->subscribers->fnGetTransactionDetails($intTransactionId);
        $CI_OBJ = & get_instance();
        $arrSample['arrData'] = $arrTransactionInfo[0];
        $html = $CI_OBJ->load->view('subscriber/demo', $arrSample, true);

        $this->load->library('email');

        $strSubject = 'Invoice of the Magazine';

        $this->email->set_mailtype("html");
        $this->email->from('team@smsystem.com', 'Subscription Management system');
        $this->email->to($arrData['sub_email']);

        $this->email->subject($strSubject);
        $this->email->message($html);

        # before create an transaction array first check the whether the payment for this already done or not.
        # get the subscriber name.
        $this->load->model('subscribers');
        $boolStatus = $this->subscribers->fnCheckNotification($arrData['sub_id'], $arrData['mag_id'], $strSubject);
        if ($boolStatus == 0) {
            $boolResult = $this->email->send();
            #insert the transaction.
            $arrRecords = array();
            $arrRecords['subscriber_id'] = $arrData['sub_id'];
            $arrRecords['name'] = $arrData['sub_name'];
            $arrRecords['magazine_id'] = $arrData['mag_id'];
            $arrRecords['subject'] = $strSubject;
            $arrRecords['status'] = 'sent';
            $arrRecords['send_on'] = date("Y-m-d");
            $arrRecords['message'] = $html;
            $intNewTransactionId = $this->subscribers->fnSaveAllDetails('notification', $arrRecords, $strSubject);
            echo "Email send successfully";exit;
        }
        echo "Email Already send";exit;

    }

    /**
     *  function  transaction_listing
     *  Fucntion to list out all transactions.
     * @param int $offset
     */
    function transaction_listing($offset = 1)
    {
        # get the subscriber name.
        $this->load->model('subscribers');

        # Include required liabraries.
        $this->load->library('pagination');
        $this->load->library('Backend_pagination');

        $strSearchKey = "";

        if (count($_GET) > 0) { // If there is date then put the date related condition.
            /*if ($_GET['from_date'] != "" && $_GET['to_date'] != "") {
                $offset = 1;
                $strStartDate = DateTime::createFromFormat('d/m/Y', $_GET['from_date'])->format('Y-m-d');
                $strEndDate = DateTime::createFromFormat('d/m/Y', $_GET['to_date'])->format('Y-m-d');

                $strSearchKey = $strSearchKey. " AND T.transaction_date BETWEEN '".$strStartDate."' AND '".$strEndDate."'";
            } */
            if ($_GET['transaction_id'] != "") {
                $offset = 1;
                $strSearchKey = $strSearchKey. " AND T.transaction_id like '%".$_GET['transaction_id']."%'";
            }
            if ($_GET['payment_mode'] !== "") { // If there is payment mode then put the date related condition.
                $offset = 1;
                $strSearchKey = $strSearchKey. " AND T.mode_of_payment = ".$_GET['payment_mode'];
            }

            if ($_GET['status'] != "") { // If there is status then put the date related condition.
                $offset = 1;
                if ($_GET['status'] == '6') {
                    $strSearchKey = $strSearchKey. " AND T.is_suspended ='1'";
                } else {
                    $strSearchKey = $strSearchKey. " AND T.status =".$_GET['status'];
                }
                //echo $strSearchKey;exit;
            }
        }

        $arrResult = $this->subscribers->fnGetTransactionList("","", $strSearchKey, 1);

        # Functionality of pagination.
        $custom_config['uri_segment'] = 3;
        $this->backend_pagination->setup_pagination($custom_config);
        $this->backend_pagination->arr_data = $arrResult;
        $this->backend_pagination->offset = $offset;
        $this->backend_pagination->url = 'index.php/subscriber/transaction_listing/';
        $this->backend_pagination->setup_pagination();
        $arrData['pagination']  = $this->backend_pagination->strpagination;
        $arrDetails = $this->subscribers->fnGetTransactionList($this->backend_pagination->limit,$this->backend_pagination->offsetPage, $strSearchKey, 1);
        //echo "<pre>";print_r($arrDetails);exit;
        $arrData['middle']   = 'subscriber/transaction_listing';
        $arrData['arrData']   = $arrDetails;
        $arrData['arrGetData']   = $_GET;
        $this->load->view('admin/templates/template', $arrData);
    }

    /**
     * Function notification_listing
     * Function to list out the notification.
     * @param int $offset
     */
    function notification_listing($offset = 1)
    {

        # get the subscriber name.
        $this->load->model('subscribers');

        # Include required liabraries.
        $this->load->library('pagination');
        $this->load->library('Backend_pagination');

        $strSearchKey = "";

        if (count($_GET) > 0) { // If there is date then put the date related condition.
            if ($_GET['from_date'] != "" && $_GET['to_date'] != "") {
                $offset = 1;
                $strStartDate = DateTime::createFromFormat('d/m/Y', $_GET['from_date'])->format('Y-m-d');
                $strEndDate = DateTime::createFromFormat('d/m/Y', $_GET['to_date'])->format('Y-m-d');

                $strSearchKey = $strSearchKey. " AND send_on BETWEEN '".$strStartDate."' AND '".$strEndDate."'";
            }

            if ($_GET['status'] != "") { // If there is status then put the date related condition.
                $offset = 1;
                $strSearchKey = $strSearchKey. " AND status ='".$_GET['status']."'";
            }
        }

        $arrResult = $this->subscribers->fnGetAllNotifications("","", $strSearchKey);

        # Functionality of pagination.
        $custom_config['uri_segment'] = 3;
        $this->backend_pagination->setup_pagination($custom_config);
        $this->backend_pagination->arr_data = $arrResult;
        $this->backend_pagination->offset = $offset;
        $this->backend_pagination->url = 'index.php/subscriber/notification_listing/';
        $this->backend_pagination->setup_pagination();
        $arrData['pagination']  = $this->backend_pagination->strpagination;
        $arrDetails = $this->subscribers->fnGetAllNotifications($this->backend_pagination->limit,$this->backend_pagination->offsetPage, $strSearchKey);

        $arrAllSubscribers = $this->subscribers->fnGetDetailsWithEmail();
        $arrData['middle']   = 'subscriber/notification';
        $arrData['arrData']   = $arrDetails;
        $arrData['arrGetData']   = $_GET;
        $arrData['arrAllSubscribers']   = $arrAllSubscribers;
        $this->load->view('admin/templates/template', $arrData);

    }

    /**
     *  Function finalise_payment
     *  Function to make  final payment.
     * @access: Public
     * @Author: Himanshu Charegaonkar
     */
    public function finalise_payment($offset = 1)
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }

        # get the subscriber name.
        $this->load->model('subscribers');

        # Include required liabraries.
        $this->load->library('pagination');
        $this->load->library('Backend_pagination');



        $strSearchKey = " AND T.status = 2";


        if (count($_GET) > 0) { // If there is date then put the date related condition.
            if ($_GET['from_date'] != "" && $_GET['to_date'] != "") {
                $offset = 1;
                $strStartDate = date("Y-m-d", strtotime($_GET['from_date']));
                $strEndDate = date("Y-m-d", strtotime($_GET['to_date']));

                $strSearchKey = $strSearchKey. " AND T.transaction_date BETWEEN '".$strStartDate."' AND '".$strEndDate."'";
            }
            if ($_GET['payment_mode'] !== "") { // If there is payment mode then put the date related condition.
                $offset = 1;
                $strSearchKey = $strSearchKey. " AND T.mode_of_payment =".$_GET['payment_mode'];
            }

            if ($_GET['status'] != "") { // If there is status then put the date related condition.
                $offset = 1;
                $strSearchKey = $strSearchKey. " AND T.status =".$_GET['status'];
            }
        }
        $arrProcessingPayments = $this->subscribers->fnGetProcessingPayments("", "", $strSearchKey,1);

        # Functionality of pagination.
        $custom_config['uri_segment'] = 3;
        $this->backend_pagination->setup_pagination($custom_config);
        $this->backend_pagination->arr_data = $arrProcessingPayments;
        $this->backend_pagination->offset = $offset;
        $this->backend_pagination->url = 'index.php/subscriber/finalise_payment/';
        $this->backend_pagination->setup_pagination();
        $arrData['pagination']  = $this->backend_pagination->strpagination;
        $arrDetails = $this->subscribers->fnGetProcessingPayments($this->backend_pagination->limit,$this->backend_pagination->offsetPage, $strSearchKey, 1);
        $arrData['middle']   = 'subscriber/finalise_payment';
        $arrData['arrData']   = $arrDetails;
        $this->load->view('admin/templates/template', $arrData);
    }

    /**
     *  Function to generate the receipt of transaction (Final voucher)
     */
    public function receipt()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }

        $router = & load_class('Router', 'core');
        $class_name = $router->fetch_class();
        $method_name = $router->fetch_method();
        $strModule = $method_name;
        if ($strModule == "index") {
            $strModule = "";
        } else {
            $strModule = "/".$strModule;
        }
        $strTotalUrlToCheck = $class_name.$strModule;
        $arr_session = $this->session->all_userdata();
        $level_id = $arr_session['level'];
        $arr_result = $this->user->fnCheckAccessIsAllowed($level_id, $strTotalUrlToCheck);
        if (empty($arr_result)) {
            redirect($_SERVER['HTTP_REFERER']);
        }
        # Check for the given id.
        $intTransactionId = (int) base64_decode($_GET['id']);
        if ($intTransactionId == 0) {
            $this->session->set_flashdata('error', 'Please select valid transaction id');
            $strRedirectPath = base_url().'index.php/subscriber/finalise_payment';
            redirect($strRedirectPath);
        }


        # get the subscriber name.
        $this->load->model('subscribers');

        # To move further, check the status of transaction.
        //$arrTransactionDetails = $this->subscribers->fnGetAllDetails('transaction', 'transaction_id', $intTransactionId);
        $arrTransactionDetails = $this->subscribers->fnAddAllMagazineToReceipt($intTransactionId);
        //echo "<pre>";print_r($arrTransactionDetails);exit;
        $intCounter = 0;
        $arrProcessingTransactions = array();
        foreach($arrTransactionDetails as $indTransaction) {
            $arrMagazineInfo = $this->subscribers->fnGetDetails("magazine", $indTransaction['product_id']);
            $arrTransactionDetails[$intCounter]['magazine_code'] = $arrMagazineInfo[0]['magezine_id'];

            $arrSubscriberInfo = $this->subscribers->fnGetDetails("subscriber", $indTransaction['subscriber_id']);
            $arrTransactionDetails[$intCounter]['subscriber_name'] = ucwords($arrSubscriberInfo[0]['last_name']." ".$arrSubscriberInfo[0]['first_name']);

            if ($indTransaction['promo_code'] != null || $indTransaction['promo_code'] > 0 ) {
                $arrPromoInfo = $this->subscribers->fnGetDetails("campaigns", $indTransaction['promo_code']);
                $arrTransactionDetails[$intCounter]['promo_code'] = $arrPromoInfo[0]['campeign_code'];
            }

            if ($indTransaction['status'] == 2) {
                $arrProcessingTransactions[] = $indTransaction['id'];
            }
            $intCounter++;
        }
        $strProcessingIds = implode(",", $arrProcessingTransactions);
        # IF the transaction status is processing then, make it as Paid.
        if ($strProcessingIds != "") {
            $this->subscribers->fnUpdateProcessingTransaction($strProcessingIds);
        }

        //$strSearchKey = " AND T.id =".$intTransactionId;

        # Call function which get all attributes of the required transaction.
        //$arrProcessingPayments = $this->subscribers->fnGetProcessingPayments("", "", $strSearchKey);

        # Call to auto send email function to send the email of transaction details.
        if ($arrTransactionDetails[0]['mode_of_payment'] != 5)
        $this->fnSendAutoEmail($intTransactionId);

        $arrResult = $arrTransactionDetails;
        $this->session->set_userdata('receipt_details', $arrResult);
        
        // $arrTableName = array (1 => 'Cash', 2 => 'Cheque', 3 => 'Credit Card', 4 => 'Payment Online', 5 => 'Club Membership', 6 => 'Complementary', 7 => 'Replacement', 8 => 'Invoice');

        $arrTableName = unserialize(paymentMethods_display);

        $arrData['middle']   = 'subscriber/receipt';
        $arrData['arrData']   = $arrTransactionDetails;
        $arrData['intTransactionId']   = $intTransactionId;
        $arrData['payment_method']   = $arrTableName;
        $this->load->view('admin/templates/template', $arrData);
    }

    /**
     * Function to generate the receipt of the pdf.
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function fnGenrateReceiptPdf()
    {
        $intTransactionId = (int)$_GET['id'];
        # get the subscriber name.
        $this->load->model('subscribers');
        # To move further, check the status of transaction.
        $arrTransactionDetails = $this->subscribers->fnGetTransactionInfo($intTransactionId, $intBool = 1);
        $strCampCode = "";
        if ($arrTransactionDetails[0]['promo_code'] != null) {
            $arrPromoInfo = $this->subscribers->fnGetDetails('campaigns', $arrTransactionDetails[0]['promo_code']);
            $strCampCode = $arrPromoInfo[0]['campeign_code'];
        }

        $arr_data = $this->session->userdata('receipt_details');
        $this->load->library('common');
        $arr_data['list'] = $list;
        $arrData['arrData']   = $arrTransactionDetails;
        $arrData['strCampCode'] = $strCampCode;
        $arrTransactionDetails[0]['strCampCode'] = $strCampCode;
        $arr_data['heading'] = array('Case#', 'Submission Date', 'Status');
        $this->common->getPDFReport_common($arrTransactionDetails, 'receipt.pdf', 'subscriber/receipt_pdf');exit;
    }

    /**
     *  Function to send an email.
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    function SendEmailForReceipt()
    {
        $intTransactionId = $_POST['transaction_id'];
        # get the subscriber name.
        $this->load->model('subscribers');

        # To move further, check the status of transaction.
        $arrTransactionDetails = $this->subscribers->fnGetTransactionInfo($intTransactionId, $intBool = 1);
        if ($arrTransactionDetails[0]['email'] == null || $arrTransactionDetails[0]['email'] == "") {
            echo "Subscriber's email address not found";exit;
        }

        $strCampCode = "";
        if ($arrTransactionDetails[0]['promo_code'] != null) {
            $arrPromoInfo = $this->subscribers->fnGetDetails('campaigns', $arrTransactionDetails[0]['promo_code']);
            $strCampCode = $arrPromoInfo[0]['campeign_code'];
        }
        $CI_OBJ = & get_instance();
        $arrSample['arrData'] = $arrTransactionDetails;
        $arrSample['strCampCode'] = $strCampCode;
        $html = $CI_OBJ->load->view('subscriber/receipt_pdf', $arrSample, true);
        $strSubject = 'Receipt of the Magazine';
        # before create an transaction array first check the whether the payment for this already done or not.
        # get the subscriber name.
        $this->load->model('subscribers');
        $boolStatus = $this->subscribers->fnCheckNotification($intTransactionId, $strSubject);
        if ($boolStatus == 0) {


            $this->load->library('email');
            $strSubject = 'Receipt of the Magazine';

            $this->email->set_mailtype("html");
            $this->email->from('team@smsystem.com', 'Subscription Management System');
            $this->email->to($arrTransactionDetails[0]['email']);

            $this->email->subject($strSubject);
            $this->email->message($html);

            $boolResult = $this->email->send();

            #insert the transaction.
            $arrRecords = array();
            $arrRecords['subject'] = $strSubject;
            $arrRecords['status'] = 'sent';
            $arrRecords['send_on'] = date("Y-m-d");
            $arrRecords['transaction_id'] = $intTransactionId;
            $intNewTransactionId = $this->subscribers->fnSaveAllDetails('notification', $arrRecords);
            echo "Email send successfully";exit;
        }
        echo "Email Already Send";exit;

    }

    /**
     * Function to check the whether the given email address is registered or not.
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    function fnCheckEmailExist()
    {
        $strEmailAddress = $_GET['email'];
        $strFirstName = $_GET['first_name'];
        $strLastName = $_GET['last_name'];
        $strDob = $_GET['dob'];
        $strField = $_GET['field'];
        # get the subscriber name.
        $this->load->model('subscribers');
        if ($strField == '') {
            $strBoolStatus = $this->subscribers->fnCheckEmailExist('email', $strEmailAddress);
        } elseif ($strField == 'nric') {
            $strBoolStatus = $this->subscribers->fnCheckEmailExist('nric', $strEmailAddress);
        } elseif($strField == 'combinition') {
            $strDob = date("Y-m-d", strtotime($strDob));
            $strBoolStatus = $this->subscribers->fnCheckGivenCombination($strFirstName, $strLastName, $strDob);
        }

        echo count($strBoolStatus);
    }



    /**
     * function to resend the email
     *  Function to send an email.
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    function ResendSendEmail()
    {
        # get the subscriber name.
        $this->load->model('subscribers');
        $intNotificationId = (int)base64_decode($_GET['id']);
        $intSubscriberId = (int)base64_decode($_GET['sub_id']);
        $strDecodedSubscriberId = $_GET['sub_id'];
        $arrEmailMessageInfo = $this->subscribers->fnGetRequestedDetails('notification', $intNotificationId);
        if (empty($arrEmailMessageInfo)) {
            $this->session->set_flashdata('error', "Notification Details not be found");
            $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$strDecodedSubscriberId;
            redirect($strRedirectPath);
        }
        $arrSubscriberInfo = $this->subscribers->fnGetRequestedDetails('subscriber', $arrEmailMessageInfo[0]['sub_id']);
        if (empty($arrSubscriberInfo)) {
            $this->session->set_flashdata('error', "Subscriber Details not found");
            $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$strDecodedSubscriberId;
            redirect($strRedirectPath);
        }
        if ($arrSubscriberInfo[0]['email'] == null) {
            $this->session->set_flashdata('error', "email address not found");
            $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$strDecodedSubscriberId;
            redirect($strRedirectPath);
        }

        $this->load->library('email');
        $html = "";
        if ($arrEmailMessageInfo[0]['transaction_id'] != null) {
            $arrEmailMessageContent = $this->subscribers->fnGetTransactionInfo($arrEmailMessageInfo[0]['transaction_id'], 1);
            $strCampCode = "";
            if ($arrEmailMessageContent[0]['promo_code'] != null) {
                $arrPromoInfo = $this->subscribers->fnGetDetails('campaigns', $arrEmailMessageInfo[0]['promo_code']);
                $strCampCode = $arrPromoInfo[0]['campeign_code'];
            }

            $CI_OBJ = & get_instance();
            $arrData['arrData'] = $arrEmailMessageContent;
            $arrData['strCampCode'] = $strCampCode;
            $html = $CI_OBJ->load->view('subscriber/receipt_pdf', $arrData, true);
        } else {
            $html = json_decode($arrEmailMessageInfo[0]['view_html']);
        }
        $strSubject = $arrEmailMessageInfo[0]['subject'];

        $this->email->set_mailtype("html");
        $this->email->from('team@smsystem.com', 'Subscription Management System');
        $this->email->to($arrSubscriberInfo[0]['email']);

        $this->email->subject($strSubject);
        $this->email->message($html);

        $boolResult = $this->email->send();

        $this->session->set_flashdata('success', "Email resent successfully");
        $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$strDecodedSubscriberId;
        redirect($strRedirectPath);

    }


    /**
     * Function to generate the receipt PDF
     * Function to generate the receipt of the pdf.
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function GenerateReceiptPdfForSubscriber()
    {

        # get the subscriber name.
        $this->load->model('subscribers');
        $intId = (int)base64_decode($_GET['id']);
        $arrInfo = $this->subscribers->fnGetTransactionInfo($intId, 1);
        $this->load->library('common');
        $arr_data['list'] = $list;
        $arrData['arrData']   = $arrInfo;
        $arr_data['heading'] = array('Case#', 'Submission Date', 'Status');
        $this->common->getPDFReport_common($arrInfo, 'receipt.pdf', 'subscriber/receipt_pdf');exit;
    }

    /*
     * Function fnSendBulkEmail
     * Function to send the bulk emails
     * @author	Himanshu Charegaonkar
     * @access	public
     *
     */
    public function fnSendBulkEmail()
    {
        $strEmailIds = $_POST['email_ids'];
        $strMessage = $_POST['message'];

        if($strEmailIds == "") {
            echo "Please select some recipients";exit;
        }

        if ($strMessage == "") {
            echo "Please enter some message to send";exit;
        }


        $this->load->library('email');

        $strSubject = 'Greetings from the Subscription Management Team!!';

        $this->email->set_mailtype("html");
        $this->email->from('team@smsystem.com', 'Subscription Manager');
        $this->email->to($strEmailIds);

        $this->email->subject($strSubject);
        $this->email->message($strMessage);

        $boolResult = $this->email->send();

        echo "Email sent successfully"; exit;

    }



    public function fnGetMagazineDetails()
    {
        $strMagazineId = $_GET['strMagazineId'];
        $intCampId = $_GET['intCampId'];
        # get the subscriber name.
        $this->load->model('magezines');
        $this->load->model('subscribers');
        $this->load->model('promotions');
        if ($intCampId != "" && $intCampId > 0) {
            $arrMagazineInfo = $this->promotions->fnGetCampaignMagazineDetails($strMagazineId, $intCampId);
            $arrCampaignInfo = $this->promotions->fnGetDetails('campaigns', $intCampId);
            $strHtml = '<table class="table table-white table-vertical-center margin-none table-striped footable">
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Amount: </label>
                            <div class="col-sm-7">
                                <input class="form-control" type="text" name="sub_option" readonly value="'.$arrMagazineInfo[0]["amount"].'" />
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Start Issue: </label>
                            <div class="col-sm-7">
                                <label  class="control-label text-left">'.$arrMagazineInfo[0]["start_issue"].'</label>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">End Issue: </label>
                            <div class="col-sm-7">
                                <label  class="control-label text-left">'.$arrMagazineInfo[0]["end_issue"].'</label>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">No of Years: </label>
                            <div class="col-sm-7">
                                <input class="form-control" type="text" name="sub_option"  readonly value="'.$arrCampaignInfo[0]["campaign_no_years"].'" />
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">end date: </label>
                            <div class="col-sm-7">
                                <label  class="control-label text-left">'.$arrCampaignInfo[0]["end_date"].'</label>
                            </div>
                        </td>
                    </tr>';
        } else {
            $arrMagazineInfo = $this->magezines->fnGetDetails('magazine', $strMagazineId);
            $arrYearsAmountInfo = $this->subscribers->fnGetSubscriptionDetailsWithMagazine($strMagazineId);
            $arrResult = array();
            $arrResult['name'] = $arrMagazineInfo[0]['name'];
            $arrResult['description'] = $arrMagazineInfo[0]['description'];
            $arrResult['status'] = $arrMagazineInfo[0]['status'];
            $arrResult['year'] =$arrYearsAmountInfo;

            $strHtml = '<table class="table table-white table-vertical-center margin-none table-striped footable" id="sub_single_magazine">
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Name: </label>
                            <div class="col-sm-7">
                                <label  class="control-label text-left">'.$arrMagazineInfo[0]['name'].'</label>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Description: </label>
                            <div class="col-sm-7">
                                <label  class="control-label text-left">'.$arrMagazineInfo[0]['description'].'</label>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Status: </label>
                            <div class="col-sm-7">
                                <label  class="control-label text-left">'.$arrMagazineInfo[0]['status'].'</label>
                            </div>
                        </td>
                    </tr>';
            if (count($arrYearsAmountInfo) > 0) {
                $strDropDown = '<tr>
                            <td>
                                <label  class="col-sm-4 control-label text-left">Year: </label>
                                <div class="col-sm-3"><select class="cust_select marl-n validate[required] text-input" id = "single_magazine_sub_option" name = "single_magazine_sub_option" required="required"><option value = "">--select--</option>';
                foreach($arrYearsAmountInfo as $info) {
                    $strDropDown .='<option value="'.$info["subscribe_no_years"].'">'.$info["subscribe_no_years"].'</option>';
                }

                $strDropDown .= '</select></div></td></tr>';
            } else {
                $strDropDown = '<tr>
                            <td>
                                <label  class="col-sm-4 control-label text-left">Year: </label>
                                <div class="col-sm-3"><select class="cust_select marl-n validate[required] text-input" id = "single_magazine_sub_option" name = "sub_option" required="required"><option value = "">--select--</option>';
                for($intCounter = 1; $intCounter<=12; $intCounter++) {
                    $strDropDown .='<option value="'.$intCounter.'">'.$intCounter.'</option>';
                }

                $strDropDown .= '</select></div></td></tr>';
            }

            $strRemainingHtml = '<tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Amount: </label>
                            <div class="col-sm-7">
                                <input class="form-control validate[required,custom[integer],min[1]] text-input" type="text" name="single_mag_sub_option" id="single_mag_sub_option" value="" />
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Start Date: </label>
                            <div class="col-sm-7">
                                <input data-date-format="M-yyyy" class="form-control date validate[required]" type="text" id="single_mag_start_date" name="single_mag_start_date" value="" />
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">End Date: </label>
                            <div class="col-sm-7">
                                <input data-date-format="M-yyyy" class="form-control date validate[required]" type="text" id="single_mag_end_date" name="single_mag_end_date" value="" />
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Start Issue: </label>
                            <div class="col-sm-7">
                                <input class="form-control validate[required,custom[integer],min[1]] text-input" type="text" id="single_mag_start_issue" name="single_mag_start_issue" value="" />
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">End Issue: </label>
                            <div class="col-sm-7">
                                <input class="form-control validate[required,custom[integer],min[1]] text-input" type="text" id="single_mag_end_issue" name="single_mag_end_issue" value="" />
                            </div>
                        </td>
                    </tr></table>';
            $strHtml = $strHtml.$strDropDown.$strRemainingHtml;
        }

        echo $strHtml;

    }



    public function fnGetAssociateMagazines()
    {
        $intCampaignId = $_GET['intCampaignId'];
        $strFlag = $_GET['flag'];
        $intNumberOfYear = $_GET['intNumberOfYear'];
        $arrUsedMagazines = $_GET['arrUsedMagazines'];
        if ($intCampaignId > 0) {
            $this->load->model('promotions');
            if ($strFlag == 'magazine_dropdown') {
                $arrDetails = $this->promotions->fnGetCampaignsMagazines($intCampaignId, $arrUsedMagazines, 1);
                $arrData['arrDetails']   = $arrDetails;
                $arrData['intCampaignId']   = $intCampaignId;
                $arrData['intNumberOfYear']   = $intNumberOfYear;
                echo $this->load->view('subscriber/add_magazine_to_campaign', $arrData, true);exit;

            } else {
                $arrCampaignInfo = $this->promotions->fnGetDetails('campaigns', $intCampaignId);
                $strHtml = '<table class="table table-white table-vertical-center margin-none table-striped footable">
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Name: </label>
                            <div class="col-sm-7">
                                <label  class="control-label text-left">'.$arrCampaignInfo[0]["name"].'</label>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Description: </label>
                            <div class="col-sm-7">
                                <label  class="control-label text-left">'.$arrCampaignInfo[0]["description"].'</label>
                            </div>
                        </td>
                    </tr>
                    <hr>';
            }
            echo $strHtml;
        }
    }

    public function fnAddCampaignMagazineSubscription()
    {
        $intGivenCampaignId = $_GET['intCampaignId'];
        $this->load->model('promotions');
        $arrDetails = $this->promotions->fnGetCampaignMagazinesToAdd($intGivenCampaignId);
        $arrData['arrDetails']   = $arrDetails;
        $arrData['intCampaignId']   = $intGivenCampaignId;
        echo $this->load->view('subscriber/add_magazine_to_campaign', $arrData, true);exit;
    }

    // ------------- Subscribe Campaign starts ---------------//

    public function fnSubscribeCampaign()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }

        # Check for the given id.
        $intSubscriberId = (int) base64_decode($_GET['subscriber_id']);
        if ($intSubscriberId == 0) {
            $this->session->set_flashdata('error', 'Please select valid subscriber id');
            $strRedirectPath = base_url().'index.php/subscriber/subscriber_list';
            redirect($strRedirectPath);
        }

        $this->load->model('subscribers');
        $arrUserInfo = $this->subscribers->fnGetDetails('subscriber', $intSubscriberId);
        $strSubscriberName = $arrUserInfo[0]['first_name']." ".$arrUserInfo[0]['last_name'];


        $arrCountArray = $this->subscribers->fnGetAvailableCampaigns();
        $arrData['middle']   = 'subscriber/subscribe_campaign';
        $arrData['arrData']   = $arrCountArray;
        $arrData['strUserName'] = $strSubscriberName;
        $arrData['strUserId'] = $intSubscriberId;
        $this->load->view('admin/templates/template', $arrData);

    }



    function fnGetMagazinesDetails()
    {
        $strMagazineId = $_GET['strMagazineId'];
        $strCampaignId = $_GET['strCampaignId'];
        $intNumberOfYears = $_GET['numberOfYears'];
        $intMagazine_campaign = $_GET['add_magazine_campaign'];
        $this->load->model('subscribers');
        if ($intMagazine_campaign != "") {
            $arrMagazineInfo = $this->subscribers->fnGetCampaignMagazineDetails($strCampaignId, $strMagazineId, 1, 0);

        } else {
            $arrMagazineInfo = $this->subscribers->fnGetCampaignMagazineDetails($strCampaignId, $strMagazineId, 1, $intNumberOfYears);
            print_r(json_encode($arrMagazineInfo[0]));exit;
        }

        $strHtml = '<table class="table table-white table-vertical-center margin-none table-striped footable">
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Start Issue: </label>
                            <div class="col-sm-7">
                                <input class="form-control validate[required,custom[integer],min[1]] text-input" type="text" id="issue1" name="start_issue" value="'.$arrMagazineInfo[0]["start_issue"].'" />
                            </div>
                        </td>
                    </tr>
                     <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">End Issue: </label>
                            <div class="col-sm-7">
                                <input class="form-control validate[required,custom[integer],min[1]] text-input" type="text" id="issue2" name="end_issue" value="'.$arrMagazineInfo[0]["end_issue"].'" />
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Start Date: </label>
                            <div class="col-sm-7">
                                <input class="form-control date validate[required]" data-date-format="M-yyyy" type="text" id="camp_start_date" name="start_date" value="'.date("M Y", strtotime($arrMagazineInfo[0]["start_date"])).'" readonly/>
                            </div>
                        </td>
                    </tr>
                     <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">End Date: </label>
                            <div class="col-sm-7">
                                <input class="form-control date validate[required]" data-date-format="M-yyyy" type="text" id="camp_end_date" name="end_date" value="'.date("M Y", strtotime($arrMagazineInfo[0]["end_date"])).'" readonly/>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Amount: </label>
                            <div class="col-sm-7">
                                <input class="form-control validate[required,custom[integer],min[1]] text-input" type="text" id="amount" name="amount" value="'.$arrMagazineInfo[0]["amount"].'" />
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <label  class="col-sm-4 control-label text-left">Number Of Years subscription: </label>
                            <div class="col-sm-7">
                                <input class="form-control" type="text" id="camp_number_years" name="camp_number_years" value="'.$arrMagazineInfo[0]["no_of_year"].'" />
                            </div>
                        </td>
                    </tr></table>';
        echo $strHtml;
    }


    public function fnUpdateCampaignMagazineInfo()
    {
        $arrGetInfo = $_GET;
        $arrResultData = array();
        $arrResultData['magazine_code'] = $arrGetInfo['magazine_code'];
        $arrResultData['magazine_Id'] = $arrGetInfo['magazine_Id'];
        $arrResultData['start_issue'] = $arrGetInfo['start_issue'];
        $arrResultData['end_issue'] = $arrGetInfo['end_issue'];
        $arrResultData['start_date'] = $arrGetInfo['start_date'];
        $arrResultData['end_date'] = $arrGetInfo['end_date'];
        $arrResultData['amount'] = $arrGetInfo['amount'];
        $arrResultData['years'] = $arrGetInfo['years'];
        $arrResultData['total_issue'] = $arrGetInfo['total_issue'];
        $arrResultData['row_id'] = $arrGetInfo['row_id'];
        echo $this->load->view('subscriber/edit_magazine_campaign', $arrResultData, true);exit;
    }

    public function fnSendIndividualMail()
    {
        $strRecipient = $_GET['recipient'];
        $strMessage = $_GET['message'];
        $strSubject = $_GET['mail_subject'];

        $this->load->library('email');

        $this->email->set_mailtype("html");
        $this->email->from('team@smsystem.com', 'Subscription Management System');
        $this->email->to($strRecipient);

        $this->email->subject($strSubject);
        $this->email->message($strMessage);

        $boolResult = $this->email->send();

        echo 1; exit;
    }

    public function fnSendIndividualMailAttachments()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->load->helper('url');

        $strRecipient = $_POST['recipient'];
        $strMessage = $_POST['message_desc'];
        $strSubject = $_POST['mail_subject'];
        //echo "<pre>";print_r($_POST);exit;
        $strUploadedFileName = "";
        if (($_FILES['attachment_for_file']['size'] > 0) && ($_FILES['attachment_for_file']['name'] != "")) {
            # Set the rules for the uploaded file.
            if ($_SERVER['HTTP_HOST'] == 'localhost') {
                $config['upload_path'] = $_SERVER['DOCUMENT_ROOT']."/smsystem/uploads/";
            } else {
                $config['upload_path'] = $_SERVER['DOCUMENT_ROOT']."/magazine/uploads/";
            }
            $config['allowed_types'] = '*';
            $config['max_size']	= '100000';
            $this->load->library('upload', $config);
            # Check whether the file is uploaded or not.
            if ($this->upload->do_upload('attachment_for_file'))
            {
                $data = array('upload_data' => $this->upload->data());
                $strUploadedFileName = $data['upload_data']['file_name'];
            } else {
                $error = array('error' => $this->upload->display_errors());
                $strErrorVal = $error['error'];
            }
        }
        $this->load->library('email');

        $this->email->set_mailtype("html");
        $this->email->from('team@smsystem.com', 'Subscription Management System');
        $this->email->to($strRecipient);

        $this->email->subject($strSubject);
        $this->email->message($strMessage);
        if ($strUploadedFileName != "") {
            $this->email->attach($config['upload_path'].$strUploadedFileName);
        }

        $boolResult = $this->email->send();
        $strRedirectUrl = $_SERVER['HTTP_REFERER'];
        $this->session->set_flashdata('success', 'Email send successfully');
        redirect($strRedirectUrl);
    }

    function fnGenerateTransactionReport()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }

        $intCampaignId = (int) base64_decode($_GET['id']);

        if ($intCampaignId == 0) {
            # Redirect to listing page with the success message.
            $this->session->set_flashdata('error', 'Please Provide Campaign Id');
            redirect(base_url().'index.php/promotion/promotion_list');
        }
                                       
        # Load the required model.
        $this->load->model('subscribers');

        $arrRenewals = $this->subscribers->fnGetTransactionDetails($intCampaignId, 1);
        $intTotalAmount = 0;
        //echo "<pre>";print_r($arrRenewals);exit;
        #get the payment Details:
        $intPaymentOption =  $arrRenewals[0]['mode_of_payment'];

        // $arrTableName = array (1 => 'payment_cash', 2 => 'payment_cheque', 3 => 'payment_credit_card', 4 => 'payment_online' ,
        //     5 => 'payment_club_membership', 6 => 'payment_complementary', 7 => 'payment_replacement', 8 => 'payment_invoice');

        $arrTableName = unserialize(arrPaymentMethods);

        $arrPaymentStatus = array(1 => "Unpaid", 2 => "Processing", 3 => "Paid");

        if (count($arrRenewals) > 0) {

            foreach($arrRenewals as $index => $values) {
                $intTotalAmount = $intTotalAmount + $arrRenewals[$index]['total_amount'];
                $arrRenewals[$index]['payment_status'] = $arrPaymentStatus[$values['status']];
                # get the relative payment details:
                $arrPayDetails = $this->subscribers->fnGetPaymentDetails($arrTableName[$intPaymentOption], $values['Primary_id']);
                if (count($arrPayDetails) > 0) {
                    $strAgentName = $arrPayDetails[0]["other_details"];
                    if ($arrPayDetails[0]["agent_id"] > 0) {
                        $arrAgentDetails = $this->subscribers->fnGetDetails("agent", $arrPayDetails[0]["agent_id"]);
                        $strAgentName = $arrAgentDetails[0]['first_name']." ".$arrAgentDetails[0]['last_name'];
                    }
                    if ($intPaymentOption == 1) {
                        $arrRenewals[$index]["agent_id"] = $strAgentName;


                    } elseif ($intPaymentOption == 2) {
                        $arrRenewals[$index]["check_date"] = $arrPayDetails[0]['cheque_date'];
                        $arrRenewals[$index]["cheque_number"] = $arrPayDetails[0]['cheque_number'];
                        $arrRenewals[$index]["issued_bank"] = $arrPayDetails[0]['issued_bank'];

                    } elseif ($intPaymentOption == 3) {
                        $arrRenewals[$index]["card_number"] = $arrPayDetails[0]['card_number'];
                        $arrRenewals[$index]["card_name"] = $arrPayDetails[0]['card_name'];
                        $arrRenewals[$index]["card_expiry"] = $arrPayDetails[0]['card_expiry'];
                        $arrRenewals[$index]["card_bank"] = $arrPayDetails[0]['card_bank'];

                    } elseif ($intPaymentOption == 4) {
                        $arrRenewals[$index]["online_transaction_id"] = $arrPayDetails[0]['online_transaction_id'];
                        $arrRenewals[$index]["isseud_bank_name"] = $arrPayDetails[0]['isseud_bank_name'];
                        $arrRenewals[$index]["transaction_date"] = date("d-m-Y", strtotime($arrPayDetails[0]['transaction_date']));

                    } elseif ($intPaymentOption == 5) {
                        $arrRenewals[$index]["agent_id"] = $strAgentName;

                    } elseif ($intPaymentOption == 6) {
                        $arrRenewals[$index]["agent_id"] = $strAgentName;

                    } elseif ($intPaymentOption == 7) {
                        $arrRenewals[$index]["agent_id"] = $strAgentName;

                    }
                    elseif ($intPaymentOption == 8) {
                        $arrRenewals[$index]["agent_id"] = $strAgentName;

                    }
                }

            }

        }

        $arrTransactionStatus = array(1 => 'Pending', 2 => 'Processing', 3=> 'Paid');
        if (count($arrRenewals) > 0) {
            $strCampaignCode = "Transaction Id: ".$arrRenewals[0]['transaction_id'];
            $strTotalTransactions = "Total amount of transaction:". (int)$intTotalAmount;
            $strTotalTransactionsAmount = "Total Magazines:". (int)count($arrRenewals);

            $objPHPExcel = new PHPExcel();

            $objPHPExcel->setActiveSheetIndex(0);
            $objPHPExcel->getActiveSheet()->SetCellValue('B2', 'Details of the Transaction under this Campaign');
            $objPHPExcel->getActiveSheet()->SetCellValue('B4', $strCampaignCode);
            $objPHPExcel->getActiveSheet()->SetCellValue('B5', $strTotalTransactions);
            $objPHPExcel->getActiveSheet()->SetCellValue('B6', $strTotalTransactionsAmount);
            $objPHPExcel->getActiveSheet()->SetCellValue('B9', 'Transaction Code');
            $objPHPExcel->getActiveSheet()->SetCellValue('C9', 'Subscriber Name');
            $objPHPExcel->getActiveSheet()->SetCellValue('D9', 'Subscriber Email');
            $objPHPExcel->getActiveSheet()->SetCellValue('E9', 'Magazine Code');
            $objPHPExcel->getActiveSheet()->SetCellValue('F9', 'Subscribed for Year(s)');
            $objPHPExcel->getActiveSheet()->SetCellValue('G9', 'No. of Copies');
            $objPHPExcel->getActiveSheet()->SetCellValue('H9', 'Amount');
            $objPHPExcel->getActiveSheet()->SetCellValue('I9', 'Start Issue');
            $objPHPExcel->getActiveSheet()->SetCellValue('J9', 'End Issue');
            $objPHPExcel->getActiveSheet()->SetCellValue('K9', 'Payment Method');
            $objPHPExcel->getActiveSheet()->SetCellValue('L9', 'Payment Status');

            if ($arrRenewals[0]['mode_of_payment'] == 1) {
                $objPHPExcel->getActiveSheet()->SetCellValue('M9', 'Cash Collected By');
            }

            if ($arrRenewals[0]['mode_of_payment'] == 2) {
                $objPHPExcel->getActiveSheet()->SetCellValue('M9', 'Cheque Date');
                $objPHPExcel->getActiveSheet()->SetCellValue('N9', 'Chque Number');
                $objPHPExcel->getActiveSheet()->SetCellValue('O9', 'Bank Name');
                $objPHPExcel->getActiveSheet()->SetCellValue('P9', 'Cash Collected By');
            }

            if ($arrRenewals[0]['mode_of_payment'] == 3) {
                $objPHPExcel->getActiveSheet()->SetCellValue('M9', 'Card Number');
                $objPHPExcel->getActiveSheet()->SetCellValue('N9', 'Card Name');
                $objPHPExcel->getActiveSheet()->SetCellValue('O9', 'Card Expiry');
                $objPHPExcel->getActiveSheet()->SetCellValue('P9', 'Bank Name');
                $objPHPExcel->getActiveSheet()->SetCellValue('Q9', 'Cash Collected By');
            }

            if ($arrRenewals[0]['mode_of_payment'] == 4) {
                $objPHPExcel->getActiveSheet()->SetCellValue('M9', 'Transaction Id');
                $objPHPExcel->getActiveSheet()->SetCellValue('N9', 'Bank Name');
                $objPHPExcel->getActiveSheet()->SetCellValue('O9', 'Transaction Date');
                $objPHPExcel->getActiveSheet()->SetCellValue('P9', 'Cash Collected By');
            }
            if ($arrRenewals[0]['mode_of_payment'] == 5 || $arrRenewals[0]['mode_of_payment'] == 6 || $$arrRenewals[0]['mode_of_payment'] == 7) {
                $objPHPExcel->getActiveSheet()->SetCellValue('M9', 'Cash Collected By');
            }

            $rowNumber = 11;

            foreach($arrRenewals as $transaction_details) {

                $objPHPExcel->getActiveSheet()->setCellValue('B'.$rowNumber,$transaction_details['transaction_id']);
                $objPHPExcel->getActiveSheet()->setCellValue('C'.$rowNumber,$transaction_details['first_name']." ".$arrRenewals['last_name']);
                $objPHPExcel->getActiveSheet()->setCellValue('D'.$rowNumber,$transaction_details['email']);
                $objPHPExcel->getActiveSheet()->setCellValue('E'.$rowNumber,$transaction_details['magezine_id']);
                $objPHPExcel->getActiveSheet()->setCellValue('F'.$rowNumber,$transaction_details['period']);
                $objPHPExcel->getActiveSheet()->setCellValue('G'.$rowNumber,$transaction_details['totalNCopies']);
                $objPHPExcel->getActiveSheet()->setCellValue('H'.$rowNumber,$transaction_details['total_amount']);
                $objPHPExcel->getActiveSheet()->setCellValue('I'.$rowNumber,$transaction_details['start_issue']);
                $objPHPExcel->getActiveSheet()->setCellValue('J'.$rowNumber,$transaction_details['end_issue']);
                $objPHPExcel->getActiveSheet()->setCellValue('K'.$rowNumber,$transaction_details['payment_mode']);
                $objPHPExcel->getActiveSheet()->setCellValue('L'.$rowNumber,$transaction_details['payment_status']);
                
                if ($transaction_details['status'] > 0) {
                
                    if ($transaction_details['mode_of_payment'] == 1) {
                        $objPHPExcel->getActiveSheet()->setCellValue('M'.$rowNumber,$transaction_details['agent_id']);
                    }
                    
                    if ($transaction_details['mode_of_payment'] == 2) {
                        $objPHPExcel->getActiveSheet()->setCellValue('M'.$rowNumber,$transaction_details['check_date']);
                        $objPHPExcel->getActiveSheet()->setCellValue('N'.$rowNumber,$transaction_details['cheque_number']);
                        $objPHPExcel->getActiveSheet()->setCellValue('O'.$rowNumber,$transaction_details['issued_bank']);
                        $objPHPExcel->getActiveSheet()->setCellValue('P'.$rowNumber,$transaction_details['agent_id']);
                    }

                    if ($transaction_details['mode_of_payment'] == 3) {
                        $objPHPExcel->getActiveSheet()->setCellValue('M'.$rowNumber,$transaction_details['card_number']);
                        $objPHPExcel->getActiveSheet()->setCellValue('N'.$rowNumber,$transaction_details['card_name']);
                        $objPHPExcel->getActiveSheet()->setCellValue('O'.$rowNumber,$transaction_details['card_expiry']);
                        $objPHPExcel->getActiveSheet()->setCellValue('P'.$rowNumber,$transaction_details['card_bank']);
                        $objPHPExcel->getActiveSheet()->setCellValue('Q'.$rowNumber,$transaction_details['agent_id']);
                    }

                    if ($transaction_details['mode_of_payment'] == 4) {
                        $objPHPExcel->getActiveSheet()->setCellValue('M'.$rowNumber,$transaction_details['online_transaction_id']);
                        $objPHPExcel->getActiveSheet()->setCellValue('N'.$rowNumber,$transaction_details['isseud_bank_name']);
                        $objPHPExcel->getActiveSheet()->setCellValue('O'.$rowNumber,$transaction_details['transaction_date']);
                        $objPHPExcel->getActiveSheet()->setCellValue('P'.$rowNumber,$transaction_details['agent_id']);
                    }
                    if ($transaction_details['mode_of_payment'] == 5 || $transaction_details['mode_of_payment'] == 6 || $transaction_details['mode_of_payment'] == 7) {
                        $objPHPExcel->getActiveSheet()->setCellValue('M'.$rowNumber,$transaction_details['agent_id']);
                    }
                }

                $rowNumber = $rowNumber + 1;
            }
            
            foreach(range(1,35) as $rowID) {
                $objPHPExcel->getActiveSheet()->getRowDimension($rowID)->setRowHeight(20);
            }
            // Save Excel 2007 file
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $strFileName = "promotion-magazine-details".time().".xls";
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="'.$strFileName);
            header('Cache-Control: max-age=0');

            $objWriter->save('php://output');
            exit();
        }
    }

    /**
     * Function fnGetMagazineInfoRenew
     * function to Renew the Magazine
     */
    function fnGetMagazineInfoRenew()
    {
        $strTransactionId = (int)$_GET['transaction_id'];
        $strSubscriberId = (int)$_GET['subscribers_id'];
        $strMagazineCode = $_GET['magazines_code'];
        if ($strTransactionId == 0) {
            echo "Please provide valid transaction information";exit;
        }
        # Load the required model.
        $this->load->model('subscribers');
        $arrAvailableMagazines = $this->subscribers->fnGetMagazineWithSubscription($strSubscriberId);
        $arrData['magazine_details'] = $arrAvailableMagazines;
        $arrData['intTransactionId'] = $strTransactionId;
        $arrData['subscriberId'] = $strSubscriberId;
        $this->load->view('subscriber/renew_subscription', $arrData);

    }

    /**
     * Function to select the Magazine subscription method and proceed
     *
     */
    function subscribe_magazine_process()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }

        #Get the Subscriber Id and check whether it has some value.
        $intSubscriberId = (int) base64_decode($_POST['subscriber_id']);

        if ($intSubscriberId == 0) {
            # Redirect to listing page with the success message.
            $this->session->set_flashdata('error', 'Please Provide subscriber Id');
            redirect(base_url().'index.php/subscriber/subscriber_list');
        }

        # Set the Redirection path.
        $strRedirectUrlPart = "index.php/subscriber/fnSubscribeCampaign/?subscriber_id=".$_POST['subscriber_id'];
        if ($_POST['process_way'] == 'process_magazine') {
            $strRedirectUrlPart = "index.php/subscriber/subscribe_product?user_id=".$_POST['subscriber_id'];
        }
        redirect(base_url().$strRedirectUrlPart);
    }

    function fnGetRelatedMagazineDetails()
    {
        $strMagazineCode = $_GET['strMagazineId'];
        $intCampaignId = $_GET['strCampaignId'];
        $intNumberOfYear = $_GET['numberOfYears'];

        $this->load->model('promotions');
        $arrResult = array();
        if ($strMagazineCode != "") {
            $arrResult = $this->promotions->fnGetAllDetailsOfMagazine($strMagazineCode, $intCampaignId, $intNumberOfYear);

        }
        print_r(json_encode($arrResult[0]));exit;
    }

    /**
     * Function update_payment_method
     * Function to update the payment status and other information.
     */
    function update_payment_method()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }

        $router = & load_class('Router', 'core');
        $class_name = $router->fetch_class();
        $method_name = $router->fetch_method();
        $strModule = $method_name;
        if ($strModule == "index") {
            $strModule = "";
        } else {
            $strModule = "/".$strModule;
        }
        $strTotalUrlToCheck = $class_name.$strModule;
        $arr_session = $this->ci->session->all_userdata();
        $level_id = $arr_session['level'];
        $arr_result = $this->ci->user->fnCheckAccessIsAllowed($level_id, $strTotalUrlToCheck);
        if (empty($arr_result)) {
            redirect($_SERVER['HTTP_REFERER']);
        }

        # Get the Transaction Id send through the URLS.
        $strEncodedTransactionId = $_GET['id'];
        $strDecTransactionId = (int) base64_decode($strEncodedTransactionId);

        # Check whether the transaction id has some value or not.
        if ($strDecTransactionId == 0) {
            # Redirect to listing page with the success message.
            $this->session->set_flashdata('error', 'Please Provide valid transaction Id');
            redirect(base_url().'index.php/subscriber/finalise_payment');
        }

        # Call the model.
        $this->load->model('subscribers');

        #Check whether the transaction id is available or not.
        $arrTransactionInfo = $this->subscribers->fnGetAllDetails('transaction', 'transaction_id', $strDecTransactionId);

        # Redirect with error if transaction is not available.
        if (count($arrTransactionInfo) == 0) {
            $this->session->set_flashdata('error', 'Please Provide valid transaction Id');
            redirect(base_url().'index.php/subscriber/finalise_payment');
        }

        // $arrPaymentTableHeads = array (1 => 'payment_cash', 2 => 'payment_cheque', 3 => 'payment_credit_card', 4 => 'payment_online' ,
        //     5 => 'payment_club_membership', 6 => 'payment_complementary', 7 => 'payment_replacement');
        $arrPaymentTableHeads = unserialize(arrPaymentMethods);

        # Delete the previous payment history.
        foreach($arrTransactionInfo as $indTransaction) {
            # first get the used Payment method for previous payment process.
            $strPaymentTableHead = $arrPaymentTableHeads[$arrTransactionInfo[0]['mode_of_payment']];
            $this->subscribers->fnDeletePaymentMethod($indTransaction['id'], $strPaymentTableHead);
        }

        # Update the payment status to PAY for transaction.
        $arrValuesToUpdate =  array('status' => 1, 'mode_of_payment' => 1, 'is_suspended' => '1');
        $this->subscribers->fnUpdatePaymentStatus($strDecTransactionId, $arrValuesToUpdate);

        # prepare the URL to redirect to Make payment window.
        $strEncSubscriberId = base64_encode($arrTransactionInfo[0]['subscriber_id']);
        $strUrl = base_url().'index.php/subscriber/finalise_payment';
        redirect($strUrl);


    }

    /**
     * function to send the auto email from when transaction got finalise.
     * @param $intTransactionId - integer  transaction Id.
     * @return bool
     */
    function fnSendAutoEmail($intTransactionId)
    {
        # get the subscriber name.
        $this->load->model('subscribers');

        # To move further, check the status of transaction.
        $arrTransactionDetails = $this->subscribers->fnGetTransactionInfo($intTransactionId, $intBool = 1);
        if ($arrTransactionDetails[0]['email'] == null || $arrTransactionDetails[0]['email'] == "") {
            return true;
        }

        $strCampCode = "";
        if ($arrTransactionDetails[0]['promo_code'] != null) {
            $arrPromoInfo = $this->subscribers->fnGetDetails('campaigns', $arrTransactionDetails[0]['promo_code']);
            $strCampCode = $arrPromoInfo[0]['campeign_code'];
        }
        $CI_OBJ = & get_instance();
        $arrSample['arrData'] = $arrTransactionDetails;
        $arrSample['strCampCode'] = $strCampCode;
        $html = $CI_OBJ->load->view('subscriber/receipt_pdf', $arrSample, true);
        $strSubject = 'Receipt of the Magazine';
        # before create an transaction array first check the whether the payment for this already done or not.
        # get the subscriber name.
        $this->load->model('subscribers');
        $boolStatus = $this->subscribers->fnCheckNotification($intTransactionId, $strSubject);
        if ($boolStatus == 0) {
            $this->load->library('email');
            $strSubject = 'Receipt of the Magazine';

            $this->email->set_mailtype("html");
            $this->email->from('team@smsystem.com', 'Subscription Management System');
            $this->email->to($arrTransactionDetails[0]['email']);

            $this->email->subject($strSubject);
            $this->email->message($html);

            $boolResult = $this->email->send();

            #insert the transaction.
            $arrRecords = array();
            $arrRecords['subject'] = $strSubject;
            $arrRecords['status'] = 'sent';
            $arrRecords['send_on'] = date("Y-m-d");
            $arrRecords['transaction_id'] = $intTransactionId;
            $arrRecords['view_html'] = null;
            $arrRecords['sub_id'] = $arrTransactionDetails[0]['subscriber_id'];
            $intNewTransactionId = $this->subscribers->fnSaveAllDetails('notification', $arrRecords);
           return true;
        }
        return true;
    }

    /**
     * Function to add comment for the subscriber.
     */
    function add_comment_subscriber()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }

        # Call the model.
        $this->load->model('subscribers');
        $this->load->model('promotions');
        # set form fields rules.
        $this->load->helper(array('form', 'url'));
        $this->form_validation->set_rules('message_desc', 'Comment', 'trim|required|');
        # Check whether the validation turns true.
        if ($this->form_validation->run() == TRUE) {
            # Get the Transaction Id send through the URLS.
            $strEncodedSubId = $_POST['subscriber_enc_id'];
            $strDecSubId = (int) base64_decode($strEncodedSubId);

            # Check whether the transaction id has some value or not.
            if ($strDecSubId == 0) {
                # Redirect to listing page with the success message.
                $this->session->set_flashdata('error', 'Please Provide valid subscriber Id');
                redirect(base_url().'index.php/subscriber/preview');
            }

            #Check whether the transaction id is available or not.
            $arrSubscriberInfo = $this->subscribers->fnGetAllDetails('subscriber', 'id', $strDecSubId);
            if (count($arrSubscriberInfo) == 0) {
                # Redirect to listing page with the success message.
                $this->session->set_flashdata('error', 'Please Provide valid subscriber Id');
                redirect(base_url().'index.php/subscriber/preview');
            }
            # Create the array of records.
            $arrComment['subscriber_id'] = $strDecSubId;
            $arrComment['comment'] = trim($_POST['message_desc']);
            $arrComment['comment_by'] = $this->session->userdata('id');
            $arrComment['comment_date_time'] = strtotime(Date("Y-m-d H:i:s"));
            $arrComment['comment_type'] = 'general';
            $arrComment['transaction_id'] = null;

            $this->subscribers->fnSaveAllDetails('subscriber_comment', $arrComment);
            $this->session->set_flashdata('success', 'Comment Added successfully');
            $strRedirectPath = base_url().'index.php/subscriber/add_comment_subscriber/?subscriber_id=  '.$strEncodedSubId;
            redirect($strRedirectPath);
        } else {
            $strGetEncSubId = $_GET['subscriber_id'];
            $strDecSubId = (int) base64_decode($strGetEncSubId);
            #Check whether subscriber has come previous comments.
            $arrSubscriberComment = $this->subscribers->fnGetAllDetails('subscriber_comment', 'subscriber_id', $strDecSubId);
            $arrGetAllSystemUsers = $this->promotions->fnGetDetails('user');
            $arrUserInfo = array();
            if (count($arrGetAllSystemUsers) > 0) {
                foreach ($arrGetAllSystemUsers as $user) {
                    $arrUserInfo[$user['id']] = ucwords($user['first_name']." ".$user['last_name']);
                }
            }

            $arrData['comments']   = array_reverse($arrSubscriberComment);
            $arrData['users']   = $arrUserInfo;
            $arrData['str_given_userId']   = $strGetEncSubId;
            $arrData['middle'] = 'subscriber/add_comment_subscriber';
            $this->load->view('admin/templates/template', $arrData);
        }
    }

    /**
     * Function fnSendSubscriptionEmail
     * function to send the email contains all details regarding the subscription.
     */
    function fnSendSubscriptionEmail()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }
        $router = &load_class('Router', 'core');
        $class_name = $router->fetch_class();
        $method_name = $router->fetch_method();
        $strModule = $method_name;
        if ($strModule == "index") {
            $strModule = "";
        } else {
            $strModule = "/".$strModule;
        }
        $strTotalUrlToCheck = $class_name.$strModule;
        $arr_session = $this->session->all_userdata();
        $level_id = $arr_session['level'];
        $arr_result = $this->user->fnCheckAccessIsAllowed($level_id, $strTotalUrlToCheck);
        if (empty($arr_result)) {
            redirect($_SERVER['HTTP_REFERER']);
        }

        $intSubscriberId = (int)base64_decode($_GET['user_id']);
        #if Send subscriber id doesn't have valid integer value then redirect it with error.

        if ($intSubscriberId == 0) {
            $this->session->set_flashdata('error', 'Please provide valid subscriber Id');
            $strRedirectPath = base_url().'index.php/subscriber/subscriber_list';
            redirect($strRedirectPath);
        }

        # Call the model.
        $this->load->model('subscribers');

        # Array of Payment methods
        $arrPaymentTable= array (1 => 'Cash', 2 => 'Cheque', 3 => 'Credit Card', 4 => 'Online' ,
            5 => 'Club Membership', 6 => 'Complementary', 7 => 'Replacement');

        #Get the transaction history for the Given Subscriber.
        $arrSubscriberTransaction = $this->subscribers->fnGetTransactionInfoForIndividual($intSubscriberId, 1);
        if (empty($arrSubscriberTransaction)) {
            $this->session->set_flashdata('error', 'Subscription history not found for this subscriber');
            $strRedirectPath = base_url().'index.php/subscriber/subscriber_list';
            redirect($strRedirectPath);
        }
        $strLogoUrl = base_url().'assets/images/logo/sub-logo.jpg';
        $strHtml = "";
        $strHtml .= '<div class="navbar-header" style="margin-bottom: 20px">
                     <img src="'.$strLogoUrl.'" />
                     </div>';
        $strHtml .= "Dear ".$arrSubscriberTransaction[0]["subscriber_name"].", ";
        $strHtml .= '<p><i>&nbsp;&nbsp;&nbsp;&nbsp;Please find your subscription details till today:</i></p>';
        $strHtml .= '<table cellpadding="5" cellspacing="5" style="margin-left: 5px" border="1">';
        $strHtml .= '<tr><td>Magazine Id</td><td>Year(s)</td><td>Start Date</td><td>Expiry On</td><td>Issue</td><td>Start Issue</td><td>End Issue</td><td>Amount</td><td>Status</td><td>Payment Method</td></tr>';
        foreach($arrSubscriberTransaction as $transaction_info) {
            $strHtml .= "<tr>";
            $strHtml .= "<td>".$transaction_info['magezine_id']."</td>";
            $strHtml .= "<td>".$transaction_info['period']."</td>";
            $strHtml .= "<td>".date('d M Y ', strtotime($transaction_info['subscribed_on']))."</td>";
            $strHtml .= "<td>".date('d M Y ', strtotime($transaction_info['subscription_end_on']))."</td>";
            $strHtml .= "<td>".$transaction_info['no_of_issue']."</td>";
            $strHtml .= "<td>".$transaction_info['start_issue']."</td>";
            $strHtml .= "<td>".$transaction_info['end_issue']."</td>";
            $strHtml .= "<td>".$transaction_info['amount']."</td>";
            $strHtml .= "<td>".$transaction_info['status']."</td>";
            $strHtml .= "<td>".$arrPaymentTable[$transaction_info['mode_of_payment']]."</td>";
            $strHtml .= "</tr>";
        }
        $strHtml .= '</table>';
        $strHtml .= '<div style="margin-top: 40px;">
                        <ul style="list-style-type:disc;margin-left: -10px">
                            <li><i>Please keep this for your reference.</i></li>
                            <li><i>This is an auto-generated email, so please do not reply to this email as it will not be monitored.</i></li>
                        </ul>
                        <small></small></p>
                        <br>
                        <p>Thank You,</p>
                        <p>Magazine Fulfilment Department</p>
                        <p>Nurture Craft International Pte Ltd</p>
                        <p>Office Phone: +65 62586236</p>

                    </div>';
        #After creating the HTML successfully, send the email of this.
        $this->load->library('email');
        $strSubject = 'Subscription Details';

        $this->email->set_mailtype("html");
        $this->email->from('team@smsystem.com', 'Subscription Management System');
        $this->email->to($arrSubscriberTransaction[0]["sub_email"]);

        $this->email->subject('Subscription Details');
        $this->email->message($strHtml);

        $boolResult = $this->email->send();
        if($boolResult == 1){
            $arrRecords = array();
            $arrRecords['subject'] = $strSubject;
            $arrRecords['status'] = 'sent';
            $arrRecords['send_on'] = date("Y-m-d");
            $arrRecords['transaction_id'] = null;
            $arrRecords['view_html'] = json_encode($strHtml);
            $arrRecords['sub_id'] = $intSubscriberId;
            $this->subscribers->fnSaveAllDetails('notification', $arrRecords);

            $this->session->set_flashdata('success', 'Subscription details email has been sent successfully');
            $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.base64_encode($intSubscriberId);
            redirect($strRedirectPath);
        } else {
            $this->session->set_flashdata('error', 'Some problem encounter to send an email');
            $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.base64_encode($intSubscriberId);
            redirect($strRedirectPath);
        }
    }

    /**
     *  Function rearrange_active_magazine
     *  Function to update the active - paid magazine
     *  It can be terminated, Refund, Transfer
     */
    function rearrange_active_magazine()
    {
        if (isset($_GET['prime_tran_id']) && $_GET['sub_id'] != "") {
            # Check for the parameter and its associated value.
            $intMagazineTransactionId = (int) base64_decode($_GET['prime_tran_id']);
            $intSubscriberId = (int) base64_decode($_GET['sub_id']);
            if ($intMagazineTransactionId == 0 || $intSubscriberId == 0) {
                $this->session->set_flashdata('error', 'Magazine Id or Subscriber Id are not present');
                $strRedirectPath = base_url().'index.php/subscriber/subscriber_list';
                redirect($strRedirectPath);
            }
            #Check whether the Magazine id in transaction id.
            $this->load->model('subscribers');
            $arrTransactionInfo = $this->subscribers->fnGetAllDetails('transaction', 'id', $intMagazineTransactionId);
            if (empty($arrTransactionInfo)) {
                $this->session->set_flashdata('error', 'Given magazine id is not valid');
                $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$_GET['sub_id'];
                redirect($strRedirectPath);
            }
            $arrData['intTransactionMagazineId'] = $_GET['prime_tran_id'];
            $arrData['intSubscriberId'] = $_GET['sub_id'];
            //$arrData['middle'] = 'subscriber/rearrange_active_magazine';
            echo $this->load->view('subscriber/rearrange_active_magazine', $arrData, true);
        }

        if (isset($_POST['updated_action'])) {
            $intSelectedAction = (int) $_POST['updated_action'];
            if ($intSelectedAction == 0) {
                $this->session->set_flashdata('error', 'Please select either any option to proceed');
                $strRedirectPath = base_url().'index.php/rearrange_active_magazine/?prime_tran_id='.$_POST['intTransactionMagazineId']."&sub_id=".$_POST['intSubscriberId'];
                redirect($strRedirectPath);
            }
            $txtTransferComment = $_POST['transfer_comments'];
            $intMagazineTransactionId = (int)base64_decode($_POST['intTransactionMagazineId']);
            $intSubscriberId = (int)base64_decode($_POST['intSubscriberId']);
            if ($intMagazineTransactionId == 0 || $intSubscriberId == 0) {
                $this->session->set_flashdata('error', 'Magazine Id or Subscriber Id are not present');
                $strRedirectPath = base_url().'index.php/subscriber/subscriber_list';
                redirect($strRedirectPath);
            }
            #Check whether the Magazine id in transaction id.
            $this->load->model('subscribers');
            $arrTransactionInfo = $this->subscribers->fnGetAllDetails('transaction', 'id', $intMagazineTransactionId);
            if (empty($arrTransactionInfo)) {
                $this->session->set_flashdata('error', 'Given magazine id is not valid');
                $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$_POST['intSubscriberId'];
                redirect($strRedirectPath);
            }
            # If selected option is 2 i.e Termination and Refund
            if ($intSelectedAction == 2) {
                #Prepare array of records to update and call function to update the status
                $this->subscribers->fnUpdateActiveMagazineStatus($intSelectedAction, $intMagazineTransactionId);

                # After the update, save the comment
                $txtTransferComment = $txtTransferComment. "<br>". 'For transaction and magazine -'.$arrTransactionInfo[0]['transaction_id']."/".$arrTransactionInfo[0]['id'];
                $arrComment['subscriber_id'] = $intSubscriberId;
                $arrComment['comment'] = trim($txtTransferComment);
                $arrComment['comment_by'] = $this->session->userdata('id');
                $arrComment['comment_date_time'] = strtotime(Date("Y-m-d H:i:s"));
                $arrComment['comment_type'] = 'transaction';
                $arrComment['transaction_id'] = $arrTransactionInfo[0]['transaction_id'];

                $this->subscribers->fnSaveAllDetails('subscriber_comment', $arrComment);

                # After successful update, redirect with success message.
                $this->session->set_flashdata('success', 'Magazine status has been updated successfully');
                $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$_POST['intSubscriberId'];
                redirect($strRedirectPath);
            } elseif ($intSelectedAction == 3){
                # Put all details into the Session to access it at the time of New magazine Subscription.
                $this->load->library('session');
                $this->session->unset_userdata('transferred_magazine_details');
                $arrMagazineTransferredInfo = array();
                $arrMagazineTransferredInfo = array(
                    'magazine_transaction_key' => $intMagazineTransactionId,
                    'intTransfereeMagazine'  => $arrTransactionInfo[0]['id'],
                    'comment'     => $txtTransferComment,
                    'old_transaction_id'     => $arrTransactionInfo[0]['transaction_id'],
                    'old_magazine_id'     => $arrTransactionInfo[0]['product_id'],
                );
                $this->session->set_userdata('transferred_magazine_details', $arrMagazineTransferredInfo);
                $strRedirectPath = base_url().'index.php/subscriber/subscribe_product?user_id='.$_POST['intSubscriberId'];
                redirect($strRedirectPath);
            } elseif ($intSelectedAction == 4){

                #Prepare array of records to update and call function to update the status
                $this->subscribers->fnUpdateActiveMagazineStatus($intSelectedAction, $intMagazineTransactionId);
                # After the update, save the comment
                $txtTransferComment = $txtTransferComment. "<br>". 'For transaction and magazine -'.$arrTransactionInfo[0]['transaction_id']."/".$arrTransactionInfo[0]['id'];
                $arrComment['subscriber_id'] = $intSubscriberId;
                $arrComment['comment'] = trim($txtTransferComment);
                $arrComment['comment_by'] = $this->session->userdata('id');
                $arrComment['comment_date_time'] = strtotime(Date("Y-m-d H:i:s"));
                $arrComment['comment_type'] = 'transaction';
                $arrComment['transaction_id'] = $arrTransactionInfo[0]['transaction_id'];

                $this->subscribers->fnSaveAllDetails('subscriber_comment', $arrComment);

                # After successful update, redirect with success message.
                $this->session->set_flashdata('success', 'Magazine status has been updated successfully');
                $strRedirectPath = base_url().'index.php/subscriber/preview/?user_id='.$_POST['intSubscriberId'];
                redirect($strRedirectPath);
            }
        }
    }

    /**
     * Function fnTransferMagazineSessionDetails
     * Function to update the status as well as put comment for the transfer transaction.
     * @param $intNewMagazineId
     * @param $intSubscriberId
     * @return bool
     */
    function fnTransferMagazineSessionDetails($intNewMagazineId, $intSubscriberId)
    {
        $this->load->library('session');
        $arrMagazineSessionInfo = $this->session->userdata('transferred_magazine_details');
        if (!empty($arrMagazineSessionInfo)){
            #Get the session Details.
            $intOldMagazineId = $arrMagazineSessionInfo['intTransfereeMagazine'];
            $intTransactionId = $arrMagazineSessionInfo['old_transaction_id'];
            $txtTransferComment = $arrMagazineSessionInfo['comment'];
            $intMagazineTransactionPrimeKey = $arrMagazineSessionInfo['magazine_transaction_key'];
            $intOldProductId = $arrMagazineSessionInfo['old_magazine_id'];

            #load require models.
            $this->load->model('subscribers');

            # First update the status of previous magazine to transfer.
            $this->subscribers->fnUpdateActiveMagazineStatus(3, $intMagazineTransactionPrimeKey);

            # Add transfer Details to comment
            $txtTransferComment = $txtTransferComment. "<br>". 'Magazine id '.$intOldProductId.' has been transferred to '.$intNewMagazineId.' for transaction id '.$intTransactionId."/".$intOldMagazineId;
            $arrComment['subscriber_id'] = $intSubscriberId;
            $arrComment['comment'] = trim($txtTransferComment);
            $arrComment['comment_by'] = $this->session->userdata('id');
            $arrComment['comment_date_time'] = strtotime(Date("Y-m-d H:i:s"));
            $arrComment['comment_type'] = 'transaction';
            $arrComment['transaction_id'] = $intTransactionId;
            $this->subscribers->fnSaveAllDetails('subscriber_comment', $arrComment);

            # After all activity unset the session variable.
            $this->session->unset_userdata('transferred_magazine_details');
            return true;
        }
        return true;
    }

    /**
     * Function fnCheckForUniqueTransactionKey
     * Function which looks for the old transaction id store in session and if not then generate the New one.
     * @return string
     * @author Himanshu Charegaonkar
     * @access public
     */
    function fnCheckForUniqueTransactionKey()
    {
        $this->load->library('session');
        $arrMagazineSessionInfo = $this->session->userdata('transferred_magazine_details');
        // Create the transaction prefix which is current year and month.
        $strTransactionPrefix = date("y").date("m");
        $strTransactionId = substr(number_format(time() * rand(),0,'',''),0,6);
        # Set the transaction by concatenating the random string and prefix.
        $strUniqueTransactionKey = $strTransactionPrefix.$strTransactionId;

        # if session contains any previous transaction key then use as it is, if no then send new key.
        if (!empty($arrMagazineSessionInfo)){
            $strUniqueTransactionKey = $arrMagazineSessionInfo['old_transaction_id'];
        }

        return $strUniqueTransactionKey;
    }


    function fnUpdateRenewalPayment()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }
        # Load the required model.
        $this->load->model('subscribers');
        $this->load->model('promotions');
        $this->load->model('magezines');
        # Check for the given id.
        $intDecUserId = (int) base64_decode($_POST['subscriber_id']);

        #Check whether we get the subscriber Id
        if ($intDecUserId == 0) {
            $this->session->set_flashdata('error', "Please provide valid Subscriber Id");
            $strRedirectPath = base_url().'index.php/subscriber/subscriber_list';
            redirect($strRedirectPath);
        }
        # Check whether the given user Id is present in database or not.
        $arrSubscriberInfo = $this->promotions->fnGetDetailsOfTable('subscriber', 'id', $intDecUserId);

        if (empty($arrSubscriberInfo)) {
            $strRedirectPath = base_url().'index.php/subscriber/subscribe_product/?user_id='.base64_encode($intDecUserId);
            redirect($strRedirectPath);
        }
        $strSubscriberName = $arrSubscriberInfo[0]['first_name']." ".$arrSubscriberInfo[0]['last_name'];

        $arrPostedData = $_POST;
        $intIndMagazineId = (int)base64_decode($arrPostedData['transaction_id']);
        #Declare related array for magazine code and amount and start issue and end issue.
        $arrMagazineCode = $arrPostedData['magazine_code'];
        $arrStartIssue = $arrPostedData['start_issue'];
        $arrEndIssue = $arrPostedData['end_issue'];
        $arrStartDate = $arrPostedData['start_date'];
        $arrEndDate = $arrPostedData['end_date'];
        $arrAmount = $arrPostedData['amount'];
        $arrTotalIssue = $arrPostedData['no_issues'];
        $arrDuration = $arrPostedData['number_of_year'];

        $strUniqueTransactionKey = $this->fnCheckForUniqueTransactionKey();
        # Create a array of records.
        $arrInsertArray = array();
        $arrInsertArray['transaction_date'] = date("Y-m-d");
        $arrInsertArray['subscriber_id'] = $intDecUserId;
        $arrInsertArray['subscriber_name'] = $strSubscriberName;
        $arrInsertArray['product_id'] = $arrMagazineCode;
        $arrInsertArray['period'] = $arrDuration;
        $arrInsertArray['subscribed_on'] = date("Y-m-d", strtotime($arrStartDate));
        $arrInsertArray['subscription_end_on'] = date("Y-m-d", strtotime($arrEndDate));
        $arrInsertArray['promo_code'] = null;
        $arrInsertArray['status'] = 1;
        $arrInsertArray['start_issue'] = $arrStartIssue;
        $arrInsertArray['end_issue'] = $arrEndIssue;
        $arrInsertArray['amount'] = $arrAmount;
        $arrInsertArray['total_amount'] = $arrAmount;
        $arrInsertArray['mode_of_payment'] = 1;
        $arrInsertArray['currency_of_payment'] = 1;
        $arrInsertArray['no_of_issue'] = $arrTotalIssue;
        $arrInsertArray['transaction_id'] = $strUniqueTransactionKey;
        # Save the Transaction details.
        $intNewPrimeTransactionId = $this->subscribers->fnSave('transaction', $arrInsertArray);

        /** Old Patch where Past Primary Ind Magazine Delete Start */
        #$this->subscribers->FnDeleteINdMagazine($intIndMagazineId);
        /** Old Patch End */

        /** New Patch Start */
        # Now update the Prime transaction Id to Renewed Status
        $this->subscribers->fnUpdateActiveMagazineStatus('5', $intIndMagazineId);
        #Insert log of this Renewal
        $arrRenewalLog = array();
        $arrRenewalLog['prev_transaction_Id'] = $intIndMagazineId;
        $arrRenewalLog['new_transaction_Id'] = $intNewPrimeTransactionId;
        $this->subscribers->fnSave('tbl_renewal_log', $arrRenewalLog);
        /** New Patch End */

        # Redirect with the success message.
        $this->session->set_flashdata('success', 'subscribed magazine has been added');
        $strRedirectPath = base_url().'index.php/subscriber/make_payment/?sub_id='.base64_encode($intDecUserId)."&transaction_id=".base64_encode($strUniqueTransactionKey);
        redirect($strRedirectPath);
    }
}
