<?php

class Resources extends Admin_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->model(array('resources/resources_model'));
    $this->load->helper('resources/resources');
    $this->form_validation->set_error_delimiters("<span class='red'>", "</span>");
    $this->default_view = 'resources';
    $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' => "* ",
        'condition' => $condtion,
        'debug' => FALSE
    );
    $res_array = $this->resources_model->getcategory($condtion_array);
    //echo_sql();
   // echo "<pre>";print_r($res_array);die;
    //trace($_POST);
    $config['total_rows'] = $this->resources_model->total_rec_found;
    //$data['page_links'] = admin_pagination($base_url, $config['total_rows'], $config['limit'], $offset);
    $data['headingTitle'] = ( $parent_id > 0 ) ? 'Manage Subcategory' : 'Manage Resources';
    $data['res'] = $res_array;
    $data['parent_id'] = $parent_id;
  
   //echo "helooo";print_r($this->input->get_post('set_exclusive_range'));die;
    if ($this->input->post('action') != '') {
      if ($this->input->post('action') == 'Delete') {
        $prod_id = $this->input->post('arr_ids');
        $this->session->set_userdata('success', 'Record Has been deleted Successfully!');
        foreach ($prod_id as $v) {
          $where = array('entity_type' => 'resources/index', 'entity_id' => $v);
          safe_delete('wps_meta_tags', $where, TRUE);
        }
      }
      $this->update_status('wps_resources', 'id');  
     // echo "helooo";print_r($this->input->get_post('set_exclusive_range'));die;
    
    }

     if ($this->input->get_post('set_exclusive_range')) {
       // echo "helooo";print_r($this->input->get_post('set_exclusive_range'));die;
        $this->db->query("UPDATE wps_resources SET exclusive_range = '1' WHERE vtour_id = '" . $this->input->get_post('set_exclusive_range') . "'");
        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', 'Select Category has been set as Exclusive Range.');
        redirect($_SERVER['HTTP_REFERER']);
      }
       if ($this->input->get_post('unset_exclusive_range')) {
        $this->db->query("UPDATE wps_resources SET exclusive_range = '0' WHERE vtour_id = '" . $this->input->get_post('unset_exclusive_range') . "'");
        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', 'Select Category has been removed from Exclusive Range.');
        redirect($_SERVER['HTTP_REFERER']);
      }
       if ($this->input->get_post('set_unique_collection')) {
        $this->db->query("UPDATE wps_resources SET unique_collection = '1' WHERE vtour_id = '" . $this->input->get_post('set_unique_collection') . "'");
        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', 'Select Category has been set as Unique Collection.');
        redirect($_SERVER['HTTP_REFERER']);
      }
      if ($this->input->get_post('unset_unique_collection')) {
        $this->db->query("UPDATE wps_resources SET unique_collection = '0' WHERE vtour_id = '" . $this->input->get_post('unset_unique_collection') . "'");
        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', 'Select Category has been removed from Unique Collection.');
        redirect($_SERVER['HTTP_REFERER']);
      }

    if ($this->input->post('update_order') != '') {
      $this->update_displayOrder('wps_resources', 'sort_order', 'id');
    }
     
    $this->load->view($this->default_view . '/view_resources_list', $data);
  }

  public function add() {
    
    
//    $data['ckeditor1'] = set_ck_config(array('textarea_id' => 'description'));
//     $data['ckeditor2'] = set_ck_config(array('textarea_id' => 'description2'));
//    $data['ckeditor3'] = set_ck_config(array('textarea_id' => 'description3'));
//    $data['ckeditor4'] = set_ck_config(array('textarea_id' => 'description4'));
//     $data['ckeditor5'] = set_ck_config(array('textarea_id' => 'specification'));
    $parent_id = (int) $this->uri->segment(4, 0);
      
     $resource_name = $this->db->escape_str($this->input->post('title'));
    $posted_friendly_url = $this->input->post('friendlyUrl');  

    if ($parent_id != '' && $parent_id > 0) {
      $parent_id = applyFilter('NUMERIC_GT_ZERO', $parent_id);
      $data['headingTitle'] = 'Add Sub Resources';
      if ($parent_id <= 0) {
        redirect("wps-admin/resources");
      }
      $parentdata = $this->resources_model->get_category_by_id($parent_id);
      if (!is_array($parentdata)) {
        $this->session->set_userdata('error', 'Invalid Record!');
        redirect('wps-admin/resources', '');
      }
      $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['headingTitle'] = 'Add New Resources';
    }

    $this->form_validation->set_rules('title', 'Resource Name', "trim|required|max_length[100]|unique[wps_resources.title ='" . $resource_name . "' AND status!='2' AND parent_id='" . $parent_id . "']");

    if ($this->form_validation->run() === TRUE) {
         
      $uploaded_icon = "";
    

      if (!empty($_FILES) && $_FILES['vtour_pdf']['name'] != '') {
        $this->load->library('upload');
        $config1['upload_path'] = UPLOAD_DIR . '/resources/';
        $config1['allowed_types'] = 'gif|jpg|png|jpeg|pdf';
        $this->upload->initialize($config1);
        $uploaded_data = $this->upload->do_upload('vtour_pdf');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $uploaded_icon = $uploaded_data['upload_data']['file_name'];
        }
      }
   
  $redirect_url = "resources/index";
     
      $posted_data = array(
          'title' => $this->input->post('title'),
          
         
          'parent_id' => $parent_id,
          //'friendly_url' => $this->cbk_friendly_url,
          'date_added' => $this->config->item('config.date.time'),
          //'updated_date' => $this->config->item('config.date.time'),
           'media' => $uploaded_icon,
      
      );
//       trace($posted_data);
//        exit;
      $this->db->insert('wps_resources', $posted_data);
      $insertId = $this->db->insert_id();
      if ($insertId > 0) {
        if ($this->input->get_post('metaTitle') != '' && $this->input->get_post('metaDescription') != '') {
          $title = get_text($this->input->get_post('metaTitle'));
          $description = get_text($this->input->get_post('metaDescription'));
          $keywords = get_keywords($this->input->get_post('metaKeyword'));
        } else {
          $title = '';
          $description = '';
          $keywords = '';
        }
        $meta_array = array(
            'entity_type' => $redirect_url,
            'entity_id' => $insertId,
            //'page_url' => $this->cbk_friendly_url,
            'meta_title' => $this->input->post('title'),
            'meta_description' => $this->input->post('title'),
            'meta_keyword' => $this->input->post('title')
        );
     //$this->db->insert('wps_meta_tags', $meta_array);
      }

      $this->session->set_userdata('success', 'Record has been added successfully!');
      $redirect_path = isset($parentdata) && is_array($parentdata) ? 'resources/index/' . $parentdata['category_id'] : 'resources';
      $this->load->helper('url');
      redirect(base_url() . 'wps-admin/' . $redirect_path, '');
      exit;
    }
    $data['parent_id'] = $parent_id;
    $this->load->view($this->default_view . '/view_resources_add', $data);
  }

  public function edit() {    
    //$data['ckeditor1'] = set_ck_config(array('textarea_id' => 'description'));
    //$data['ckeditor2'] = set_ck_config(array('textarea_id' => 'description2'));
    //$data['ckeditor3'] = set_ck_config(array('textarea_id' => 'description3'));
    //$data['ckeditor4'] = set_ck_config(array('textarea_id' => 'description4'));
    // $data['ckeditor5'] = set_ck_config(array('textarea_id' => 'specification'));
    $baseURL = base_url();
    $catId = (int) $this->uri->segment(4);
    //echo "hiiii";die;
    $rowdata = $this->resources_model->get_category_by_id($catId);
    $data['headingTitle'] = ($rowdata['parent_id'] > 0 ) ? 'Edit Resources' : 'Edit Resources';

    if (!is_array($rowdata)) {
      $this->session->set_flashdata('message', lang('idmissing'));
      redirect('wps-admin/resources', '');
    }
   //echo "<pre>";print_r($_POST);die;
    $posted_friendly_url = $this->input->post('friendlyUrl');
    $this->cbk_friendly_url = seo_url_title($posted_friendly_url);
    $resource_name = $this->db->escape_str($this->input->post('title'));
    $categoryId = $rowdata['id'];
    //Meta Details - Main
    //$metaDets = get_db_single_row("wps_meta_tags", "meta_title, meta_description, meta_keyword", "entity_type = 'vtour/index' AND entity_id = '" . $categoryId . "'");


    $this->form_validation->set_rules('title', 'Resources Name', "trim|required|max_length[100]|unique[wps_resources.title ='" . $resource_name . "' AND status!='0' AND parent_id='" . $rowdata['parent_id'] . "' AND id!='" . $categoryId . "']");


    if ($this->form_validation->run() == TRUE) {
   
      $uploaded_icon = $rowdata['vtour_pdf'];
      $unlink_image2 = array('source_dir' => "vtourpdf", 'source_file' => $rowdata['vtour_pdf']);
      if (!empty($_FILES) && $_FILES['vtour_pdf']['name'] != '') {
        $this->load->library('upload');
        $config1['upload_path'] = UPLOAD_DIR . '/resources/';
        $config1['allowed_types'] = 'gif|jpg|png|jpeg|pdf';
        $this->upload->initialize($config1);
        $uploaded_data = $this->upload->do_upload('vtour_pdf');
        if (is_array($uploaded_data) && !empty($uploaded_data)) {
          $uploaded_icon = $uploaded_data['upload_data']['file_name'];
          removeImage($unlink_image2);
        }
      }  
     

      $posted_data = array(
          'title' => $this->input->post('title'),
    
          'media' => $uploaded_icon,
         'updated_date' => $this->config->item('config.date.time'),
         

      );
      //trace($posted_data);die;

      $this->db->where('id', $categoryId);
      $this->db->update('wps_resources', $posted_data);


      //Update Meta
      if ($categoryId > 0) {
        if ($this->input->get_post('metaTitle') != '' && $this->input->get_post('metaDescription') != '') {
          $title = get_text($this->input->get_post('metaTitle'));
          $description = get_text($this->input->get_post('metaDescription'));
          $keywords = $this->input->get_post('metaKeyword');
        } else {
          $title = '';
          $description = '';
          $keywords = '';
        }
        $posted_data_meta = array(
            'meta_title' => $title,
            'meta_description' => $description,
            'meta_keyword' => $keywords,
        );
        $this->db->where('entity_id', $categoryId);
        $this->db->where('entity_type', 'resources/index');
       // $this->db->update('wps_meta_tags', $posted_data_meta);
      }
      //End here

      $this->session->set_userdata('success', 'Record has been updated successfully!');
      $redirect_path = $rowdata['parent_id'] > 0 ? 'resources/index/' . $rowdata['parent_id'] : 'resources';
      //header("Location:".$baseURL.'wps-admin/' . $redirect_path);
      redirect(base_url('wps-admin/' . $redirect_path), '');
    }
    $data['parent_id'] = $rowdata['parent_id'];

    //$data['metaDets'] = $metaDets;
    $data['catresult'] = $rowdata;
    $this->load->view($this->default_view . '/view_resources_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('wps-admin/resources', '');
    } else {
      $total_category = count_category("AND parent_id='$catId' ");
      $total_product = count_products("AND 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'], '');
    }
  }

  function validateFile($flName, $ext) {
    $parameter = explode(',', $ext);
    $fileName = $parameter[0];
    $allowedExt = $parameter[1];
    $isRequired = $parameter[2];
    if ($isRequired == 'false') {
      if (empty($_FILES[$fileName]['name'])) {
        return TRUE;
      } else {
        $file = $_FILES[$fileName];
        $ext_groups = array();
        $ext_groups['image'] = array('jpg', 'jpeg', 'gif', 'png', 'JPG', 'JPEG', 'GIF', 'PNG');
        $ext_groups['document'] = array('rtf', 'doc', 'docx', 'pdf', 'txt', 'ppt', 'zip');
        $ext_groups['media'] = array('mp4', 'mpeg4');
        $ext_groups['compressed'] = array('zip', 'gzip', 'tar', 'gz');
        $exts = $ext_groups[$allowedExt];
        //get file ext
        $file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        if (!in_array($file_ext, $exts)) {
          $exts_allowed = implode(" | ", $exts);
          $this->form_validation->set_message('validateFile', "File should be " . $exts_allowed);
          return FALSE;
        } else {
          return TRUE;
        }
      }
    } else {
      if (empty($_FILES[$fileName]['name'])) {
        $this->form_validation->set_message('validateFile', 'Please select file.');
        return false;
      } else {
        $file = $_FILES[$fileName];
        $ext_groups = array();
        $ext_groups['image'] = array('jpg', 'jpeg', 'gif', 'png', 'JPG', 'JPEG', 'GIF', 'PNG');
        $ext_groups['document'] = array('rtf', 'doc', 'docx', 'pdf', 'txt', 'ppt', 'zip');
        $ext_groups['media'] = array('mp4', 'mpeg4');
        $ext_groups['compressed'] = array('zip', 'gzip', 'tar', 'gz');
        $exts = $ext_groups[$allowedExt];
        //get file ext
        $file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        if (!in_array($file_ext, $exts)) {
          $exts_allowed = implode(" | ", $exts);
          $this->form_validation->set_message('validateFile', "File should be " . $exts_allowed);
          return FALSE;
        } else {
          return TRUE;
        }
      }
    }
  }

  public function updateuserstatus() {
    $userId = $this->input->post('userId');
    $status = $this->input->post('status');
    if ($userId > 0) {
      $this->db->query("UPDATE wps_categories SET status = '" . $status . "' WHERE category_id = '" . $userId . "'");
      if ($status == 0) {
        echo 'Record has been Deactived successfully!';
      } else {
        echo 'Record has been Actived successfully!';
      }
    } else {
      echo 'Something went wrong, please try again later!';
    }
  }

  public function check_upload_excel() {
    $filearrext = array('xls', 'xlsx');
    if ($_FILES['excel_file']['name'] == '') {
      $this->form_validation->set_message('check_upload_excel', 'Please upload excel file.');
      return FALSE;
    }
    if ($_FILES['excel_file']['name'] != '') {
      $extension = substr(strrchr($_FILES['excel_file']['name'], '.'), 1);
      if (!in_array($extension, $filearrext)) {
        $this->form_validation->set_message('check_upload_excel', 'Please upload (xls) file only.');
        return FALSE;
      } else {
        return TRUE;
      }
    }
  }

}

// End of controller
