<?php

class Gallery extends Admin_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->model(array('gallery/gallery_model',  'gallery_category/gallery_category_model'));
    $this->load->helper('gallery/gallery');
    $this->form_validation->set_error_delimiters("<div class='required'>", "</div>");
    $this->default_view = 'gallery';
    $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(gallery_id) FROM wps_gallery AS b WHERE b.parent_id=a.gallery_id ) AS total_subcategories",
        'condition' => $condtion,
        'debug' => FALSE
    );
    $res_array = $this->gallery_model->getgallery($condtion_array);
    //trace($res_array);
    //echo_sql();
    $config['total_rows'] = $this->gallery_model->total_rec_found;
    //$data['page_links'] = admin_pagination($base_url, $config['total_rows'], $config['limit'], $offset);
    if ($parent_id > 0) {
      $data['headingTitle'] = 'Album Image';
    } else {
      $data['headingTitle'] = 'Gallery';
    }
    $data['res'] = $res_array;
    $data['parent_id'] = $parent_id;


    if ($this->input->post('action') != '') {

      if ($this->input->post('action') == 'Delete') {
        $prod_id = $this->input->post('arr_ids');
        $this->session->set_flashdata('delete_cat', 'Gallery Has been deleted Successfully!');
        foreach ($prod_id as $v) {
          $where = array('entity_type' => 'gallery/index', 'entity_id' => $v);
          $this->gallery_model->safe_delete('wps_meta_tags', $where, TRUE);
        }
      }
      $this->update_status('wps_gallery', 'gallery_id');
    }
    if ($this->input->post('update_order') != '') {
      $this->update_displayOrder('wps_gallery', 'sort_order', 'gallery_id');
    }
$categoryList = $this->gallery_category_model->get_gallery_cat('', '');
    $data['categoryList'] = $categoryList;

  $category_detail=$this->db->query("SELECT * FROM wps_gallery_category JOIN wps_gallery ON wps_gallery.gallery_parent_id = wps_gallery_category.category_id")->result_array();
$data['category_detail'] = $category_detail;

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

  public function add() {
     $branch_id=$this->session->userdata('branch_id');
    $parent_id = '';
    $data['ckeditor'] = set_ck_config(array('textarea_id' => 'cat_desc'));
   
    $img_allow_size = $this->config->item('allow.file.size');
    $img_allow_dim = $this->config->item('allow.imgage.dimension');
    $gallery_name = $this->db->escape_str($this->input->post('gallery_name'));
    $posted_friendly_url = $this->input->post('friendly_url');

    $this->cbk_friendly_url = seo_url_title($posted_friendly_url);
    $data['parentData'] = '';
    $data['headingTitle'] = 'Add Gallery';

    $seo_url_length = $this->config->item('seo_url_length');
      
    $this->form_validation->set_rules('parent_id', 'Category Id', 'trim|required');
    
    $this->form_validation->set_rules('subcat_id', 'Category Id', 'trim');
      
      
      
    $this->form_validation->set_rules('gallery_name', 'Title', "trim|required|max_length[100]");
     
    
    $this->form_validation->set_rules('gallery_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 = "";
        if (!empty($_FILES) && $_FILES['gallery_image']['name'] != '') {
          $this->load->library('upload');
          $config1['upload_path'] = UPLOAD_DIR . '/gallery/';
          $config1['allowed_types'] = 'gif|jpg|png|jpeg';
          $this->upload->initialize($config1);
          $uploaded_data = $this->upload->do_upload('gallery_image');
          if (is_array($uploaded_data) && !empty($uploaded_data)) {
            $uploaded_file = $uploaded_data['upload_data']['file_name'];
          
          }
        }


      
        $posted_data = array(
            //'friendly_url' => $this->cbk_friendly_url,
            'gallery_name' => $this->input->post('gallery_name'),
            'gallery_parent_id' => $this->input->post('parent_id', TRUE),
            'gallery_sub_parentID' => $this->input->post('subcat_id'),
            'gallery_image' => $uploaded_file,
        );
       
       $parent_id=$this->input->post('parent_id', TRUE);
      
      $insertId = $this->gallery_model->safe_insert('wps_gallery', $posted_data, FALSE);

      if ($insertId > 0 && $parent_id == 0) {
        $redirect_url = "gallery/index";
        $meta_description = $this->input->post('gallery_name');
        $meta_keyword = $this->input->post('gallery_name');
        $meta_array = array(
            'entity_type' => $redirect_url,
            'entity_id' => $insertId,
            'page_url' => $this->cbk_friendly_url,
            'gallery_parent_id' => $this->input->post('parent_id', TRUE),
            'meta_title' => get_text($this->input->post('gallery_name'), 80),
            'meta_description' => get_text($meta_description),
            'meta_keyword' => get_keywords($meta_keyword)
        );
        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) ? 'gallery/index/' . $parentdata['gallery_id'] : 'gallery';
      redirect('wps-admin/' . $redirect_path, '');
    }
   
    $data['parent_id'] = $parent_id;
    //
   
      $categoryList = $this->db->query("SELECT * FROM wps_gallery_category where status='1'")->result_array();
    
    $data['categoryList'] = $categoryList;
    $this->load->view($this->default_view . '/view_gallery_add', $data);
  }
  public function edit() {
    $catId = (int) $this->uri->segment(4);
    $rowdata = $this->gallery_model->get_gallery_by_id($catId);
    $data['headingTitle'] = ($rowdata['parent_id'] > 0 ) ? 'Album Image' : 'Album';
    $img_allow_size = $this->config->item('allow.file.size');
    $img_allow_dim = $this->config->item('allow.imgage.dimension');
    $posted_friendly_url = $this->input->post('friendly_url');
    $this->cbk_friendly_url = seo_url_title($posted_friendly_url);

    if (!is_array($rowdata)) {
      $this->session->set_flashdata('message', lang('idmissing'));
      redirect('wps-admin/gallery', '');
    }
    $galleryId = $rowdata['gallery_id'];
    $seo_url_length = $this->config->item('seo_url_length');
    
    $this->form_validation->set_rules('gallery_name', 'Title', "trim|required|max_length[100]");
     
   
    $this->form_validation->set_rules('gallery_image', 'Album Image', "false");

    if ($this->form_validation->run() == TRUE) {
     
      $uploaded_file = $rowdata['gallery_image'];
      $unlink_image = array('source_dir' => "gallery", 'source_file' => $rowdata['gallery_image']);
      if ($this->input->post('cat_img_delete') === 'Y') {
        removeImage($unlink_image);
        $uploaded_file = NULL;
      }
       $uploaded_file = "";
        if (!empty($_FILES) && $_FILES['gallery_image']['name'] != '') {
          $this->load->library('upload');
          $config1['upload_path'] = UPLOAD_DIR . '/gallery/';
          $config1['allowed_types'] = 'gif|jpg|png|jpeg';
          $this->upload->initialize($config1);
          $uploaded_data = $this->upload->do_upload('gallery_image');
          if (is_array($uploaded_data) && !empty($uploaded_data)) {
            $uploaded_file = $uploaded_data['upload_data']['file_name'];
          
          }
        }
      
        $posted_data = array(
            'gallery_parent_id' => $this->input->post('parent_id', TRUE),
            'gallery_name' => $this->input->post('gallery_name'),
            //'friendly_url' => $this->cbk_friendly_url,
            //'branch_id' => $this->input->post('branch_id'),
            'gallery_image' => $uploaded_file,
        );
      
        update_meta_page_url('gallery/index', $galleryId, $this->cbk_friendly_url);
      

      $where = "gallery_id = '" . $galleryId . "'";
      $this->gallery_model->safe_update('wps_gallery', $posted_data, $where, FALSE);

      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', lang('successupdate'));
      $redirect_path = $rowdata['parent_id'] > 0 ? 'gallery/index/' . $rowdata['parent_id'] : 'gallery';
      redirect('wps-admin/' . $redirect_path . '/' . query_string(), '');
    }
   
    $data['catresult'] = $rowdata;
     $categoryList = $this->db->query("SELECT * FROM wps_gallery_category where status='1'")->result_array();
    $data['categoryList'] = $categoryList;
//      echo "<pre>";
//      print_r($categoryList);
//       echo "</pre>";
//      exit;
    $this->load->view($this->default_view . '/view_gallery_edit', $data);
  } 

  public function comment() {
    $gallery_id = (int) $this->uri->segment(4);
    $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'));
    $keyword = trim($this->input->get_post('keyword', TRUE));
    $keyword = $this->db->escape_str($keyword);
    $condtion = "";
    if ($gallery_id != '') {
      $condtion = "&& gallery_id = '" . $gallery_id . "'";
    }
    $status = $this->input->get_post('status', TRUE);
    $keyword = $this->input->get_post('keyword', TRUE);
    if ($status != '') {
      $condtion['status'] = $status;
    }
    if ($keyword != '') {
      $condtion['keyword'] = $keyword;
    }
    $condtion_array = array(
        'field' => "*",
        'condition' => $condtion,
        'gallery_id' => $gallery_id,
        'type' => 'A',
        'debug' => FALSE
    );
    $res_array = $this->gallery_model->get_gallery_comment($config['limit'], $offset, $condtion_array);
    $data['title'] = 'allery Comment';
    $config['total_rows'] = $this->gallery_model->total_rec_found;
    $data['page_links'] = admin_pagination($base_url, $config['total_rows'], $config['limit'], $offset);
    $data['headingTitle'] = 'Comments';
    $data['gallery_id'] = $gallery_id;
    $data['res'] = $res_array;

    if ($this->input->post('status_action') != '') {
      $this->update_status('wps_gallery_comment', 'comment_id');
    }
    if ($this->input->post('update_order') != '') {
      $this->update_displayOrder('wps_gallery_comment', 'sort_order', 'comment_id');
    }

    $this->load->view('gallery/view_reviews_list', $data);
  }
    
public function ajaxGal()
{
@extract($_POST);
 $sql_ajax=$this->db->query("SELECT * FROM wps_gallery_category where parent_id='$parent_id' and status='1'");
    $num = $sql_ajax->num_rows();
if($num > 0)
{
echo "<select name='subcat_id' class='form-control'>";
echo '<option value="" selected disabled>Select Gallery Subcategory</option>';
foreach($sql_ajax->result_array() as $galResult)
{	
echo '<option value="'.$galResult['category_id'].'">'.$galResult['name'].'</option>';
 
 }
echo "</select>";
}
}
}

// End of controller