<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
class Users extends CI_Controller {

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

    /**
     * Function login
     * Login functiobnality for the user.
     * Controllers default method.
     *
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function login()
    {
        # set form fields rules.
        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required');

        # processing further depending upon the form validation success or failure.
        if ($this->form_validation->run() === FALSE)
        {
            # return again to login window.
            $strValidationErrors = validation_errors();
            $this->session->set_flashdata('error', $strValidationErrors);
            $arrData['custom_error'] = "";
            $this->load->view('admin/login');
        }
        else
        {
            #$this->load->view('Login');
            $strGivenUserName = trim($_POST['username']);
            $strGivenPassword = trim($_POST['password']);

            # Check whether the login credential's are valid or not.
            $this->load->model('user');
            $arrCheckResult = $this->user->fnCheckLogin($strGivenUserName, $strGivenPassword);
            if (count($arrCheckResult) > 0) {

                if($arrCheckResult[0]['access_role'] != 13) {
                    # Set the remember me functionality by setting  up a cookie.
                    if (isset($_POST['remember']) && $_POST['remember'] != "") {
                        setcookie("username", $strGivenUserName, time()+7200);
                        setcookie("password", $strGivenPassword, time()+7200);
                    } else {
                        setcookie("username", "", time()-1000);
                        setcookie("password", "", time()-1000);
                    }

                    # Set a session.
                    $this->session->set_userdata(array('id' => $arrCheckResult[0]['id'], 'username' => $strGivenUserName,
                        'level' => $arrCheckResult[0]['access_role'], 'first_name' => $arrCheckResult[0]['first_name'], 'last_name' => $arrCheckResult[0]['last_name']));
                    redirect(base_url().'index.php/subscriber/subscriber_list');
                }else {

                    # if account is suspended, return again to login window.
                    $data = array();
                    $this->session->set_flashdata('error', 'Your account has been suspended');
                    redirect(base_url().'index.php/users/login');
                }

                
            } else {
                # if user name password dose not match, return again to login window.
                $data = array();
                $this->session->set_flashdata('error', 'Please enter valid user name or password');
                redirect(base_url().'index.php/users/login');
            }
        }
    }

    /**
     * Function Add user
     * Functionality to add new user type in the system
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function add_user()
    {
        # set form fields rules.
        $this->load->helper(array('form', 'url'));
        $this->load->model('user');
        # Set the form validation rule for the personal information such as name, email, phone,mobile, gender, NRIC
        $this->form_validation->set_rules('first_name', 'First Name', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[user.email]|xss_clean');
        $this->form_validation->set_rules('username', 'Username', 'trim|required|max_length[100]|is_unique[user.username]|xss_clean');
        $this->form_validation->set_rules('phone', 'Last Name', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('access_roles', 'Access Roles', 'trim|required');
        #$this->form_validation->set_rules('designation', 'Designation', 'trim|required');
        # Check whether the validation turns true.
        if ($this->form_validation->run() == TRUE)
        {
            $arrInsert = array();
            $arrInsert['first_name'] = $_POST['first_name'];
            $arrInsert['last_name'] = $_POST['last_name'];
            $arrInsert['username'] = $_POST['username'];
            $arrInsert['password'] = $_POST['password'];
            $arrInsert['designation'] = ($_POST['designation']) ? $_POST['designation'] : null;
            $arrInsert['access_role'] = $_POST['access_roles'];
            $arrInsert['phone_number'] = $_POST['phone'];
            $arrInsert['email'] = $_POST['email'];
            $this->user->fnSaveUser($arrInsert);
            $this->session->set_flashdata('success', "New user has been created");
            $strRedirectPath = base_url().'index.php/users/users_listing';
            redirect($strRedirectPath);
        } else {
            $arrCheckResult = $this->user->fnGetAccessRoles();
            /** if validation errors found then redirect  **/
            $strValidationErrors = validation_errors();
            if ($strValidationErrors != "" ) {
                $this->session->set_flashdata('error', $strValidationErrors);
                $strRedirectPath = base_url().'index.php/users/add_user';
                redirect($strRedirectPath);
            } else {
                $arrData['middle']   = 'admin/add_user';
                $arrData['access_roles']   = $arrCheckResult;
                $strValidationErrors = validation_errors();
                $this->session->set_flashdata('error', $strValidationErrors);
                echo $this->load->view('admin/add_user', $arrData);
            }
        }
    }

    /**
     * Function Update user
     * Functionality to Update user type in the system
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function update_user()
    {
        if (isset($_GET['user_id'])) {
            $intSelectedUser = (int)base64_decode($_GET['user_id']);
            if ($intSelectedUser == 0) {
                $this->session->set_flashdata('error', 'Please provide valid users Id');
                $strRedirectPath = base_url().'index.php/users/users_listing';
                redirect($strRedirectPath);
            }
        }

        # set form fields rules.
        $this->load->helper(array('form', 'url'));
        $this->load->model('user');
        $this->load->model('subscribers');
        # Set the form validation rule for the personal information such as name, email, phone,mobile, gender, NRIC
        $this->form_validation->set_rules('first_name', 'First Name', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');
        $this->form_validation->set_rules('username', 'Username', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('phone', 'Last Name', 'trim|required|max_length[100]|xss_clean');
        $this->form_validation->set_rules('access_roles', 'Access Roles', 'trim|required');
        #$this->form_validation->set_rules('designation', 'Designation', 'trim|required');
        # Check whether the validation turns true.
        if ($this->form_validation->run() == TRUE)
        {
            $arrInsert = array();
            $arrInsert['first_name'] = $_POST['first_name'];
            $arrInsert['last_name'] = $_POST['last_name'];
            $arrInsert['username'] = $_POST['username'];
            $arrInsert['password'] = $_POST['password'];
            $arrInsert['designation'] = ($_POST['designation']) ? $_POST['designation'] : null;
            $arrInsert['access_role'] = $_POST['access_roles'];
            $arrInsert['phone_number'] = $_POST['phone'];
            $arrInsert['email'] = $_POST['email'];
            $intSelectedUserId = (int) base64_decode($_POST['user_id']);
            $this->user->fnUpdateUser($arrInsert, $intSelectedUserId);
            $this->session->set_flashdata('success', "User Profile has been updated successfully");
            $strRedirectPath = base_url().'index.php/users/users_listing';
            redirect($strRedirectPath);
        } else {
            $arrCheckResult = $this->subscribers->fnGetDetails('user', $intSelectedUser);
            $arrAccessRoles = $this->user->fnGetAccessRoles();
            /** if validation errors found then redirect  **/
            $strValidationErrors = validation_errors();
            //echo "<pre>";print_r($strValidationErrors);exit;
            if ($strValidationErrors != "" ) {
                $this->session->set_flashdata('error', $strValidationErrors);
                $strRedirectPath = base_url().'index.php/users/add_user';
                redirect($strRedirectPath);
            } else {
                $arrData['middle']   = 'admin/add_user';
                $arrData['user_information']   = $arrCheckResult[0];
                $arrData['access_roles']   = $arrAccessRoles;
                $arrData['intSelectedUser']   = $intSelectedUser;
                $strValidationErrors = validation_errors();
                $this->session->set_flashdata('error', $strValidationErrors);
                echo $this->load->view('admin/update_user', $arrData);
            }
        }
    }

    /**
     * Function manage_permission
     * Functionality to add new user type in the system
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function manage_permission()
    {
        $arrData['middle']   = 'admin/manage_permission';
        $strValidationErrors = validation_errors();
        $this->session->set_flashdata('error', $strValidationErrors);
        $this->load->view('admin/templates/template', $arrData);
    }

    /**
     * Function logout
     *
     * Controllers  method. for logout
     *
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function logout()
    {
        # Check whether the session is set or not.
        $this->session->sess_destroy();
        $strRedirectpath = base_url().'index.php/users/login';
        redirect($strRedirectpath);

    }

    /**
     *  function dashboard
     *  Function to show dashboard  which show report listing.
     * @access public
     * @author Himanshu Charegaonkar
     */
    public function dashboard()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectpath = base_url().'index.php/users/login';
            redirect($strRedirectpath);
        }
        $intLimitForList = 3;

        $intMonth = "";
        $intYear = "";
        if($_POST['month'] != "") {
            $intMonth = $_POST['month'];
        } else {
            $intMonth = date('m');
        }

        if($_POST['year'] != "") {
            $intYear = $_POST['year'];
        } else {
            $intYear = date('Y');
        }
        # Call the model for taking count
        $this->load->model('subscribers');
        $arrSubscribers = $this->subscribers->fnGetSubscribersMagazineWise($intLimitForList);
        $arrSubscriptions = $this->subscribers->fnGetLatestSubscription($intLimitForList);
        $arrRenewals = $this->subscribers->fnGetLatestSubscription($intLimitForList, "renewals");

        $arrParamToSql = array('month' => $intMonth, 'year' => $intYear);
        //$arrTotalMonthlyRevenue = $this->subscribers->fnGetMonthlyTransactions("sum(amount) as amount", "GROUP BY MONTH( transaction_date )", 1, $arrParamToSql);
        $arrTotalMonthlyRevenue = $this->subscribers->fnGetMonthlyTransactions("sum(amount) as amount", "GROUP BY MONTH( transaction_date )", 1, $arrParamToSql);

        $arrTotalDailyRevenue = $this->subscribers->fnGetMonthlyTransactions("sum(amount) as amount, transaction_date", "GROUP BY DAY(transaction_date)",1,  $arrParamToSql);
        $arrTotalSumRevenue = $this->subscribers->fnGetMonthlyTransactions("sum(amount) as amount", "", 0, $arrParamToSql);

        $arrRevenue = array();
        if (count($arrTotalDailyRevenue) > 0) {
            foreach($arrTotalDailyRevenue as $revenue) {
                $arrRevenue[] = array(intval(strtotime($revenue['transaction_date']) * 1000), floatval($revenue['amount']));
            }
        }
        //$arrRevenue =  json_encode($arrRevenue, JSON_NUMERIC_CHECK);
        $arrData['middle']   = 'admin/dashboard';
        $arrData['magazine_subscribers']   = $arrSubscribers;
        $arrData['magazine_subscriptions']   = $arrSubscriptions;
        $arrData['magazine_renewals']   = $arrRenewals;
        $arrData['months'] =  array('1' => 'January', '2' => 'February', '3' => 'March', '4' => 'April', '5' => 'May',
            '6' => 'June', '7' => 'July', '8' => 'August', '9' => 'September', '10' => 'October',
            '11' => 'November', '12' => 'December');
        $arrData['year'] = array('2012' => '2012', '2013' => '2013', '2014' => '2014', '2015' => '2015');
        $arrData['monthly_revenue']   = $arrTotalMonthlyRevenue;
        $arrData['current_month']   = $intMonth;
        $arrData['current_year']   = $intYear;
        $arrData['daily_revenue']   = $arrRevenue;
        $arrData['sum_revenue']   = $arrTotalSumRevenue;

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

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

        $strSearchKey = "";
        if (isset($_GET['search_value'])) {
            $strSearchKey = $_GET['search_value'];
        }

        # Load the required models
        $this->load->model('subscribers');
        $this->load->library('pagination');
        $this->load->library('Backend_pagination');
        $arrSubscriptions = $this->subscribers->fnGetLatestSubscription("", "", $strSearchKey);

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


        $arrData['middle']   = 'admin/subscriptions';
        $arrData['magazine_subscriptions']   = $arrDetails;
        $this->load->view('admin/templates/template', $arrData);
    }

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

        $intMonth = "";
        if($_GET['month'] != "") {
            $intMonth = $_GET['month'];
        } else {
            $intMonth = date('m');
        }


        # Load the required models
        $this->load->model('subscribers');
        $arrSubscribers = $this->subscribers->fnGetSubscribersMagazineWise("", $intMonth);


        # Create a list of months.
        $arrMonthArray = array('1' => 'January', '2' => 'February', '3' => 'March', '4' => 'April', '5' => 'May',
            '6' => 'June', '7' => 'July', '8' => 'August', '9' => 'September', '10' => 'October',
            '11' => 'November', '12' => 'December');

        $arrData['middle']   = 'admin/subscribers';
        $arrData['magazine_subscribers']   = $arrSubscribers;
        $arrData['arrMonthArray']   = $arrMonthArray;
        $arrData['intMonth']   = $intMonth;
        $this->load->view('admin/templates/template', $arrData);
    }

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

        $strSearchKey = "";
        if (isset($_GET['search_value'])) {
            $strSearchKey = $_GET['search_value'];
        }


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


        $arrRenewals = $this->subscribers->fnGetLatestSubscriptionPagination("", "", $strSearchKey);
        $intTotal = count($arrRenewals);

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




        $arrData['middle']   = 'admin/renewals';
        $arrData['magazine_renewals']   = $arrDetails;
        $arrData['strSearchKey']   = $strSearchKey;
        $arrData['intTotal']   = $intTotal;
        $this->load->view('admin/templates/template', $arrData);
    }

    /*
     * Function renewals
     * Function to get the upcoming renewals
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function settings()
    {
        $arrData['middle']   = 'admin/settings';
        //$arrData['magazine_renewals']   = $arrRenewals;
        $this->load->view('admin/templates/template', $arrData);
    }

    /*
     * Function transaction_preview
     * Function to get the transaction preview
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    public function transaction_preview()
    {
        $intTransactionId = $_GET['transaction_id'];
        # Call the model for taking count
        $this->load->model('subscribers');
        $arrRenewalsDetails = $this->subscribers->fnGetAllDetails('transaction', 'transaction_id', $intTransactionId);
        $arrRenewals = $arrRenewalsDetails[0];
        $intCounter = 0;
        foreach($arrRenewalsDetails as $indTransaction) {
            $arrMagazineInfo = $this->subscribers->fnGetDetails("magazine", $indTransaction['product_id']);
            $arrRenewalsDetails[$intCounter]['magazine_code'] = $arrMagazineInfo[0]['magezine_id'];
            $intCounter++;
        }

        $arrSubscriberInfo = $this->subscribers->fnGetDetails("subscriber", $arrRenewalsDetails[0]['subscriber_id']);
        $strSubscriberName = $arrSubscriberInfo[0]['last_name']." ".$arrSubscriberInfo[0]['first_name'];
        $arrMonths = array(1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April', 5 => 'May', 6 => 'June', 7 => 'July', 8 => 'Augest',
                            9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December');

        #get the payment Details:
        $intPaymentOption =  $arrRenewals['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', 9 => 'payment_nets',10 => 'payment_paynow');

        $arrTableName = unserialize(arrPaymentMethods);

        if ($arrRenewalsDetails[0]['status'] > 1) {
            # get the relative payment details:
            $arrPayDetails = $this->subscribers->fnGetPaymentDetails($arrTableName[$intPaymentOption], $arrRenewalsDetails[0]['id']);
            $strPaymentMethod = str_replace("payment_", " ",$arrTableName[$intPaymentOption]);
            $strPaymentMethod = ucwords(str_replace("_", " ",$strPaymentMethod));
            $strRowData = '<tr><th  data-class="highlight" class="text-center">Payment Method</th>
                            <td  class="text-center">'.$strPaymentMethod.'</td></tr>';
            $strCashCollectedBy = "";
            $strCashCollectedBy = $arrPayDetails[0]["other_details"];
            if ($arrPayDetails[0]["agent_id"] > 0) {
                $arrAgentDetails = $this->subscribers->fnGetDetails("agent", $arrPayDetails[0]["agent_id"]);
                $strCashCollectedBy = $arrAgentDetails[0]['first_name']." ".$arrAgentDetails[0]['last_name'];
            }
            if ($intPaymentOption == 1) {
                #$arrRenewals['campaign_id'] = $arrPayDetails[0];
                $strRowData .= '<tr><th  data-class="highlight" class="text-center">Cash collected by</th>
                            <td  class="text-center">'.$strCashCollectedBy.'</td></tr>';

            } elseif ($intPaymentOption == 2) {
                #$arrRenewals['cheque_date'] = $arrPayDetails[0]['cheque_date'];
                #$arrRenewals['cheque_number'] = $arrPayDetails[0]['cheque_number'];
                #$arrRenewals['issued_bank'] = $arrPayDetails[0]['issued_bank'];
                $strRowData .= '<tr><th  data-class="highlight" class="text-center">Cheque Data</th>
                            <td  class="text-center">'.date("d M Y",strtotime($arrPayDetails[0]["cheque_date"])).'</td></tr>';
                $strRowData = $strRowData.'<tr><th  data-class="highlight" class="text-center">Cheque Number</th>
                            <td  class="text-center">'.$arrPayDetails[0]["cheque_number"].'</td></tr>';
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Issued Bank</th>
                            <td  class="text-center">'.$arrPayDetails[0]["issued_bank"].'</td></tr>';
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Collected by</th>
                            <td  class="text-center">'.$strCashCollectedBy.'</td></tr>';
            } elseif ($intPaymentOption == 3) {
                #$arrRenewals['card_number'] = $arrPayDetails[0]['card_number'];
                #$arrRenewals['card_name'] = $arrPayDetails[0]['card_name'];
                #$arrRenewals['card_expiry'] = $arrPayDetails[0]['card_expiry'];
                #$arrRenewals['card_bank'] = $arrPayDetails[0]['card_bank'];

                $strRowData .= '<tr><th  data-class="highlight" class="text-center">Card Number</th>
                            <td  class="text-center">'.$arrPayDetails[0]["card_number"].'</td></tr>';
                $strRowData = $strRowData.'<tr><th  data-class="highlight" class="text-center">Card Name</th>
                            <td  class="text-center">'.$arrPayDetails[0]["card_name"].'</td></tr>';

                $strExperyDdate =  explode("-", $arrPayDetails[0]["card_expiry"]);
                $strExpieryMonth = $arrMonths[$strExperyDdate[0]]." ".$strExperyDdate[1];
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Card Expiry</th>
                            <td  class="text-center">'.$strExpieryMonth.'</td></tr>';
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Card bank</th>
                            <td  class="text-center">'.$arrPayDetails[0]["card_bank"].'</td></tr>';
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Collected by</th>
                            <td  class="text-center">'.$strCashCollectedBy.'</td></tr>';

            } elseif ($intPaymentOption == 4) {
                $strRowData .= '<tr><th  data-class="highlight" class="text-center">Transaction Id</th>
                            <td  class="text-center">'.$arrPayDetails[0]["online_transaction_id"].'</td></tr>';
                $strRowData = $strRowData.'<tr><th  data-class="highlight" class="text-center">Bank Name</th>
                            <td  class="text-center">'.$arrPayDetails[0]["isseud_bank_name"].'</td></tr>';
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Transaction Date</th>
                            <td  class="text-center">'.$arrPayDetails[0]["transaction_date"].'</td></tr>';
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Collected by</th>
                            <td  class="text-center">'.$strCashCollectedBy.'</td></tr>';
            } elseif ($intPaymentOption == 5) {
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Collected by</th>
                            <td  class="text-center">'.$strCashCollectedBy.'</td></tr>';
            } elseif ($intPaymentOption == 6) {
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Collected by</th>
                            <td  class="text-center">'.$strCashCollectedBy.'</td></tr>';
            } elseif ($intPaymentOption == 7) {
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Collected by</th>
                            <td  class="text-center">'.$strCashCollectedBy.'</td></tr>';
            } elseif ($intPaymentOption == 8) {
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Collected by</th>
                            <td  class="text-center">'.$strCashCollectedBy.'</td></tr>';
            } elseif ($intPaymentOption == 9) {
                $strRowData .= '<tr><th  data-class="highlight" class="text-center">Transaction Id</th>
                            <td  class="text-center">'.$arrPayDetails[0]["nets_transaction_id"].'</td></tr>';
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Transaction Date</th>
                            <td  class="text-center">'.$arrPayDetails[0]["transaction_date"].'</td></tr>';
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Collected by</th>
                            <td  class="text-center">'.$strCashCollectedBy.'</td></tr>';
            } elseif ($intPaymentOption == 10) {
                // $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Purchase Code</th>
                //             <td  class="text-center">'.$arrPayDetails[0]["purchase_code"].'</td></tr>';
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Collected by</th>
                            <td  class="text-center">'.$strCashCollectedBy.'</td></tr>';
            } elseif ($intPaymentOption == 11) {
                
                $strRowData = $strRowData. '<tr><th  data-class="highlight" class="text-center">Collected by</th>
                            <td  class="text-center">'.$strCashCollectedBy.'</td></tr>';
            }

        }

        $arrData['middle']   = 'admin/transaction_preview';
        $arrData['arrSub']   = $arrRenewalsDetails;
        $arrData['strRowData']   = $strRowData;
        $arrData['strSubscriberName']   = $strSubscriberName;
        echo $this->load->view('admin/transaction_preview', $arrData);
    }

    /**
     * Function to check details.
     * An ajax handler function of add user validation.
     */
    public function fnCheckDetails()
    {
        $strFieldName = $_GET['field'];
        $strValue = $_GET['value'];
        $this->load->model('user');
        $arrVal = $this->user->fnCheckDetails($strFieldName, $strValue);
        echo  count($arrVal);exit;
    }


    /**
     * Function to get all users of the system
     * Accept no parameter
     * @access public
     * @author Himanshu Charegaonkar
     */
    public function users_listing()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }
        # Load required model
        $this->load->model('user');

        $strSelectedRole = (int) $_GET['sel_role'];
        # Call model function to Get the details of users such as name, email etc.
        $arrUserList = $this->user->fnCheckDetails("","",$strSelectedRole);
        # Get all available access roles.
        $arrUserRole = $this->user->fnGetAccessRoles();

        # Make the key value pair array depending upon the id.
        $arrUserRoleById= array();
        foreach($arrUserRole as  $role) {
            $arrUserRoleById[$role['id']] = $role['name'];
        }
        $arrData['middle']   = 'admin/user_listing';
        $arrData['users']   = $arrUserList;
        $arrData['roles']   = $arrUserRoleById;
        $arrData['selected_roles']   = $strSelectedRole;
        $arrData['access_roles']   = $arrUserRole;
        $this->load->view('admin/templates/template', $arrData);
    }

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

        $strGetAllAccess = $this->user->fnGetAccessRoles();

        $strSearchKey = "";
        if ($_GET['sel_role'] != "") {
            $strSearchKey = $_GET['sel_role'];
        }
        # Get all available access roles.
        $arrUserRole = $this->user->fnGetAccessRoles($strSearchKey);
        //echo "<pre>";print_r($arrUserRole);exit;
        $arrData['middle']   = 'admin/access_listing';
        $arrData['roles']   = $arrUserRole;
        $arrData['selected_roles']   = $strSearchKey;
        $arrData['all_access']   = $strGetAllAccess;
        $this->load->view('admin/templates/template', $arrData);
    }

    function fnEditAccess()
    {
        $intAccessId = base64_decode($_GET['id']);
        # set form fields rules.
        $this->load->helper(array('form', 'url'));
        $this->load->model('user');
        # Set the form validation rule for the personal information such as name, email, phone,mobile, gender, NRIC
        $this->form_validation->set_rules('name', 'Access Name', 'trim|required|max_length[100]|xss_clean');
        # Check whether the validation turns true.
        if ($this->form_validation->run() == TRUE)
        {
            $arrInsert = array();
            $arrInsert['name'] = $_POST['name'];
            $intAccessId = $_POST['id'];
            #Update the access.
            $this->user->fnUpdateAccess($intAccessId, $arrInsert);
            $this->session->set_flashdata('success', "Access Details has been updated");
            $strRedirectPath = base_url().'index.php/users/access_listing';
            redirect($strRedirectPath);
        } else {
            /** if validation errors found then redirect  **/
            $strValidationErrors = validation_errors();
            if ($strValidationErrors != "" ) {
                $this->session->set_flashdata('error', $strValidationErrors);
                $strRedirectPath = base_url().'index.php/users/add_access';
                redirect($strRedirectPath);
            } else {
                # Get all available access roles.
                $arrAccessDetails = $this->user->fnGetAccessRoles($intAccessId);
                $arrData['middle']   = 'admin/add_user';
                $arrData['access_details']   = $arrAccessDetails[0];
                $strValidationErrors = validation_errors();
                $this->session->set_flashdata('error', $strValidationErrors);
                echo $this->load->view('admin/edit_access', $arrData);
            }
        }
    }

    /**
     * function fnCheckAccessName
     * Function to check the access Names.
     */
    function fnCheckAccessName()
    {
        $strAccessName = strtolower($_GET['name']);
        # set form fields rules.
        $this->load->helper(array('form', 'url'));
        $this->load->model('user');
        $arrAccessDetails = $this->user->fnCheckAccessName($strAccessName);
        echo count($arrAccessDetails);exit;
    }

    function fnAddAccess()
    {
        # set form fields rules.
        $this->load->helper(array('form', 'url'));
        $this->load->model('user');
        $this->load->model('subscribers');
        # Set the form validation rule for the personal information such as name, email, phone,mobile, gender, NRIC
        $this->form_validation->set_rules('name', 'Access Name', 'trim|required|max_length[100]|xss_clean');
        # Check whether the validation turns true.
        if ($this->form_validation->run() == TRUE)
        {
            $arrInsert = array();
            $arrInsert['name'] = $_POST['name'];
            $intAccessId = $_POST['id'];
            $intNewAccessLevel = $this->subscribers->fnSaveAllDetails('access_roles',$arrInsert);
            $arrNewAccessLevel = array();
            $arrNewAccessLevel['level_id'] = $intNewAccessLevel;
            $arrNewAccessLevel['alloted_access'] = 0;
            $this->subscribers->fnSaveAllDetails('access_role_management', $arrNewAccessLevel);

            $this->session->set_flashdata('success', "New Access level has been created");
            $strRedirectPath = base_url().'index.php/users/access_listing';
            redirect($strRedirectPath);
        } else {

            /** if validation errors found then redirect  **/
            $strValidationErrors = validation_errors();
            if ($strValidationErrors != "" ) {
                $this->session->set_flashdata('error', $strValidationErrors);
                $strRedirectPath = base_url().'index.php/users/add_access';
                redirect($strRedirectPath);
            } else {
                $arrData['middle']   = 'admin/add_user';
                $strValidationErrors = validation_errors();
                $this->session->set_flashdata('error', $strValidationErrors);
                echo $this->load->view('admin/add_access', $arrData);
            }
        }
    }

    function fnDeleteAccess()
    {
        $intAccessId = (int)base64_decode($_GET['id']);
        $this->load->model('user');
        $this->user->fnDeleteAccessLevel($intAccessId);
        echo 1;exit;

    }

    function fnSendChangePasswordEmail()
    {
        $strEmailId = (string)$_POST['email_id'];
        # First check whether the email address has been entered or not
        if ($strEmailId == "") {
            $this->session->set_flashdata('error', "Please enter email address");
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }
        # now check whether the email address has been exist in database or not
        $this->load->model('user');
        $arrCheckResult = $this->user->fnCheckForEmail($strEmailId);
        if (empty($arrCheckResult)) {
            $this->session->set_flashdata('error', "Given email address not found");
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }
                                                              
        $intUserId = $arrCheckResult[0]['id'];
        $strUserName = $arrCheckResult[0]['first_name']." ".$arrCheckResult[0]['last_name'];
        $strEmailChangeUrl = base_url()."index.php/users/fnChangePassword/?id=Str-user".base64_encode($intUserId);
        $strHtml = "<p> Hello {$strUserName} </p>
                    <p>Please find the below link to change your password for system: </p>
                    <p>{$strEmailChangeUrl}</p>";
        $this->load->library('email');
        $this->email->set_mailtype("html");
        $this->email->from('team@smsystem.com', 'Subscription Management System');
        $this->email->to($strEmailId);

        $this->email->subject('Link to change the password');
        $this->email->message($strHtml);

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

        $this->session->set_flashdata('success', "Link has been send to your registered email.");
        $strRedirectPath = base_url().'index.php/users/login';
        redirect($strRedirectPath);
    }

    function fnChangePassword()
    {
        $strGetUserId = $_GET['id'];
        $strUserId = substr($strGetUserId, 8);
        if (isset($_POST['new_password'])) {
            $strNewPassword = trim($_POST['new_password']);
            $strRePassword = trim($_POST['re_password']);
            $strGivenUserId = (int)base64_decode($_POST['given_user_id']);
            if ($strNewPassword != $strRePassword) {
                $arrData['strUserId'] = $_POST['given_user_id'];
                $this->load->view('admin/create_new_password', $arrData);
            }
            $arrUpdateInfo = array();
            $arrUpdateInfo['password'] = $strNewPassword;
            $this->load->model('user');
            $boolStatus = $this->user->fnUpdateUser($arrUpdateInfo, $strGivenUserId);
            $this->session->set_flashdata('success', "Password has been changed, please login with new credentials");
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        } else {
            $arrData['strUserId'] = $strUserId;
            $arrData['middle']   = 'admin/create_new_password';
            $this->load->view('admin/create_new_password', $arrData);
        }


    }
}
