<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
class Magazine 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 magazines.
	* @author	Himanshu Charegaonkar
	* @access	public
	*/
	public function magazine_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('magezines');
		$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['sel_currency'] !== "") { // If there is payment mode then put the date related condition.
                $strSearchKey = $strSearchKey. " AND currency =".$_GET['sel_currency'];
            }

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

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

            if ($_GET['sel_status'] != "") { // If there is status then put the date related condition.
                $strSearchKey = $strSearchKey. " AND status ='".$_GET['sel_status']."'";
            }
        }
		
		/** Pagination patch start **/
		
		# Call the model for taking count 
		$arrCountArray = $this->magezines->fnGetAllMagazines("", "", $strSearchKey);
        # Functionality of pagination.
        # 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/magazine/magazine_list/';
        $this->backend_pagination->setup_pagination();
        $arrData['pagination']  = $this->backend_pagination->strpagination;

        $arrDetails = $this->magezines->fnGetAllMagazines($this->backend_pagination->limit,$this->backend_pagination->offsetPage, $strSearchKey);

		/** Pagination patch end **/
		
		# Add respcted details from the foreign key value.
		if (count($arrDetails) > 0) {
			for($intCount = 0; $intCount < count($arrDetails); $intCount++) {
				# Get the category Name.
				$arrCategoryName = $this->magezines->fnGetRequestedDetails('category', $arrDetails[$intCount]['category']);
				$arrDetails[$intCount]['category_name'] = $arrCategoryName[0]['name'];
				
				# get the currency Name
				$arrCurrencyName = $this->magezines->fnGetRequestedDetails('currency', $arrDetails[$intCount]['currency']);
				$arrDetails[$intCount]['currency_name'] = $arrCurrencyName[0]['name'];
				
				# get the language name
				$arrLanguageName = $this->magezines->fnGetRequestedDetails('language', $arrDetails[$intCount]['language']);
				$arrDetails[$intCount]['language_name'] = $arrLanguageName[0]['name'];
			}	
		}

        #get the all currencies
        $arrCurrency = $this->magezines->fnGetDetails('currency');
        $arrCategory = $this->magezines->fnGetDetails('category');
        $arrLanguage = $this->magezines->fnGetDetails('language');

		# Add the middle content to the template.
		$arrData['middle'] = 'magezine/magezine';
		$arrData['details'] = $arrDetails;
		$arrData['all_currencies'] = $arrCurrency;
		$arrData['all_categories'] = $arrCategory;
		$arrData['all_languages'] = $arrLanguage;
		$arrData['cust_Pagination'] = $this->pagination->create_links();
        $arrData['arrGetData']   = $_GET;
		$this->load->view('admin/templates/template', $arrData);
	}
	
	/**
	* Function magazine_list
	* Listting of added magezines.
	* @author	Himanshu Charegaonkar
	* @access	public
	*/
	public function add_magezine()
	{
		# 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('magezines');
		
		# set form fields rules.
		$this->load->helper(array('form', 'url'));
		$this->form_validation->set_rules('magezine_id', 'Magezine Id', 'required|is_unique[magazine.magezine_id]|max_length[35]|alpha_numeric|xss_clean');
		$this->form_validation->set_rules('magezine_name', 'Magezine Name', 'required|max_length[30]|xss_clean');
		$this->form_validation->set_rules('magezine_category', 'Magezine Category', 'required');
		$this->form_validation->set_rules('magezine_language', 'Magezine Language', 'required');
		#$this->form_validation->set_rules('magezine_issues', 'Magezine Issues', 'required');
		$this->form_validation->set_rules('magezine_currency', 'Magezine Currency', 'required');
		#$this->form_validation->set_rules('magezine_desc', 'Magezine Desc', 'required|');
		$this->form_validation->set_rules('magezine_status', 'Magezine Status', 'required');
		$this->form_validation->set_rules('magezine_sub_no_years[]', 'No of years subscription', 'required|numeric');
		$this->form_validation->set_rules('magezine_sub_amount[]', 'Subscription Amount', 'required');
		
		# Check whether the validation turns true.
		if ($this->form_validation->run() == TRUE)
		{
			$arrPostedData = $_POST;
			
			# first check whether the no of years are get multiple in the array.
			for($intNum = 0; $intNum<5; $intNum ++)
			{
				$arrCheckvalues = array_count_values($_POST['magezine_sub_no_years']);
				if ($arrCheckvalues[$intNum] > 1) {
					$this->session->set_flashdata('error', 'Please select unique number of year for each subscription package');
					redirect(base_url().'index.php/magazine/add_magezine');
				}
			}
            #get the values of all fields.
            $arrMagezine = array();
			# Check whether the file get uploaded or not.
			if ($_FILES['magezine_image']['name'] != '')
			{
				# Set the file upload configuration.
				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'] = 'png|jpeg|jpg';
       			$config['max_size']	= '2000';	
				$this->load->library('upload', $config);
				
				# Check whther the uploaded file does have any errors.
				if (! $this->upload->do_upload('magezine_image'))
				{
					# if found redirect to the form.
					$this->session->set_flashdata('error', $this->upload->display_errors());
					redirect(base_url().'index.php/magazine/add_magezine');
				} else {
					$data = array('upload_data' => $this->upload->data());
					$strUploadedFileName = $data['upload_data']['file_name'];
                    $arrMagezine['magazine_image'] = $strUploadedFileName;
				}
            } /*else {
				
				# If image dosent uploaded, redirect with the error
				$this->session->set_flashdata('error', 'Please upload a Image');
				redirect(base_url().'index.php/magazine/add_magezine');
			} */
            #get the values of all fields.
            $arrMagezine['magezine_id'] = $_POST['magezine_id'];
            $arrMagezine['name'] = $_POST['magezine_name'];
            $arrMagezine['category'] = $_POST['magezine_category'];
            $arrMagezine['language'] = $_POST['magezine_language'];
            #$arrMagezine['issues_per_year'] = $_POST['magezine_issues'];
            $arrMagezine['issues_per_year'] = null;
            $arrMagezine['currency'] = $_POST['magezine_currency'];
            $arrMagezine['description'] = $_POST['magezine_desc'];
            $arrMagezine['promotional_package'] = $_POST['magezine_promo'];
            $arrMagezine['status'] = $_POST['magezine_status'];
            $arrMagezine['magazine_image'] = $strUploadedFileName;
            $arrMagezine['created_on'] = date("Y-m-d H:i:s");
            $arrMagezine['created_by'] = 1;
            $arrMagezine['months'] = implode(',', $_POST['months']);
            $intMagezineId = $this->magezines->fnSaveMagezine('magazine', $arrMagezine);

            # Now insert the second part which is insert the magezines amout and years.
            $arrMagezineyearsAndAmout = array();
            $arrMagezineyearsAndAmout['magazine_id'] = $intMagezineId;

            # get the array of selected years.
            $arrSelectedYears = $_POST['magezine_sub_no_years'];
            $arrAmountForYears = $_POST['magezine_sub_amount'];

            # insert the respective entries into the database.
            for ($intCount = 0; $intCount<count($arrSelectedYears); $intCount++) {
                $arrMagezineyearsAndAmout['magazine_id'] = $intMagezineId;
                $arrMagezineyearsAndAmout['subscribe_no_years'] = $arrSelectedYears[$intCount];
                $arrMagezineyearsAndAmout['amount'] = $arrAmountForYears[$intCount];

                #insert this into the database.
                $this->magezines->fnSaveMagezineAmount('magazine_subscription_amount', $arrMagezineyearsAndAmout);
            }
            $this->session->set_flashdata('success', 'New magezine has been added successfuly');
            redirect(base_url().'index.php/magazine/magazine_list');
		} else {
			
			/** if validation errros found then redirect  **/
			$strValidationErrors = validation_errors();
			if ($strValidationErrors != "" ) {
				$this->session->set_flashdata('error', $strValidationErrors);
				$strRedirectpath = base_url().'index.php/magazine/add_magezine';
				redirect($strRedirectpath);
			} else {
				# get the all currencies.
				$arrAvailableCurrency = $this->magezines->fnGetDetails('currency');
				# get the all category.
				$arrAvailableCategory = $this->magezines->fnGetDetails('category');
				# Get all Lanugaes.
				$arrAvailableLanguages = $this->magezines->fnGetDetails('language');
				# Get all promotion.
				#$arrAvailablePromotion = $this->magezines->fnGetAvailablePromotion();
				$arrData['currency'] = $arrAvailableCurrency;
				$arrData['category'] = $arrAvailableCategory;
				$arrData['language'] = $arrAvailableLanguages;
				#$arrData['promotion'] = $arrAvailablePromotion;
				$arrData['middle']   = 'magezine/add_magezine';
				$strValidationErrors = validation_errors();
				$this->session->set_flashdata('error', $strValidationErrors);
				echo $this->load->view('magezine/add_magezine', $arrData, true);
			}
		}
	}
	
	
	/**
	 * Function edit_magezine
	 * Function to edit magazine.
	 * Listting of added magazines.
	 * @author	Himanshu Charegaonkar
	 * @access	public
	 */
	function fnCheckMagazineIssueDelete(){
		# Load the required model.
		$this->load->model('magezines');
		$magazine_issue_ = trim($this->input->post('magazine_issue_'));
		$this->magezines->fnDeleteMagazineMonthlyIssue2($magazine_issue_);
		echo 1;
	}	

	public function edit_magezine()
	{
		# 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. 
		$intReceMagezineId = (int) base64_decode($_REQUEST['magezine_id']);
		if ($intReceMagezineId == 0) {
			$strRedirectpath = base_url().'index.php/magazine/magazine_list';
            redirect($strRedirectpath);
		}
		# Load the required model.
		$this->load->model('magezines');
		# get the details about the requested magezine.
		$arrCountArray = $this->magezines->fnGetDetails('magazine', $intReceMagezineId);

        # lets check whether the magazine has been subscribe any subscriber.
        $this->load->model('subscribers');
        $arrCheckMagazineSubscription = $this->subscribers->fnGetAllDetails('subscribe_magazine', 'magazine_id', $intReceMagezineId);

		
		# set form fields rules.
		$this->load->helper(array('form', 'url'));
		if ($_POST['magezine_code'] == $arrCountArray[0]['magezine_id']) {
			$this->form_validation->set_rules('magezine_code', 'Magezine Id', 'required|max_length[35]|alpha_numeric|xss_clean');
		} else {
			$this->form_validation->set_rules('magezine_code', 'Magezine Id', 'required|is_unique[magazine.magezine_id]|max_length[35]|alpha_numeric|xss_clean');
		}
		$this->form_validation->set_rules('magezine_name', 'Magezine Name', 'required|max_length[30]|xss_clean');
		$this->form_validation->set_rules('magezine_category', 'Magezine Category', 'required');
		$this->form_validation->set_rules('magezine_language', 'Magezine Language', 'required');
		#$this->form_validation->set_rules('magezine_issues', 'Magezine Issues', 'required');
		$this->form_validation->set_rules('magezine_currency', 'Magezine Currency', 'required');
		#$this->form_validation->set_rules('magezine_desc', 'Magezine Desc', 'required|');
		$this->form_validation->set_rules('magezine_status', 'Magezine Status', 'required');
		$this->form_validation->set_rules('magezine_sub_no_years[]', 'No of years subscription', 'required|numeric');
		$this->form_validation->set_rules('magezine_sub_amount[]', 'Subscription Amount', 'required');
		$arrMagezine = array();
		# Check whether the validation turns true.
		if ($this->form_validation->run() == TRUE)
		{
			$arrPostedData = $_POST;
			
			# first check whether the no of years are get multiple in the array.
			for($intNum = 0; $intNum<5; $intNum ++)
			{
				$arrCheckvalues = array_count_values($_POST['magezine_sub_no_years']);
				if ($arrCheckvalues[$intNum] > 1) {
					$this->session->set_flashdata('error', 'Please select unique number of year for each subscription package');
					redirect(base_url().'index.php/magazine/edit_magezine/?magezine_id='.$_REQUEST['magezine_id']);
				}
			}
			
			# Check whether the file get uploaded or not.
			if ($_FILES['magezine_image']['name'] != '')
			{
				# Set the file upload configuration.
				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'] = 'png|jpeg|jpg';
				$config['max_size']	= '2000';
				$this->load->library('upload', $config);

				# Check whther the uploaded file does have any errors.
				if (! $this->upload->do_upload('magezine_image'))
				{
					# if found redirect to the form.
					$this->session->set_flashdata('error', $this->upload->display_errors());
					redirect(base_url().'index.php/magazine/edit_magezine/?magezine_id='.$_REQUEST['magezine_id']);
				} else {
					
					$data = array('upload_data' => $this->upload->data());
					$strUploadedFileName = $data['upload_data']['file_name'];
					$arrMagezine['magazine_image'] = $strUploadedFileName;
				}
			}			
					
			#get the values of all fields.
			$arrMagezine['magezine_id'] = $_POST['magezine_code'];
			$arrMagezine['name'] = $_POST['magezine_name'];
			$arrMagezine['category'] = $_POST['magezine_category'];
			$arrMagezine['language'] = $_POST['magezine_language'];
			#$arrMagezine['issues_per_year'] = $_POST['magezine_issues'];
			$arrMagezine['issues_per_year'] = null;
			$arrMagezine['currency'] = $_POST['magezine_currency'];
			$arrMagezine['description'] = $_POST['magezine_desc'];
			$arrMagezine['promotional_package'] = $_POST['magezine_promo'];
			$arrMagezine['status'] = $_POST['magezine_status'];
			$arrMagezine['created_on'] = date("Y-m-d H:i:s");
			$arrMagezine['created_by'] = 1;
			$arrMagezine['months'] = implode(',', $_POST['months']);
			$this->magezines->fnUpdateMagezine($arrMagezine, $intReceMagezineId);
			
			# first delete the previous amount of the subscription.
			$this->magezines->fnDeleteMagezineSub($intReceMagezineId);
				
			# Now insert the second part which is insert the magezines amout and years.
			$arrMagazineMonthlyIssue = array();

			# get the array of selected years.
			$arrSelectedYears = $_POST['magezine_sub_no_years'];
			$arrAmountForYears = $_POST['magezine_sub_amount'];
			$magezine_issue_ids = $_POST['magezine_issue_ids'];

			foreach ($arrSelectedYears as $intCount => $arrSelectedYears_value) {
            	 if($magezine_issue_ids[$intCount] != ''){
            		$arrMagazineMonthlyIssue['id'] 			= $magezine_issue_ids[$intCount];
            		$arrMagazineMonthlyIssue['magazine_id'] = $intReceMagezineId;
					$arrMagazineMonthlyIssue['subscribe_no_years'] = $arrSelectedYears_value;
					$arrMagazineMonthlyIssue['amount'] 			   = $arrAmountForYears[$intCount];
	                $this->magezines->fnSaveMagezineAmount('magazine_subscription_amount', $arrMagazineMonthlyIssue);
            	}else{
            		$arrMagazineMonthlyIssue2 					= array();
            		$arrMagazineMonthlyIssue2['magazine_id'] 	= $intReceMagezineId;
					$arrMagazineMonthlyIssue2['subscribe_no_years'] = $arrSelectedYears_value;
					$arrMagazineMonthlyIssue2['amount'] 			= $arrAmountForYears[$intCount];
    				$this->magezines->fnSaveMagezineAmount('magazine_subscription_amount', $arrMagazineMonthlyIssue2);
            	}
            }

			/*# insert the respective entries into the database.
			for ($intCount = 0; $intCount<count($arrSelectedYears); $intCount++) {
				$arrMagezineyearsAndAmout['magazine_id'] = $intReceMagezineId;
				$arrMagezineyearsAndAmout['subscribe_no_years'] = $arrSelectedYears[$intCount];
				$arrMagezineyearsAndAmout['amount'] = $arrAmountForYears[$intCount];
	
				#insert this into the database.
				$this->magezines->fnSaveMagezineAmount('magazine_subscription_amount', $arrMagezineyearsAndAmout);
			}*/
			
			# After success redirect with success message.
			$this->session->set_flashdata('success', 'Magezine has been updated successfuly');
			redirect(base_url().'index.php/magazine/magazine_list');
			 
		} else {
						
			/** if validation errors found then redirect  **/
			$strValidationErrors = validation_errors();
			if ($strValidationErrors != "" ) {
				$this->session->set_flashdata('error', $strValidationErrors);
				$strRedirectpath = base_url().'index.php/magazine/edit_magezine/?magezine_id='.$_REQUEST['magezine_id'];
				redirect($strRedirectpath);
			} else {

                # get the associate subscription details of the magezine.
				$arrSubscription = $this->magezines->fnGetMagezinesSubscription($intReceMagezineId);
				$arrAvailableCurrency = $this->magezines->fnGetDetails('currency');
				$arrAvailableCategory = $this->magezines->fnGetDetails('category');
				$arrAvailableLanguages = $this->magezines->fnGetDetails('language');
				#$arrAvailablePromotion = $this->magezines->fnGetDetails('promotion');
				$arrData['currency'] = $arrAvailableCurrency;
				$arrData['category'] = $arrAvailableCategory;
				$arrData['language'] = $arrAvailableLanguages;
				$arrData['magezine_details'] = $arrCountArray[0];
				$arrData['previousMagId'] = $_REQUEST['magezine_id'];
				$arrData['arrSubscription'] = $arrSubscription;
                $arrData['is_subscribed'] = count($arrCheckMagazineSubscription);
				#$arrData['promotion'] = $arrAvailablePromotion;
				$arrData['middle']   = 'magezine/edit_magezine';
				$strValidationErrors = validation_errors();
				$this->session->set_flashdata('error', $strValidationErrors);
				echo $this->load->view('magezine/edit_magezine', $arrData, true);
			}
		}
	}
	
	/**
	 * Function preview
	 * Function to give preview of the requested magazine.
	 * @author	Himanshu Charegaonkar
	 * @access	public
	 */
	public function preview()
	{
		# 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. 
		$intReceMagezineId = (int) base64_decode($_GET['magezine_id']);
		if ($intReceMagezineId == 0) {
			$strRedirectpath = base_url().'index.php/magazine/magazine_list';
            redirect($strRedirectpath);
		}
		
		# Load the required model.
		$this->load->model('magezines');
		# get the details about the requested magezine.
		$arrCountArray = $this->magezines->fnGetDetails('magazine', $intReceMagezineId);
		
		# Add respected details from the foreign key value.
		if (count($arrCountArray) > 0) {
			for($intCount = 0; $intCount < count($arrCountArray); $intCount++) {
				# Get the category Name.
				$arrCategoryName = $this->magezines->fnGetRequestedDetails('category', $arrCountArray[$intCount]['category']);
				$arrCountArray[$intCount]['category_name'] = $arrCategoryName[0]['name'];
				
				# get the currency Name
				$arrCurrencyName = $this->magezines->fnGetRequestedDetails('currency', $arrCountArray[$intCount]['currency']);
				$arrCountArray[$intCount]['currency_name'] = $arrCurrencyName[0]['name'];
				
				# get the language name
				$arrLanguageName = $this->magezines->fnGetRequestedDetails('language', $arrCountArray[$intCount]['language']);
				$arrCountArray[$intCount]['language_name'] = $arrLanguageName[0]['name'];
			}	
		}
		
		# Get the subscription details.
		$arrSubscription = $this->magezines->fnGetMagezinesSubscription($intReceMagezineId);
		$arrData['middle']   = 'magezine/preview';
		$arrData['magezine_details'] = $arrCountArray[0];
		$arrData['arrSubscription'] = $arrSubscription;
		$this->load->view('admin/templates/template', $arrData);
	}

    /**
     * Function get_all_magazines
     *  Function to get all magazines with requested term.
     */
    function get_all_magazines()
    {
        # Load the required model.
        $this->load->model('magezines');
        $term = $_GET["term"];
        $strEmail = $_GET['var_name'];
        $arrCountArray = $this->magezines->fnGetAllMagazinesForList($strEmail , $term);
        $this->load->model('subscribers');

        # If the array returns with the records then create a json response and send it to the caller function.
        if (count($arrCountArray) > 0 ) {
            foreach($arrCountArray as $details) {
                $json[]=array(
                        'value'=> $details['magezine_id'],
                        'label'=> $details['magezine_id'],
                    );


            }

            echo json_encode($json);
        } else {

            # If no result found the  return with null value and label
            $json[]=array(
                'value'=> "",
                'label'=> "No match found",
            );
            echo json_encode($json);
        }

    }

    /**
     * Function fnCheckMagazineDetails
     * Function to check the given magazine details
     * @author	Himanshu Charegaonkar
     * @access	public
     */
    function fnCheckMagazineDetails()
    {
        $strMagazineId = $_GET['magazine_id'];
        # Load the required model.
        $this->load->model('magezines');

        # delete requested subscription
        $arrResultSet = $this->magezines->fnCheckMagazineCode($strMagazineId);
        echo count($arrResultSet);
    }
}

