<?php

class Category extends Admin_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->model(array('category/category_model'));
    $this->load->helper('category/category');
    $this->config->set_item('menu_highlight', 'product management');
    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");
    $this->default_view = 'catalog';
    $this->deletePrvg = TRUE;
  }

  public function index() {
    $pagesize = (int) $this->input->get_post('pagesize');
    $config['limit'] = ( $pagesize > 0 ) ? $pagesize : $this->config->item('pagesize');
    $offset = ( $this->input->get_post('per_page') > 0 ) ? $this->input->get_post('per_page') : 0;
    $base_url = current_url_query_string(array('filter' => 'result'), array('per_page'));
    $parent_id = (int) $this->uri->segment(4, 0);

    $keyword = trim($this->input->get_post('keyword', TRUE));
    $keyword = $this->db->escape_str($keyword);
    $condtion = "AND parent_id = '$parent_id'";
    $condtion_array = array(
        'field' => "*,( SELECT COUNT(category_id) FROM wps_categories AS b WHERE b.parent_id=a.category_id ) AS total_subcategories",
        'condition' => $condtion,
        //'limit' => $config['limit'],
        //'offset' => $offset,
        'debug' => FALSE
    );

    $res_array = $this->category_model->getcategory($condtion_array);
    $config['total_rows'] = $this->category_model->total_rec_found;
    $data['page_links'] = admin_pagination($base_url, $config['total_rows'], $config['limit'], $offset);
    $data['heading_title'] = ( $parent_id > 0 ) ? 'Subcategory' : 'Category';
    $data['res'] = $res_array;
    $data['parent_id'] = $parent_id;

    if ($this->input->get_post('set_home_category')) {
      $this->db->query("UPDATE wps_categories SET home_menu = '1' WHERE category_id = '" . $this->input->get_post('set_home_category') . "'");
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', 'Select Category has been set as home menu.');
      redirect($_SERVER['HTTP_REFERER']);
    }
    if ($this->input->get_post('unset_home_category')) {
      $this->db->query("UPDATE wps_categories SET home_menu = '0' WHERE category_id = '" . $this->input->get_post('unset_home_category') . "'");
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', 'Select Category has been removed from home menu.');
      redirect($_SERVER['HTTP_REFERER']);
    }

    if ($this->input->post('status_action') != '') {
      if ($this->input->post('status_action') == 'Delete') {
        $prod_id = $this->input->post('arr_ids');
        $this->session->set_flashdata('delete_cat', 'Category Has been deleted Successfully!');

        foreach ($prod_id as $v) {
          $where = array('entity_type' => 'category/index', 'entity_id' => $v);
          $this->category_model->safe_delete('wps_meta_tags', $where, TRUE);
        }
      }
      $this->update_status('wps_categories', 'category_id');
    }
    if ($this->input->post('update_order') != '') {
      $this->update_displayOrder('wps_categories', 'sort_order', 'category_id');
    }

    /* category set as a */

    if ($this->input->post('set_as') != '') {
      $set_as = $this->input->post('set_as', TRUE);
      $this->set_as('wps_categories', 'category_id', array($set_as => '1'));
    }

    if ($this->input->post('unset_as') != '') {
      $unset_as = $this->input->post('unset_as', TRUE);
      $this->set_as('wps_categories', 'category_id', array($unset_as => '0'));
    }
    /* End category set as a */

    $this->load->view($this->default_view . '/view_category_list', $data);
  }

  public function add() {
    $data['ckeditor'] = set_ck_config(array('textarea_id' => 'cat_desc'));
    $parent_id = (int) $this->uri->segment(4, 0);
    $img_allow_size = $this->config->item('allow.file.size');
    $img_allow_dim = $this->config->item('allow.imgage.dimension');
    $category_name = $this->db->escape_str($this->input->post('category_name'));
    $posted_friendly_url = $this->input->post('friendly_url');

    if ($parent_id != '' && $parent_id > 0) {
      $parent_id = applyFilter('NUMERIC_GT_ZERO', $parent_id);
      $data['heading_title'] = 'Add Subcategory';
      if ($parent_id <= 0) {
        redirect("sitepanel/category");
      }
      $parentdata = $this->category_model->get_category_by_id($parent_id);
      if (!is_array($parentdata)) {
        $this->session->set_flashdata('message', lang('invalidRecord'));
        redirect('sitepanel/category', '');
      }
      $this->cbk_friendly_url = seo_url_title($posted_friendly_url);
      $data['parentData'] = $parentdata;
    } else {
      $this->cbk_friendly_url = seo_url_title($posted_friendly_url);
      $data['parentData'] = '';
      $data['heading_title'] = 'Add Category';
    }

    $seo_url_length = $this->config->item('seo_url_length');

    $this->form_validation->set_rules('category_name', 'Category Name', "trim|required|max_length[100]|xss_clean|unique[wps_categories.category_name ='" . $category_name . "' AND status!='2' AND parent_id='" . $parent_id . "']");
    $this->form_validation->set_rules('friendly_url', 'Page URL', "trim|required|max_length[$seo_url_length]|xss_clean|unique[wps_meta_tags.page_url ='" . $this->cbk_friendly_url . "'] ");
    $this->form_validation->set_rules('category_image', 'Image', "file_allowed_type[image]|file_size_max[$img_allow_size]|check_dimension[$img_allow_dim]");
    $this->form_validation->set_rules('category_description', 'Description', "max_length[6000]");
    $this->form_validation->set_rules('category_alt', 'Alt', "trim|max_length[100]");

    if ($this->form_validation->run() === TRUE) {
      $uploaded_icon = $uploaded_file = "";
      if (!empty($_FILES) && $_FILES['category_image']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('category_image', 'category');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $uploaded_file = $uploaded_data['upload_data']['file_name'];
        }
      }
      
      
      if (!empty($_FILES) && $_FILES['category_icon']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('category_icon', 'category');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $uploaded_icon = $uploaded_data['upload_data']['file_name'];
        }
      }
      
      $redirect_url = "category/index";
      $category_alt = $this->input->post('category_alt');
      if ($category_alt == '') {
        $category_alt = $this->input->post('category_name');
      }
      $category_description = $this->input->post('category_description');
      $category_description = $category_description != '' ? $category_description : null;
      if (!is_null($category_description)) {
        $meta_description = $category_description;
        $meta_keyword = $category_description;
      } else {
        $meta_description = $this->input->post('category_name');
        $meta_keyword = $this->input->post('category_name');
      }

      $posted_data = array(
          'category_name' => $this->input->post('category_name'),
          'category_alt' => $category_alt,
          'category_description' => $category_description,
          'coupon_code' => $this->input->post('coupon_code'),
          'coupon_value' => $this->input->post('coupon_value'),
          'parent_id' => $parent_id,
          'friendly_url' => $this->cbk_friendly_url,
          'date_added' => $this->config->item('config.date.time'),
          'category_image' => $uploaded_file,
          'category_icon' => $uploaded_icon,
          'catType'=>$this->input->post('catType'),
      );
      $insertId = $this->category_model->safe_insert('wps_categories', $posted_data, FALSE);
      if ($insertId > 0) {
        if ($this->input->get_post('meta_title') != '' && $this->input->get_post('meta_description') != '') {
          $title = get_text($this->input->get_post('meta_title'));
          $description = get_text($this->input->get_post('meta_description'));
          $keywords = get_keywords($this->input->get_post('meta_keyword'));
        } else {
          $title = '';
          $description = '';
          $keywords = '';
        }
        $meta_array = array(
            'entity_type' => $redirect_url,
            'entity_id' => $insertId,
            'page_url' => $this->cbk_friendly_url,
            'meta_title' => $title,
            'meta_description' => $description,
            'meta_keyword' => $keywords
        );
        create_meta($meta_array);
      }


      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', lang('success'));
      $redirect_path = isset($parentdata) && is_array($parentdata) ? 'category/index/' . $parentdata['category_id'] : 'category';
      redirect('sitepanel/' . $redirect_path, '');
    }
    $data['parent_id'] = $parent_id;
    $this->load->view($this->default_view . '/view_category_add', $data);
  }

  public function edit() {


    $catId = (int) $this->uri->segment(4);
    $rowdata = $this->category_model->get_category_by_id($catId);
    $data['heading_title'] = ($rowdata['parent_id'] > 0 ) ? 'Subcategory' : 'Category';
    $img_allow_size = $this->config->item('allow.file.size');
    $img_allow_dim = $this->config->item('allow.imgage.dimension');
    if (!is_array($rowdata)) {
      $this->session->set_flashdata('message', lang('idmissing'));
      redirect('sitepanel/category', '');
    }
    $data['ckeditor'] = set_ck_config(array('textarea_id' => 'category_description'));
    $posted_friendly_url = $this->input->post('friendly_url');
    $this->cbk_friendly_url = seo_url_title($posted_friendly_url);
    $categoryId = $rowdata['category_id'];
    $seo_url_length = $this->config->item('seo_url_length');

    //Meta Details - Main
    $metaDets = get_db_single_row("wps_meta_tags", "meta_title, meta_description, meta_keyword", "entity_type = 'category/index' AND entity_id = '" . $categoryId . "'");

    $this->form_validation->set_rules('category_name', 'Category Name', "trim|required|max_length[100]|xss_clean|unique[wps_categories.category_name ='" . $this->db->escape_str($this->input->post('category_name')) . "' AND status!='2' AND parent_id='" . $rowdata['parent_id'] . "' AND category_id!='" . $categoryId . "']");

    $this->form_validation->set_rules('friendly_url', 'Page URL', "trim|required|max_length[$seo_url_length]|xss_clean|unique[wps_meta_tags.page_url ='" . $this->cbk_friendly_url . "' AND entity_id!='" . $categoryId . "'] ");

    $this->form_validation->set_rules('category_description', 'Description', "max_length[6000]");
    $this->form_validation->set_rules('category_image', 'Image', "file_allowed_type[image]|file_size_max[$img_allow_size]|check_dimension[$img_allow_dim]");
    if ($this->form_validation->run() == TRUE) {
      
      $uploaded_file = $rowdata['category_image'];
      $unlink_image = array('source_dir' => "category", 'source_file' => $rowdata['category_image']);
      if ($this->input->post('cat_img_delete') === 'Y') {
        removeImage($unlink_image);
        $uploaded_file = NULL;
      }
      if (!empty($_FILES) && $_FILES['category_image']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('category_image', 'category');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $uploaded_file = $uploaded_data['upload_data']['file_name'];
          removeImage($unlink_image);
        }
      }
      
      $uploaded_icon = $rowdata['category_icon'];
      $unlink_icon = array('source_dir' => "category", 'source_file' => $rowdata['category_icon']);
      if (!empty($_FILES) && $_FILES['category_icon']['name'] != '') {
        $this->load->library('upload');
        $uploaded_data = $this->upload->my_upload('category_icon', 'category');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $uploaded_icon = $uploaded_data['upload_data']['file_name'];
          removeImage($unlink_icon);
        }
      }
      $category_alt = $this->input->post('category_alt');
      if ($category_alt == '') {
        $category_alt = $this->input->post('category_name');
      }

      $category_description = $this->input->post('category_description');
      $category_description = $category_description != '' ? $category_description : null;

      $posted_data = array(
          'category_name' => $this->input->post('category_name'),
          'friendly_url' => $this->cbk_friendly_url,
          'category_alt' => $category_alt,
          'coupon_code' => $this->input->post('coupon_code'),
          'coupon_value' => $this->input->post('coupon_value'),
          'category_description' => $category_description,
          'category_image' => $uploaded_file,
          'category_icon' => $uploaded_icon,
          'catType'=>$this->input->post('catType'),
      );

      $where = "category_id = '" . $categoryId . "'";
      $this->category_model->safe_update('wps_categories', $posted_data, $where, FALSE);
      update_meta_page_url('category/index', $categoryId, $this->cbk_friendly_url);
      //Update Meta
      if ($this->input->get_post('meta_title') != '' && $this->input->get_post('meta_description') != '') {
        $title = get_text($this->input->get_post('meta_title'));
        $description = get_text($this->input->get_post('meta_description'));
        $keywords = $this->input->get_post('meta_keyword');
      } else {
        /*$title = $metaDets['meta_title'];
        $description = $metaDets['meta_description'];
        $keywords = $metaDets['meta_keyword'];*/
        
        $title = '';
        $description = '';
        $keywords = '';
      }
      $posted_data_meta = array(
          'meta_title' => $title,
          'meta_description' => $description,
          'meta_keyword' => $keywords,
      );
      $where_meta = "entity_type = 'category/index' AND entity_id = '" . $categoryId . "'";
      $this->category_model->safe_update('wps_meta_tags', $posted_data_meta, $where_meta, FALSE);
      //End here

      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', lang('successupdate'));
      $redirect_path = $rowdata['parent_id'] > 0 ? 'category/index/' . $rowdata['parent_id'] : 'category';
      redirect('sitepanel/' . $redirect_path . '/' . query_string(), '');
    }

    $data['metaDets'] = $metaDets;
    $data['catresult'] = $rowdata;
    $this->load->view($this->default_view . '/view_category_edit', $data);
  }

  public function delete() {
    $catId = (int) $this->uri->segment(4, 0);
    $rowdata = $this->category_model->get_category_by_id($catId);

    if (!is_array($rowdata)) {
      $this->session->set_flashdata('message', lang('idmissing'));
      redirect('sitepanel/category', '');
    } else {
      $total_category = count_category("AND parent_id='$catId' ");
      $total_product = count_products("AND category_id='$catId' ");

      if ($total_category > 0 || $total_product > 0) {
        $this->session->set_userdata(array('msg_type' => 'error'));
        $this->session->set_flashdata('error', lang('child_to_delete'));
      } else {
        $where = array('category_id' => $catId);
        $this->category_model->safe_delete('wps_categories', $where, TRUE);
        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', lang('deleted'));
      }
      redirect($_SERVER['HTTP_REFERER'], '');
    }
  }

  
  public function update_temp_title() {
    $res = $this->db->query("SELECT id, name FROM wps_countries_list WHERE 1")->result_array();
    foreach($res as $city){
      //$this->db->query("UPDATE wps_countries_list SET country_temp_name = '". seo_url_title($city['name'])."' WHERE id = '".$city['id']."'");
      //$this->db->query("INSERT INTO wps_meta_tags SET is_fixed = 'L', entity_type = 'category', entity_id = '".$city['id']."', page_url = '".seo_url_title($city['name'])."',  meta_title = '". $city['name']."',  meta_description = '". $city['name']."',  meta_keyword = '". $city['name']."'");
    }
    
  }

    public function get_parents($parent_id=0)
    { 
        $this->db->where('parent_id', $parent_id);
        $result = $this->db->get('wps_categories')->result_array();
        //print_r($result); exit();
        $temp_array = array();
        foreach ($result as $row){
          if($row['parent_id']==$parent_id)
            {
                $row['subs'] = $this->get_parents($row['category_id']);
                $temp_array[] = $row;
            }
           /* $i = 0;
            if ($i == 0){ echo '<ul>';}
            echo '<li>' .$row['category_name'];
            $this->get_parents($row['category_id']);
            echo '</li>';
            $i++;
            if ($i > 0){ echo '</ul>';} */

        }
        return $temp_array;
        //echo '<pre>';
        //print_r($temp_array);
       
    }


  public function download_category_list() {
    //load our new PHPExcel library
    $this->load->library('pexcel');
    //activate worksheet number 1
		$this->pexcel->setActiveSheetIndex(0);
		//name the worksheet
		$this->pexcel->getActiveSheet()->setTitle('Category list');

		// load database
		$this->load->database();

		// load model
		$this->load->model('category/category_model');

		// get all categories in array formate
    //$condtion = "AND parent_id = '$parent_id'";
    $condtion = "AND parent_id = '0'";

    //$condtion = "";

    $condtion_array = array(
        'field' => "*,( SELECT COUNT(category_id) FROM wps_categories AS b WHERE b.parent_id=a.category_id ) AS total_subcategories",
        'condition' => $condtion,
        //'limit' => $config['limit'],
        //'offset' => $offset,
        'debug' => FALSE
    );

    $res_array = $this->category_model->getcategory($condtion_array);

    //$config['total_rows'] = $this->category_model->total_rec_found;
    // Trying to set a column name
    $this->pexcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
    $this->pexcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
    $this->pexcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
    $this->pexcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
    $this->pexcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
    
    $this->pexcel->getActiveSheet()->SetCellValue('A1', 'Category Id');
    $this->pexcel->getActiveSheet()->SetCellValue('B1', 'Category Name');
    $this->pexcel->getActiveSheet()->SetCellValue('C1', 'Subcategory Id');
    $this->pexcel->getActiveSheet()->SetCellValue('D1', 'Subcategory Name');
    /*$this->pexcel->getActiveSheet()->SetCellValue('D1', 'category_alt');
    $this->pexcel->getActiveSheet()->SetCellValue('E1', 'friendly_url');
    $this->pexcel->getActiveSheet()->SetCellValue('F1', 'category_image');
    $this->pexcel->getActiveSheet()->SetCellValue('G1', 'category_icon');
    $this->pexcel->getActiveSheet()->SetCellValue('H1', 'bg_image');
    $this->pexcel->getActiveSheet()->SetCellValue('I1', 'category_description');
    $this->pexcel->getActiveSheet()->SetCellValue('J1', 'parent_id');
    $this->pexcel->getActiveSheet()->SetCellValue('K1', 'dispatch_time');
    $this->pexcel->getActiveSheet()->SetCellValue('L1', 'coupon_code');
    $this->pexcel->getActiveSheet()->SetCellValue('M1', 'coupon_value');
    $this->pexcel->getActiveSheet()->SetCellValue('N1', 'home_menu');
    $this->pexcel->getActiveSheet()->SetCellValue('O1', 'catType');
    $this->pexcel->getActiveSheet()->SetCellValue('P1', 'sort_order');
    $this->pexcel->getActiveSheet()->SetCellValue('Q1', 'date_added');
    $this->pexcel->getActiveSheet()->SetCellValue('R1', 'date_modified');
    $this->pexcel->getActiveSheet()->SetCellValue('S1', 'status');*/
    //total_subcategories
    $this->pexcel->getActiveSheet()->getStyle("A1:D1")->applyFromArray(array("font" => array("bold" => true)));
    // read data to active sheet
    /*$res_array=array(
      "a category"=>array("a category"=>array("a","b","c",)),
      "b category"=>array("b category"),
      "c category"=>array("c sub category"=>array("c1","c2","c3"))
    );*/

    //$res_array=$this->get_parents();

    $this->db->where('parent_id',0);
    $this->db->select('category_id, category_name');
    $res_array = $this->db->get('wps_categories')->result_array();
    $rowNumber = 2;
    foreach ($res_array as $row) {
      $col = 'A';
      foreach ($row as $cell) {
        $this->pexcel->getActiveSheet()->setCellValue($col . $rowNumber, $cell);
        $col++;
      }
      $rowNumber++;
 

      $this->db->where('parent_id', $row['category_id']);
      $this->db->select('category_id,category_name');
      $results = $this->db->get('wps_categories')->result_array();

      if(is_array($results) & !empty($results) ){
        foreach ($results as $rows) {
          $cols=$col;
          foreach ($rows as $cellk) {
            $this->pexcel->getActiveSheet()->setCellValue($cols . $rowNumber, $cellk);
            $cols++;
          }
          $rowNumber++;
        }   
      }


    }


    //$this->pexcel->getActiveSheet()->fromArray($res_array,NULL,'A2');
    
		$filename='category_list.xls'; //save our workbook as this file name

		header('Content-Type: application/vnd.ms-excel'); //mime type

		header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name

		header('Cache-Control: max-age=0'); //no cache
		            
		//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
		//if you want to save it as.XLSX Excel 2007 format

		$objWriter = PHPExcel_IOFactory::createWriter($this->pexcel, 'Excel5'); 
    //ob_end_clean();
		//force user to download the Excel file without writing it to server's HD
		$objWriter->save("uploaded-files/import/$filename"); // 'php://output'

    
  }
  public function old_download_category_list() {
    //load our new PHPExcel library
    $this->load->library('pexcel');
    //activate worksheet number 1
		$this->pexcel->setActiveSheetIndex(0);
		//name the worksheet
		$this->pexcel->getActiveSheet()->setTitle('Old Category list');

		// load database
		$this->load->database();

		// load model
		$this->load->model('category/category_model');

		// get all categories in array formate
    //$condtion = "AND parent_id = '$parent_id'";
    $condtion = "AND parent_id = '0'";

    //$condtion = "";

   /* $condtion_array = array(
        'field' => "*,( SELECT COUNT(category_id) FROM wps_categories AS b WHERE b.parent_id=a.category_id ) AS total_subcategories",
        'condition' => $condtion,
        //'limit' => $config['limit'],
        //'offset' => $offset,
        'debug' => FALSE
    );

    $res_array = $this->category_model->getcategory($condtion_array); */

    //$config['total_rows'] = $this->category_model->total_rec_found;
    // Trying to set a column name
    $this->pexcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
    $this->pexcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
    $this->pexcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
    $this->pexcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
    $this->pexcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
    $this->pexcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
    $this->pexcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
    $this->pexcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
    $this->pexcel->getActiveSheet()->getColumnDimension('I')->setAutoSize(true);
    
    
    $this->pexcel->getActiveSheet()->SetCellValue('A1', 'Category Id');
    $this->pexcel->getActiveSheet()->SetCellValue('B1', 'Category Name');
    $this->pexcel->getActiveSheet()->SetCellValue('C1', 'Subcategory Id');
    $this->pexcel->getActiveSheet()->SetCellValue('D1', 'Subcategory Name');
    $this->pexcel->getActiveSheet()->SetCellValue('E1', 'Sub Subcategory Id');
    $this->pexcel->getActiveSheet()->SetCellValue('F1', 'Sub Subcategory Name');
    $this->pexcel->getActiveSheet()->SetCellValue('G1', 'Sub Sub Subcategory Id');
    $this->pexcel->getActiveSheet()->SetCellValue('H1', 'Sub Sub Subcategory Name');
    /*$this->pexcel->getActiveSheet()->SetCellValue('D1', 'category_alt');
    $this->pexcel->getActiveSheet()->SetCellValue('E1', 'friendly_url');
    $this->pexcel->getActiveSheet()->SetCellValue('F1', 'category_image');
    $this->pexcel->getActiveSheet()->SetCellValue('G1', 'category_icon');
    $this->pexcel->getActiveSheet()->SetCellValue('H1', 'bg_image');
    $this->pexcel->getActiveSheet()->SetCellValue('I1', 'category_description');
    $this->pexcel->getActiveSheet()->SetCellValue('J1', 'parent_id');
    $this->pexcel->getActiveSheet()->SetCellValue('K1', 'dispatch_time');
    $this->pexcel->getActiveSheet()->SetCellValue('L1', 'coupon_code');
    $this->pexcel->getActiveSheet()->SetCellValue('M1', 'coupon_value');
    $this->pexcel->getActiveSheet()->SetCellValue('N1', 'home_menu');
    $this->pexcel->getActiveSheet()->SetCellValue('O1', 'catType');
    $this->pexcel->getActiveSheet()->SetCellValue('P1', 'sort_order');
    $this->pexcel->getActiveSheet()->SetCellValue('Q1', 'date_added');
    $this->pexcel->getActiveSheet()->SetCellValue('R1', 'date_modified');
    $this->pexcel->getActiveSheet()->SetCellValue('S1', 'status');*/
    //total_subcategories
    $this->pexcel->getActiveSheet()->getStyle("A1:H1")->applyFromArray(array("font" => array("bold" => true)));
    // read data to active sheet
    /*$res_array=array(
      "a category"=>array("a category"=>array("a","b","c",)),
      "b category"=>array("b category"),
      "c category"=>array("c sub category"=>array("c1","c2","c3"))
    );*/

    //$res_array=$this->get_parents();

    $this->db->where('parentID',0);
    $this->db->select('catID, catName');
    $res_array = $this->db->get('category_tbl')->result_array();
    $rowNumber = 2;
    foreach ($res_array as $row) {
      $col = 'A';
      foreach ($row as $cell) {
        $this->pexcel->getActiveSheet()->setCellValue($col . $rowNumber, $cell);
        $col++;
      }
      $rowNumber++;
 

      $this->db->where('parentID', $row['catID']);
      $this->db->select('catID,catName');
      $results = $this->db->get('category_tbl')->result_array();

      if(is_array($results) & !empty($results) ){
        foreach ($results as $rows) {
          $cols=$col;
          foreach ($rows as $cellk) {
            $this->pexcel->getActiveSheet()->setCellValue($cols . $rowNumber, $cellk);
            $cols++;
          }
          $rowNumber++;

          $this->db->where('parentID', $rows['catID']);
          $this->db->select('catID,catName');
          $sub_results = $this->db->get('category_tbl')->result_array();
    
          if(is_array($sub_results) & !empty($sub_results) ){
            foreach ($sub_results as $sub_rows) {
              $colss=$cols;
              foreach ($sub_rows as $cellks) {
                $this->pexcel->getActiveSheet()->setCellValue($colss . $rowNumber, $cellks);
                $colss++;
              }
              $rowNumber++;

              $this->db->where('parentID', $sub_rows['catID']);
              $this->db->select('catID,catName');
              $sub_sub_results = $this->db->get('category_tbl')->result_array();
        
              if(is_array($sub_sub_results) & !empty($sub_sub_results) ){
                foreach ($sub_sub_results as $sub_sub_rows) {
                  $colsss=$colss;
                  foreach ($sub_sub_rows as $cellkss) {
                    $this->pexcel->getActiveSheet()->setCellValue($colsss . $rowNumber, $cellkss);
                    $colsss++;
                  }
                  $rowNumber++;
                  
                }   
              }
    

              
            }   
          }
              
        }   
      }


    }


    //$this->pexcel->getActiveSheet()->fromArray($res_array,NULL,'A2');
    
		$filename='old_category_list.xls'; //save our workbook as this file name

		header('Content-Type: application/vnd.ms-excel'); //mime type

		header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name

		header('Cache-Control: max-age=0'); //no cache
		            
		//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
		//if you want to save it as.XLSX Excel 2007 format

		$objWriter = PHPExcel_IOFactory::createWriter($this->pexcel, 'Excel5'); 
    //ob_end_clean();
		//force user to download the Excel file without writing it to server's HD
		$objWriter->save("uploaded-files/import/$filename"); // 'php://output'

    
  }

}

// End of controller