<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
# Include required library.
# Set the file upload configuration.
if ($_SERVER['HTTP_HOST'] == 'localhost') {
    require_once $_SERVER['DOCUMENT_ROOT']."/smsystem/PHPExcel/Classes/PHPExcel.php";
    require_once $_SERVER['DOCUMENT_ROOT']."/smsystem/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 Promotion extends CI_Controller {

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

	/**
	* Function magazine_list
	* Listting of added magezines.
	* @author	Himanshu Charegaonkar
	* @access	public
	*/
	public function promotion_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('promotions');
        $this->load->library('pagination');
        $this->load->library('Backend_pagination');

        $strSearchKey = "";
        $strCampCode = "";
        if (count($_GET) > 0) { // If there is date then put the date related condition.
            $strCampCode = $_GET['camp_code'];
            if ($_GET['camp_code'] != "") {
                $strSearchKey = $strSearchKey. " AND (name LIKE '%".$strCampCode."%' OR campeign_code LIKE '%".$strCampCode."%')";
            }
        }
		
		/** Pagination patch start **/
		
		# Call the model for taking count 
		$arrCountArray = $this->promotions->fnGetAllPromotions('campaigns',"","", $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/promotion/promotion_list/';
        $this->backend_pagination->setup_pagination();
        $arrData['cust_Pagination']  = $this->backend_pagination->strpagination;
        $arrDetails = $this->promotions->fnGetAllPromotions('campaigns', $this->backend_pagination->limit,$this->backend_pagination->offsetPage , $strSearchKey);
		/** Pagination patch end **/

		# Add the middle content to the template.
		
		$arrData['middle'] = 'promotion/promotion';
		$arrData['details'] = $arrDetails;
        $arrData['arrGetData']   = $_GET;
        $arrData['strCampCode']   = $strCampCode;

		$this->load->view('admin/templates/template', $arrData);
	}
	
	/**
	* Function magazine_list
	* Listting of added magezines.
	* @author	Himanshu Charegaonkar
	* @access	public
	*/
	public function add_promotion()
	{
		# 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('promotions');

        # set form fields rules.
		$this->load->helper(array('form', 'url'));
		$this->form_validation->set_rules('promo_code', 'Promo Code');
		$this->form_validation->set_rules('promo_name', 'Promo Name');
		$this->form_validation->set_rules('desc', 'Description', 'required');

		# Check whether the validation turns true.
		if ($this->form_validation->run() == TRUE)
		{
            $arrPostedData = $_POST;
            #1. Get all information and then first make in entry of campaign
			$arrMagezine = array();
			$arrMagezine['campeign_code'] = $arrPostedData['promo_code'];
            $arrMagezine['name'] = $arrPostedData['promo_name'];
			$arrMagezine['description'] = $arrPostedData['desc'];


            # Save to the database.
            $intNewPromotionId = $this->promotions->fnSavePromotion('campaigns', $arrMagezine);


            #2. Now save the magazine information such as start issue, end issue.
            $arrAllMagazines = $arrPostedData['magezine_code'];
            $arrStartIssue = $arrPostedData['camp_start_issue'];
            $arrEndIssue = $arrPostedData['camp_end_issue'];
            $arrAmount = $arrPostedData['camp_amount'];
            $arrNumberOfYear = $arrPostedData['camp_no_of_year'];
            $arrStartDate = $arrPostedData['camp_start_date'];
            $arrEndDate = $arrPostedData['camp_end_end'];
            $arrTotalIssue = $arrPostedData['camp_total_issue'];

            $arrResultForMagazineCampaign = array();

            $intCounter = 0;
            foreach($arrAllMagazines as $allMagazine) {
                $arrMagDetails = array();
                $arrMagDetails['campaign_id'] = $intNewPromotionId;
                $arrMagDetails['magazine_code'] = $arrAllMagazines[$intCounter];
                $arrMagDetails['start_issue'] = $arrStartIssue[$intCounter];
                $arrMagDetails['end_issue'] = $arrEndIssue[$intCounter];
                $arrMagDetails['amount'] = $arrAmount[$intCounter];
                $arrMagDetails['start_date'] = date("Y-m-d", strtotime($arrStartDate[$intCounter]));
                $arrMagDetails['end_date'] = date("Y-m-d", strtotime($arrEndDate[$intCounter]));
                $arrMagDetails['no_of_year'] = $arrNumberOfYear[$intCounter];
                $arrMagDetails['no_of_issue'] = $arrTotalIssue[$intCounter];
                # Save to the database.
                $intNewCampaignMagazineId = $this->promotions->fnSavePromotion('campaign_magazine', $arrMagDetails);
                $intCounter++;
            }

            $this->session->set_flashdata('success', 'New campaign has been added successfully');
			redirect(base_url().'index.php/promotion/promotion_list');
		} else {
			
			/** if validation errros found then redirect  **/
			$strValidationErrors = validation_errors();
			if ($strValidationErrors != "" ) {
				$this->session->set_flashdata('error', $strValidationErrors);
				$strRedirectpath = base_url().'index.php/promotion/add_promotion/';
				redirect($strRedirectpath);
			} else {
				$arrAvailablemagezine = $this->promotions->fnGetLiveMagezines();
				$arrData['magezine'] = $arrAvailablemagezine;
				$arrData['middle']   = 'promotion/add_promotion';
				$strValidationErrors = validation_errors();
				$this->session->set_flashdata('error', $strValidationErrors);
				//echo $this->load->view('promotion/add_promotion', $arrData, true);exit;

                $arrNewMagazineDetails = $this->load->view('promotion/add_new_magazine', $arrData, true);
                $arrData['abc'] = $arrNewMagazineDetails;
                $this->load->view('admin/templates/template', $arrData);
			}
		}
	}
	
	/**
	 * Function edit promotion
	 * Listting of added magezines.
	 * @author	Himanshu Charegaonkar
	 * @access	public
	 */
	public function edit_promotion()
	{
		# Check whether the session is set or not.
		if(! $this->session->userdata('username') ) {
			$strRedirectpath = base_url().'index.php/users/login';
			redirect($strRedirectpath);
		}

		# now check whether we receive the valid promotion id.
        $intRecPromoId = (int) base64_decode($_REQUEST['promotion_id']);
        if ($intRecPromoId == 0) {
            $strRedirectpath = base_url().'index.php/promotion/promotion_list';
            redirect($strRedirectpath);
		}
		
		# Load the required model.
		$this->load->model('promotions');
		
		# Call the model for taking count 
		$arrCountArray = array();
		$arrCountArray = $this->promotions->fnGetDetails('campaigns', $intRecPromoId);
		# set form fields rules.
		$this->load->helper(array('form', 'url'));
		if ($_POST['promo_code'] == $arrCountArray[0]['promo_code']) {
			$this->form_validation->set_rules('promo_code', 'Promo Code', 'required|max_length[100]|alpha_numeric|xss_clean');
		} else {
			$this->form_validation->set_rules('promo_code', 'Promo Code', 'required|is_unique[promotion.promo_code]|max_length[100]|alpha_numeric|xss_clean');
		}

        $this->form_validation->set_rules('promo_name', 'Promo Name');
        $this->form_validation->set_rules('desc', 'Description', 'required');

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

            #1. Get all information and then first make in entry of campaign
            $arrMagezine = array();
            $arrMagezine['campeign_code'] = $arrPostedData['promo_code'];
            $arrMagezine['name'] = $arrPostedData['promo_name'];
            $arrMagezine['description'] = $arrPostedData['desc'];
            # Update to the database.
			$this->promotions->fnUpdatePromotion($arrMagezine, $intRecPromoId);

            $intCampaignId = base64_decode($arrPostedData['promotion_id']);
            # Now delete the previous related content of campaign magazine and then create new.
            #I. First get the related ids of the campaign's magazines involved.
            $arrCampaignInfo = $this->promotions->fnDeleteMagazineList($intCampaignId);


            #2. Now save the magazine information such as start issue, end issue.
            $arrAllMagazines = $arrPostedData['magezine_code'];
            $arrStartIssue = $arrPostedData['camp_start_issue'];
            $arrEndIssue = $arrPostedData['camp_end_issue'];
            $arrAmount = $arrPostedData['camp_amount'];
            $arrNumberOfYear = $arrPostedData['camp_no_of_year'];
            $arrStartDate = $arrPostedData['camp_start_date'];
            $arrEndDate = $arrPostedData['camp_end_end'];
            $arrTotalIssue = $arrPostedData['camp_total_issue'];
            $intCounter = 0;
            foreach($arrAllMagazines as $allMagazine) {
                $arrMagDetails = array();
                $arrMagDetails['campaign_id'] = $intCampaignId;
                $arrMagDetails['magazine_code'] = $arrAllMagazines[$intCounter];
                $arrMagDetails['start_issue'] = $arrStartIssue[$intCounter];
                $arrMagDetails['end_issue'] = $arrEndIssue[$intCounter];
                $arrMagDetails['amount'] = $arrAmount[$intCounter];
                $arrMagDetails['start_date'] = date("Y-m-d", strtotime($arrStartDate[$intCounter]));
                $arrMagDetails['end_date'] = date("Y-m-d", strtotime($arrEndDate[$intCounter]));
                $arrMagDetails['no_of_year'] = $arrNumberOfYear[$intCounter];
                $arrMagDetails['no_of_issue'] = $arrTotalIssue[$intCounter];
                # Save to the database.
                $intNewCampaignMagazineId = $this->promotions->fnSavePromotion('campaign_magazine', $arrMagDetails);
                $intCounter++;
            }

            # Redirect to listing page with the success message.
			$this->session->set_flashdata('success', 'Promotion has been updated successfuly');
			redirect(base_url().'index.php/promotion/promotion_list');
		} else {
			
			/** if validation errros found then redirect  **/
			$strValidationErrors = validation_errors();
			if ($strValidationErrors != "" ) {
				$this->session->set_flashdata('error', $strValidationErrors);
				$strRedirectpath = base_url().'index.php/promotion/edit_promotion/?promotion_id='.$_GET['promotion_id'];
				redirect($strRedirectpath);
			} else {
				#1.  Get all magezines and create an array of magazines.
				$arrCampaignDetails = $this->promotions->fnGetDetails('campaigns', $intRecPromoId);

                #2. Now get the all magazines associate with these
                $arrAssociateMagazines = $this->promotions->fnGetDetailsOfTable('campaign_magazine', 'campaign_id', $intRecPromoId);
                $arrData['magazines_details'] = $arrAssociateMagazines;
				# Array of all promotions.+
                $arrData['promotion'] = $arrCampaignDetails[0];
                $arrData['promo_id'] = $_REQUEST['promotion_id'];
				$arrData['middle']   = 'promotion/edit_promotion';
				$strValidationErrors = validation_errors();
				$this->session->set_flashdata('error', $strValidationErrors);
				$this->load->view('admin/templates/template', $arrData);
			}
		}
	}

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

        # now check whether we receive the valid promotion id.
        $intRecPromoId = (int) base64_decode($_GET['promotion_id']);
        if ($intRecPromoId == 0) {
            $strRedirectpath = base_url().'index.php/promotion/promotion_list';
            redirect($strRedirectpath);
        }

        # Load the required model.
        $this->load->model('promotions');

        # delete requested subscription
        $arrResultSet = $this->promotions->fnDeletePromotion($intRecPromoId);

        # Redirect with success message.
        $this->session->set_flashdata('success', 'Promotion has been deleted');
        $strRedirectpath = base_url().'index.php/promotion/promotion_list';
        redirect($strRedirectpath);
    }

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

        # now check whether we receive the valid promotion id.
        $intRecPromoId = (int) base64_decode($_GET['promotion_id']);
        if ($intRecPromoId == 0) {
            $strRedirectpath = base_url().'index.php/promotion/promotion_list';
            redirect($strRedirectpath);
        }

        $intPromotionStatus = (int) base64_decode($_GET['status']);

        $intSetStatus = ($intPromotionStatus == 1) ? '0':'1';

        # Load the required model.
        $this->load->model('promotions');

        $arrMagazine['is_archived'] = $intSetStatus;
        # Update to the database.
        $this->promotions->fnUpdatePromotion($arrMagazine, $intRecPromoId);

        # Redirect with success message.
        $this->session->set_flashdata('success', 'Promotion has been archived');
        $strRedirectpath = base_url().'index.php/promotion/promotion_list';
        redirect($strRedirectpath);
    }

    /*
     * Function fnCheckPromotionCode
     * Function to check the promotion code
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    function fnCheckPromotionCode()
    {
            $strPromoCode = $_GET['promotion_id'];
            # Load the required model.
            $this->load->model('promotions');

            # delete requested subscription
            $arrResultSet = $this->promotions->fnCheckPromotionCode($strPromoCode);
            echo count($arrResultSet);
    }

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

        # now check whether we receive the valid promotion id.
        $intRecPromoId = (int) base64_decode($_GET['promotion_id']);
        if ($intRecPromoId == 0) {
            $strRedirectpath = base_url().'index.php/promotion/promotion_list';
            redirect($strRedirectpath);
        }

        $this->load->model('promotions');

        $arrMagazineDetails = $this->promotions->fnGetAllMagazines($intRecPromoId);
        //echo "<pre>";print_r($arrMagazineDetails);exit;
        $arrDetails = $this->promotions->fnGetAllRevenueForPromotion($arrMagazineDetails[0]['promo_code']);
        $Details['arrMagazineDetails'] = $arrMagazineDetails;
        $Details['arrDetails'] = $arrDetails;
        $arr_data = $this->load->view('promotion/promo_pdf', $Details, true);
        $this->load->library('common');
        $arrData['arrData']   = $arr_data;
        $this->common->getPDFReport_common($arrMagazineDetails, 'receipt.pdf', 'promotion/promo_pdf');exit;

    }

    /**
     * Function to generate the excel sheet of the promotion.
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    function fnGenerateExcelSheet()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }

        # now check whether we receive the valid promotion id.
        $intRecPromoId = (int) base64_decode($_GET['promotion_id']);
        if ($intRecPromoId == 0) {
            $strRedirectPath = base_url().'index.php/promotion/promotion_list';
            redirect($strRedirectPath);
        }

        $this->load->model('promotions');
        $arrMagazineDetails = $this->promotions->fnGetAllMagazines($intRecPromoId);
        $arrDetails = $this->promotions->fnGetAllRevenueForPromotion($arrMagazineDetails[0]['promo_code']);


        $strTimePeriod = "Promotion used for the Period: ".date("d M Y", strtotime($arrMagazineDetails[0]['start_date']))."To".date("d M Y", strtotime($arrMagazineDetails[0]['end_date']));
        $strTotalRevenue = "Total Revenue Earned by using promotion: ".(int)$arrDetails[0]['total_revenue'];
        $strTotalDiscount = "Total discount given by using promotion:". (int)$arrDetails[0]['total_discount'];
        $strTotalMagazines = "Total magazines used promotion: ".(int)count($arrMagazineDetails);

        $objPHPExcel = new PHPExcel();

        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->SetCellValue('B2', 'Details of the Magazine under this promotion');
        $objPHPExcel->getActiveSheet()->SetCellValue('B4', $strTimePeriod);
        $objPHPExcel->getActiveSheet()->SetCellValue('B5', $strTotalRevenue);
        $objPHPExcel->getActiveSheet()->SetCellValue('B6', $strTotalDiscount);
        $objPHPExcel->getActiveSheet()->SetCellValue('B7', $strTotalMagazines);
        $objPHPExcel->getActiveSheet()->SetCellValue('B9', 'Magazine Code');
        $objPHPExcel->getActiveSheet()->SetCellValue('C9', 'Magazine Name');
        $objPHPExcel->getActiveSheet()->SetCellValue('D9', 'Description');
        $objPHPExcel->getActiveSheet()->SetCellValue('E9', 'Status');
        $objPHPExcel->getActiveSheet()->SetCellValue('F9', 'No. Of subscribers');

        $rowNumber = 11;
        foreach($arrMagazineDetails as $cell) {
                $objPHPExcel->getActiveSheet()->setCellValue('B'.$rowNumber,$cell['magezine_id']);
                $objPHPExcel->getActiveSheet()->setCellValue('C'.$rowNumber,$cell['name']);
                $objPHPExcel->getActiveSheet()->setCellValue('D'.$rowNumber,$cell['description']);
                $objPHPExcel->getActiveSheet()->setCellValue('E'.$rowNumber,$cell['status']);
                $objPHPExcel->getActiveSheet()->setCellValue('F'.$rowNumber,$cell['total_subscriber']);
                $rowNumber++;
            }

        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();

    }


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

        $strPreviousIds = $_GET['prev_ids'];
        $strNOOfYears = $_GET['no_of_years'];
        /*$strAllMagazineIds = "";
        if ($strPreviousIds != "") {
            $PreviousIds = explode(",", $strPreviousIds);
            $arrIdsOfMagazines = array();
            foreach($PreviousIds as $id) {
                $arrResult = $this->magezines->fnCheckMagazineCode($id);
                $arrIdsOfMagazines[] = $arrResult[0]['id'];
            }

            $strAllMagazineIds = implode(",", $arrIdsOfMagazines);

        } */

        # Load the required model.
        $this->load->model('promotions');
        $this->load->model('magezines');

        if ($strPreviousIds == "" || $strPreviousIds == null) {
            $arrAvailableMagezine = $this->promotions->fnGetLiveMagazinesWithYears("", "");
            $arrData['magezine'] = $arrAvailableMagezine;
            $arrData['strNOOfYears'] = $strNOOfYears;

            echo $this->load->view('promotion/add_new_magazine', $arrData, true);exit;
        } else {
            $arrMagazineInfo = $this->magezines->fnGetMagazinesSubscriptionYear($strPreviousIds, $strNOOfYears);
            if (count($arrMagazineInfo) > 0) {
                echo $arrMagazineInfo[0]['amount'];exit;
            } else {
                echo ""; exit;
            }

        }

    }

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

        $strPreviousIds = $_GET['prev_ids'];
        # Load the required model.
        $this->load->model('promotions');
        $this->load->model('magezines');

        $arrAvailableMagezine = $this->promotions->fnGetLiveMagazinesWithYears("", "");
        $arrData['magezine'] = $arrAvailableMagezine;
        //$arrData['strNOOfYears'] = $strNOOfYears;

        echo $this->load->view('promotion/add_new_magazine', $arrData, true);exit;
    }

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

        $strPreviousIds = $_GET['prev_ids'];
        $strNOOfYears = $_GET['no_of_years'];
        # Load the required model.
        $this->load->model('magezines');

        $arrMagazineInfo = $this->magezines->fnGetMagazinesSubscriptionYear($strPreviousIds, $strNOOfYears);
        if (count($arrMagazineInfo) > 0) {
            echo $arrMagazineInfo[0]['amount'];exit;
        } else {
            echo ""; exit;
        }
    }
    public function fnGetCampaignDetails()
    {
        # Check whether the session is set or not.
        if(! $this->session->userdata('username') ) {
            $strRedirectPath = base_url().'index.php/users/login';
            redirect($strRedirectPath);
        }

        $strCampaignMagazineId = $_GET['prev_ids'];
        $strCampaignId = $_GET['campaign_id'];
        $intRowId = $_GET['row_id'];
        $this->load->model('magezines');
        # Load the required model.
        $this->load->model('promotions');

        #2. Now get the all magazines associate with these
        $arrAssociateMagazines = $this->promotions->fnGetDetails( 'campaign_magazine', $strCampaignMagazineId);
        $arrAssociateMagazines = $arrAssociateMagazines[0];
        $arrFinalResult = $this->promotions->fnGetDetailsOfTable('campaign_magazine_year', 'campaign_magazine_id', $strCampaignMagazineId);
        $arrYears = array();
        foreach($arrFinalResult as $result) {
            $arrYears[$result['year']] = $result['amount'];
        }
        $arrAssociateMagazines['year'] = $arrYears;
        //echo "<pre>";print_r($arrAssociateMagazines);exit;
        $arrData['magezine'] = $arrAssociateMagazines;
        $arrData['row_id'] = $intRowId;
        echo $this->load->view('promotion/edit_camp_details', $arrData, true);exit;
    }

    /**
     * Function to get the Magazine amount.
     */
    function fnGetMagazineAmount()
    {
        # Load the required model.
        $this->load->model('promotions');
        $arrResultSet = $this->promotions->fnGetMagazineYearAmount($_GET['strMagazineId'], $_GET['NumberOfYear']);
        echo $arrResultSet[0]['amount'];
    }

    function fnGenerateMagazineReport()
    {
        # 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('promotions');
        $arrResultSet = $this->promotions->fnGetAllMagazinesOfCampaign($intCampaignId);
        if (count($arrResultSet) > 0) {
            $strCampaignCode = "Campaign Code: ".$arrResultSet[0]['campeign_code'];
            $strCampaignName = "Campaign Name: ".$arrResultSet[0]['name'];
            $strTotalMagazines = "Total Magazine using Campaign are:". (int)count($arrResultSet);

            $objPHPExcel = new PHPExcel();

            $objPHPExcel->setActiveSheetIndex(0);
            $objPHPExcel->getActiveSheet()->SetCellValue('B2', 'Details of the Magazine under this Campaign');
            $objPHPExcel->getActiveSheet()->SetCellValue('B4', $strCampaignCode);
            $objPHPExcel->getActiveSheet()->SetCellValue('B5', $strCampaignName);
            $objPHPExcel->getActiveSheet()->SetCellValue('B6', $strTotalMagazines);
            $objPHPExcel->getActiveSheet()->SetCellValue('B9', 'Magazine Code');
            $objPHPExcel->getActiveSheet()->SetCellValue('C9', 'Magazine Name');
            $objPHPExcel->getActiveSheet()->SetCellValue('D9', 'Description');
            $objPHPExcel->getActiveSheet()->SetCellValue('E9', 'No of issues per Year');
            $objPHPExcel->getActiveSheet()->SetCellValue('F9', 'Status');

            $rowNumber = 11;
            foreach($arrResultSet as $cell) {
                $objPHPExcel->getActiveSheet()->setCellValue('B'.$rowNumber,$cell['magazine_code']);
                $objPHPExcel->getActiveSheet()->setCellValue('C'.$rowNumber,$cell['magazine_name']);
                $objPHPExcel->getActiveSheet()->setCellValue('D'.$rowNumber,$cell['magazine_description']);
                $objPHPExcel->getActiveSheet()->setCellValue('E'.$rowNumber,$cell['magazine_year_issues']);
                $objPHPExcel->getActiveSheet()->setCellValue('F'.$rowNumber,$cell['status']);
                $rowNumber++;
            }

            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();
        } else {
            $this->session->set_flashdata('error', 'No Magazine found for this Campaign');
            $strRedirectPath = base_url().'index.php/promotion/promotion_list';
            redirect($strRedirectPath);
        }


    }


    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('promotions');
        $arrResultSet = $this->promotions->fnGetTransactionInfo($intCampaignId);
        if (count($arrResultSet) > 0) {
            $intTotalRevenue = 0;
            $intUnPaidRevenue = 0;
            $intProcessingRevenue = 0;
            $intPaidRevenue = 0;
            foreach($arrResultSet as $data) {
                $intTotalRevenue = $intTotalRevenue + $data['camp_amount'];

                if ($data['payment_done'] == 1) {
                    $intUnPaidRevenue  = $intUnPaidRevenue + $data['camp_amount'];
                }

                if ($data['payment_done'] == 2) {
                    $intProcessingRevenue  = $intProcessingRevenue + $data['camp_amount'];
                }

                if ($data['payment_done'] == 3) {
                    $intPaidRevenue  = $intPaidRevenue + $data['camp_amount'];
                }

            }
            $arrTransactionStatus = array(1 => 'Pending', 2 => 'Processing', 3=> 'Paid');
            if (count($arrResultSet) > 0) {
                $strCampaignCode = "Campaign Code: ".$arrResultSet[0]['campeign_code'];
                $strTotalTransactions = "Total Transactions has been done using this Campaign:". (int)count($arrResultSet);
                $strTotalTransactionsAmount = "Total Revenue by these transactions using this Campaign:". (int)$intTotalRevenue."SGD";
                $strTotalUnpaid = "Total outstanding Amount of transaction:". (int)$intUnPaidRevenue."SGD";
                $strTotalProcessing = "Total Processing Amount of transaction:". (int)$intProcessingRevenue."SGD";
                $strTotalPaid = "Total Paid amount of transaction:". (int)$intPaidRevenue."SGD";

                $objPHPExcel = new PHPExcel();

                $objPHPExcel->setActiveSheetIndex(0);
                $objPHPExcel->getActiveSheet()->SetCellValue('B2', 'Details of the Transaction under this Campaign');
                $objPHPExcel->getActiveSheet()->SetCellValue('B4', $strTotalTransactions);
                $objPHPExcel->getActiveSheet()->SetCellValue('B5', $strTotalTransactionsAmount);
                $objPHPExcel->getActiveSheet()->SetCellValue('B6', $strTotalUnpaid);
                $objPHPExcel->getActiveSheet()->SetCellValue('B7', $strTotalProcessing);
                $objPHPExcel->getActiveSheet()->SetCellValue('B8', $strTotalPaid);
                $objPHPExcel->getActiveSheet()->SetCellValue('B12', 'Magazine Code');
                $objPHPExcel->getActiveSheet()->SetCellValue('C12', 'Subscriber Name');
                $objPHPExcel->getActiveSheet()->SetCellValue('D12', 'Subscriber Email');
                $objPHPExcel->getActiveSheet()->SetCellValue('E12', 'Subscribed for Year(s)');
                $objPHPExcel->getActiveSheet()->SetCellValue('F12', 'Amount');
                $objPHPExcel->getActiveSheet()->SetCellValue('G12', 'Subscription start Date');
                $objPHPExcel->getActiveSheet()->SetCellValue('H12', 'Subscription End Date');
                $objPHPExcel->getActiveSheet()->SetCellValue('I12', 'Start Issue');
                $objPHPExcel->getActiveSheet()->SetCellValue('J12', 'End Issue');
                $objPHPExcel->getActiveSheet()->SetCellValue('K12', 'Payment Status');

                $rowNumber = 14;
                foreach($arrResultSet as $cell) {
                    $objPHPExcel->getActiveSheet()->setCellValue('B'.$rowNumber,$cell['magezine_id']);
                    $objPHPExcel->getActiveSheet()->setCellValue('C'.$rowNumber,$cell['sub_name']);
                    $objPHPExcel->getActiveSheet()->setCellValue('D'.$rowNumber,$cell['email']);
                    $objPHPExcel->getActiveSheet()->setCellValue('E'.$rowNumber,$cell['period']);
                    $objPHPExcel->getActiveSheet()->setCellValue('F'.$rowNumber,$cell['amount']);
                    $objPHPExcel->getActiveSheet()->setCellValue('G'.$rowNumber,date("m-d-Y", strtotime($cell['subscribed_on'])));
                    $objPHPExcel->getActiveSheet()->setCellValue('H'.$rowNumber,date("m-d-Y", strtotime($cell['subscription_end_on'])));
                    $objPHPExcel->getActiveSheet()->setCellValue('I'.$rowNumber,$cell['start_issue']);
                    $objPHPExcel->getActiveSheet()->setCellValue('J'.$rowNumber,$cell['end_issue']);
                    $objPHPExcel->getActiveSheet()->setCellValue('K'.$rowNumber,$arrTransactionStatus[$cell['status']]);
                    $rowNumber++;
                }

                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();
            }
        } else {
            $this->session->set_flashdata('error', 'No Transaction found for this Campaign');
            $strRedirectPath = base_url().'index.php/promotion/promotion_list';
            redirect($strRedirectPath);
        }

    }

    function fnCopyCampaign()
    {
        # 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('promotions');
        #1.  Get all magezines and create an array of magazines.
        $arrCampaignDetails = $this->promotions->fnGetDetails('campaigns', $intCampaignId);

        #2. Now get the all magazines associate with these
        $arrAssociateMagazines = $this->promotions->fnGetDetailsOfTable('campaign_magazine', 'campaign_id', $intCampaignId);
        $arrData['magazines_details'] = $arrAssociateMagazines;
        # Array of all promotions.+
        $arrData['promotion'] = $arrCampaignDetails[0];
        $arrData['promo_id'] = $_REQUEST['id'];
        $arrData['middle']   = 'promotion/add_copy_campaign';
        $strValidationErrors = validation_errors();
        $this->session->set_flashdata('error', $strValidationErrors);
        $this->load->view('admin/templates/template', $arrData);
    }
}

