<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
class Campaign 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 add_campaign
	* Function to add the campaign for the magazines and the promotions
	* @author	Himanshu Charegaonkar
	* @access	public
	*/
	public function add_campaign()
	{
		# 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('campaign_name', 'Campaign Name', 'required|is_unique[campaigns.name]|max_length[100]|alpha_numeric|xss_clean');
		$this->form_validation->set_rules('campaign_desc', 'Campaign Description', 'required');
        $this->form_validation->set_rules('campaign_loc', 'Campaign location', 'required|max_length[100]|alpha_numeric|xss_clean');

		# Check whether the validation turns true.
		if ($this->form_validation->run() == TRUE)
		{
			$arrPostedData = $_POST;
			
			#get the values of all fields.
			$arrCampaign = array();
            $arrCampaign['name'] = $_POST['campaign_name'];
            $arrCampaign['description'] = $_POST['campaign_desc'];
            $arrCampaign['location'] = $_POST['campaign_loc'];

			# Save to the database.
			$intNewPromotionId = $this->promotions->fnSaveData('campaigns', $arrCampaign);
			
			$this->session->set_flashdata('success', 'New Campaign has been added successfully');
			redirect(base_url().'index.php/campaign/add_campaign');
		} else {
			
			/** if validation errros found then redirect  **/
			$strValidationErrors = validation_errors();
			if ($strValidationErrors != "" ) {
				$this->session->set_flashdata('error', $strValidationErrors);
				$strRedirectPath = base_url().'index.php/campaign/add_campaign/';
				redirect($strRedirectPath);
			} else {
				$arrData['middle']   = 'campaign/add_campaign';
				$strValidationErrors = validation_errors();
				$this->session->set_flashdata('error', $strValidationErrors);
				$this->load->view('admin/templates/template', $arrData);
			}
		}
	}
	
	/**
	 * Function edit promotion
	 * Listting of added magazines.
	 * @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($_GET['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('promotion', $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', 'required|max_length[100]|alpha_numeric|xss_clean');
		$this->form_validation->set_rules('desc', 'Description', 'required');
		$this->form_validation->set_rules('discount', 'Discount Type', 'required');
		$this->form_validation->set_rules('discount_amount', 'Discount Amount', 'required');
		$this->form_validation->set_rules('product[]', 'Magezines', 'required');
		$this->form_validation->set_rules('start_date', 'Start Date', 'required');
		$this->form_validation->set_rules('end_date', 'End Date', 'required');
		
		# Check whether the validation turns true.
		if ($this->form_validation->run() == TRUE)
		{
			$arrPostedData = $_POST;
			
			#get the values of all fields.
			$arrMagezine = array();
			$arrMagezine['promo_code'] = $_POST['promo_code'];
			$arrMagezine['description'] = $_POST['desc'];
			$arrMagezine['discount_type'] = $_POST['discount'];
			$arrMagezine['discount_amount'] = $_POST['discount_amount'];
			$arrMagezine['start_date'] = date("Y-m-d", strtotime($arrPostedData['start_date']));
			$arrMagezine['end_date'] = date("Y-m-d", strtotime($arrPostedData['end_date']));
			$arrMagezine['promo_name'] = $_POST['promo_name'];
			
			# Update to the database.
			$this->promotions->fnUpdatePromotion($arrMagezine, $intRecPromoId);
			
			# Now insert the second part which is insert the magezines amout and years.
			$arrMagezineyearsAndAmout = array(); 
			
			# first delete the previous amount of the subscription.
			$this->promotions->fnDeleteMagezinePromotion($intRecPromoId);
			
			# get the array of selected years.
			$arrSelectedProducts = $_POST['product'];
			
			# insert the respective entries into the database.
			for ($intCount = 0; $intCount<count($arrSelectedProducts); $intCount++) {
				$arrMagezineyearsAndAmout['promotion_id'] = $intRecPromoId;
				$arrMagezineyearsAndAmout['magazine_id'] = $arrSelectedProducts[$intCount];
				
				#insert this into the database.
				$this->promotions->fnSaveMagezinePromotion('magazine_promotion', $arrMagezineyearsAndAmout);
			}
			
			# 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 {
				# Get all magezines.
				$arrAvailablemagezine = $this->promotions->fnGetLiveMagezines();
				# Get all magezine and its associate promotions.
				$arrMagezinePromotion = $this->promotions->fnGetPromotionSubscription($intRecPromoId);

				# arrange the Array of magezine promotion array with structure of magezine id as key and details as value.
				$arrAvailableMagPromo = array();
				if (count($arrMagezinePromotion > 0)) {
					foreach($arrMagezinePromotion as $value) {
						$arrAvailableMagPromo[$value['magazine_id']] = $value;
					}
			    } 
			    # array of all available magezines. 
				$arrData['magezine'] = $arrAvailablemagezine;
				# Array of all promotions.
				$arrData['promotion'] = $arrCountArray[0];
				# Array of all magezines promotions.
				$arrData['magazine_promotion'] = $arrMagezinePromotion[0];
				# Array of magezine promotion array with structure of magezine id as key and details as value.
				$arrData['mage_promo'] = $arrAvailableMagPromo;
				$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);
    }
}

