<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class item extends MY_Controller{
	public function index(){
		$data = "";

		//Access---
        $access_array = $this->fm->get_access(array(18, 19, 20));
        $data['can_create'] = isset($access_array[18]);
        $data['can_edit'] = isset($access_array[19]);
        $data['can_delete'] = isset($access_array[20]);
		//---------

        $this->load->view($this->router->fetch_class()."/index", $data);
	}
	
	public function edit($id=""){
		//To prevent loss---
		$this->fm->keep_all_page_filter();
		//------------------
		
		$data['id'] = $id != ""? $id:0;
		
		$this->load->view($this->router->fetch_class()."/edit", $data);
	}
	
	public function load_edit(){
		$this->load->helper("file");		
		$this->load->model("item_model");
		$this->load->model("item_attachment_model");
		$post = $this->input->post();
		
		//To prevent loss---
		$this->fm->keep_all_page_filter();
		//------------------
		
		$data = array();
		
		//Access---
        $access_array = $this->fm->get_access(array(18, 19, 20));
        $data['can_create'] = isset($access_array[18]);
        $data['can_edit'] = isset($access_array[19]);
        $data['can_delete'] = isset($access_array[20]);
		//---------
		
		if($this->input->post('CODE') != "0"){
			
			$data_array = $this->item_model->get_data(array(
				'condition' => "<T>.<PK> = '".$this->fm->str_esc($post['CODE'], 1)."'",
				'' => "",
			));    

			if(count($data_array) > 0){
				$data['data'] = $data_array[0];

				$data['attach_array'] = $this->item_attachment_model->get_data(array(
					'condition' => "<T>.ITEM = '".$data['data']->CODE."'",
					'additional_select' => "OCTET_LENGTH(<T>.CONTENT) AS CONTENT_SIZE",
				));
				foreach($data['attach_array'] as $v){
					$v->IS_IMAGE = (substr(get_mime_by_extension($v->FILENAME), 0, 5) == "image");
				}
			}
		}		
		
		$this->load->model("taxcode_model");
        $data['all_taxcode'] = $this->taxcode_model->get_data( array(
            'sort' => "<T>.CODE",
            '' => "",
        ));

        $this->load->model("category_model");
        $data['all_category'] = $this->category_model->get_data( array(
            'sort' => "<T>.CODE",
            '' => "",
        ));

        $this->load->model("item_grp_model");
        $data['all_item_grp'] = $this->item_grp_model->get_data( array(
            'sort' => "<T>.CODE",
            '' => "",
        ));
		        
		if(($data['can_create'] && $this->input->post('CODE') == "0") || (isset($data['data']))){
			$this->load->view($this->router->fetch_class()."/load_edit", $data);
			return;
		}
		
		header("HTTP/1.1 500 Internal Server Error");
		header("Content-Type: application/json; charset=UTF-8");
		return;
	}
	
	public function update(){
		$this->load->helper("file");
        $this->load->model("item_attachment_model");
        $this->load->model("item_model");
		$post = $this->input->post();
		
		//To prevent loss---
		$this->fm->keep_all_page_filter();
		//------------------
		
		// print_r($post);
		// return;

		$main_post = array();
		$sub_post = array();
		foreach($post as $index=>$value){
			if(! in_array($index, array('DEL_SUB_PKKEY'))){
				if(substr($index, 0, strlen("ATTACHMENT")) == "ATTACHMENT"){
					$sub_post[$index] = $value;
				}
				else{
					$main_post[$index] = $value;
				}
			}
		}
		
        $return = $this->item_model->save($main_post);
		
		if($return['error'] == ""){
            $action = ! isset($main_post['CODE'])? "Create":"Update";
            //Attachment---
           // print_r($_FILES['ATTACHMENT']);return;
				if(isset($_FILES['ATTACHMENT']['tmp_name'])){
					foreach($_FILES['ATTACHMENT']['tmp_name'] as $x=>$file){
						if($file != "" && file_exists($file)){
							unset($attachment_data);
							$attachment_data['ITEM'] = $return['pk'];
							$attachment_data['CONTENT'] = file_get_contents($file);
							$attachment_data['FILENAME'] = $return['pk'].".png";
							//if(isset($_FILES['ATTACHMENT']['name'][$x])) $attachment_data['FILENAME'] = $_FILES['ATTACHMENT']['name'][$x];
							
							$attachment_return = $this->item_attachment_model->save($attachment_data);
						}
					}
				}
				//--------

			$item_array = $this->item_model->get_data(array(
				'condition' => "<T>.CODE = '".$this->fm->str_esc($post['CODE'], 1)."'",
				'select' => "<T>.CODE",
			));

            $action = ! isset($post['CODE'])? "Create":"Update";
            $this->session->set_flashdata('success', $action." Successful!");
        }
		else{
			$this->session->set_flashdata('error', $return['error']);
		}
		
		// redirect(base_url($this->router->fetch_class()."?".$this->session->flashdata($this->router->fetch_class().'_page_filter')));
		if(isset($post['CODE'])){
			$redirect_params = "";
			$redirect_params .= "/edit/".$post['CODE'];
        	redirect(base_url($this->router->fetch_class().$redirect_params));
		}else{
			redirect(base_url($this->router->fetch_class()."?".$this->session->flashdata($this->router->fetch_class().'_page_filter')));
		}
	}

	public function delete(){
        $this->load->model("item_model");
        $this->load->model("item_attachment_model");
        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------
        
        $pk = $this->item_model->sql_get_pk();
        if(isset($post[$pk]) && $this->item_model->remove($post[$pk])){
            $sub_array = $this->item_attachment_model->get_data(array(
                'condition' => "<T>.ITEM = '".$post[$pk]."' ",
            ));//print_r($sub_array);return;

            if(count($sub_array) > 0){
                foreach($sub_array as $sub){
                    $name = $sub->FILENAME;
                    // $file = "D:/xampp/htdocs/CMMS/assets/upload/cmrf/".$name;
                    // unlink($file);
                    $this->item_attachment_model->remove($sub->PKKEY);
                }
            }

            $this->session->set_flashdata('success', "Delete Successful!");
        }
        else{
            $this->session->set_flashdata('error', "Delete Failed!");
        }
        
        redirect(base_url($this->router->fetch_class()."?".$this->session->flashdata($this->router->fetch_class().'_page_filter')));
    }
	
	public function check_unique(){
        $this->load->model("item_model");
		$post = $this->input->post();
		
		//To prevent loss---
		$this->fm->keep_all_page_filter();
		//------------------
		
		if($this->input->post('unique') != ""){
            $condition = "<T>.CODE = '".$this->fm->str_esc($post['unique'], 1)."'";
			if(isset($post['pk'])) $condition .= " AND <T>.<PK> != '".$post['pk']."'";
            $data_array = $this->item_model->get_data(array(
				'condition' => $condition,
			));
			
			if(count($data_array) == 0){
				echo "1";
			}
		}
	}

	public function check_unique_number(){
        $this->load->model("item_model");
        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------
        
        if($this->input->post('unique') != ""){
            $condition = "<T>.CODE = '".$this->fm->str_esc($post['unique'], 1)."'";
            if(isset($post['pk'])) $condition .= " AND <T>.<PK> != '".$post['pk']."'";
            $data_array = $this->item_model->get_data(array(
                'condition' => $condition,
            ));
            
            if(count($data_array) == 0){
                echo "1";
            }
        }
    }

	public function send_email(){
        	$this->load->model("email_model");
		$get = $this->input->get();
		
	//function send($to_array="", $subject="", $message="", $cc_array="", $bcc_array="", $attach=array()){
		$p1 = $this->input->get("SENDER");
		
		$sender = array();
		array_push($sender,$p1);
		array_push($sender,"chansaifok@gmail.com");
		
		$p2 = $this->input->get("SUBJECT");
		$p3 = $this->input->get("BODY");
        $p4 = $this->input->get("CC");
        $p5 = $this->input->get("BCC");
		
		$attach = array();
		array_push($attach, "c:\\photo\\in\\GB0000001_E.jpg");
		array_push($attach, "c:\\photo\\in\\GB0000001_F.jpg");
		
		
        $this->email_model->send($sender,$p2,$p3,$p4,$p5,$attach);
	}

	public function load_crystal_report(){
		$get = $this->input->get();
		
		$data['user'] = $this->fm->get_current_user();
		if($data['user'] != NULL){
			$formula = "";
			

			//Store Footprint---
			if($this->record_footprint) $this->footprint_model->record($this->router->fetch_class()."/".$this->router->fetch_method(), isset($_SERVER['QUERY_STRING'])? $_SERVER['QUERY_STRING']:"", isset($_POST)? $_POST:array());
			//------------------
			
			//Set parameter to avoid Filter Data lost---
			$this->session->set_flashdata($this->router->fetch_class().'_page_filter', $_SERVER['QUERY_STRING']);
			//------------------------------------------
			
			$this->load->model("cr_model");
            $filter1 = "";
            $filter2 = "";
            $filter3 = "";
            $filter4 = "";
            $filter5 = "";
            $filter6 = "";
            $filter7 = "";
            $filter8 = "";
            $filter9 = "";
            $d1 = "";
            $d2 = "";
            
			$this->load->model("cr_model");
            $return = $this->cr_model->export_pdf(array(
                'TITLE' => "Item",
                'RPT' => "ITEM.rpt",
                'FILENAME' => "ITEM-".$this->fm->generate_token(10).".pdf",
				'FORMULA' => $formula,
				'D1' => $d1,
				'D2' => $d2,
                'FILTER01' => $filter1,
                'FILTER02' => $filter2,
                'FILTER03' => $filter3,
                'FILTER04' => $filter4,
                'FILTER05' => $filter5,
                'FILTER06' => $filter6,
                'FILTER07' => $filter7,
                'FILTER08' => $filter8,
                'FILTER09' => $filter9,
                'ORDERBY1' => $filter9,
                'ORDERBY2' => $filter9,
                'ORDERBY3' => $filter9,
            ));
            if(strlen($return['DESTINATION']) > 0){
                //header("Content-Type: application/pdf");
                print "<embed src=\"".base_url($return['DESTINATION'])."\" width=\"100%\" height=\"100%\">";
                return;
            }
        }
		header("HTTP/1.1 500 Internal Server Error");
		header("Content-Type: application/json; charset=UTF-8");
		return;
	}

	
	public function load_data(){
        $this->load->model("item_model");
        $this->load->model("company_profile_model");
		$post = $this->input->post();
		$data['print'] = $this->input->post('print');
		
		//Config---
		$config['page'] = (int)$this->input->post('PAGE') > 0? (int)$post['PAGE']:1;
		$config['cur_page'] = $config['page'];
		$config['page'] -= 1;
		$config['per_page'] = (int)$this->input->post('PP') > 0? (int)$post['PP']:$this->per_page_array[0];
		$config['previous_btn'] = TRUE;
		$config['next_btn'] = TRUE;
		$config['first_btn'] = TRUE;
		$config['last_btn'] = TRUE;
		//---------
		
		$condition = "";
			
		//Search---
        if($this->input->post('CODE') != ""){

            $condition = $this->fm->append($condition, "<T>.CODE LIKE '%".$this->fm->str_esc($post['CODE'], 1)."%'");

        }

        $data['header_array'] = array(

        array(

            'description' => "#",

           'style' => "text-align: center;",

           'sort' => "",

        ),

        array(

            'description' => "Item Code",

           'style' => "white-space: nowrap; text-align: center;",

           'sort' => "<T>.CODE",

        ),

        array(

            'description' => "Name",

           'style' => "white-space: nowrap; text-align: center;",

           'sort' => "<T>.NAME",

        ),

        array(

            'description' => "Description",

           'style' => "white-space: nowrap; text-align: center;",

           'sort' => "<T>.DESCRIPT",

        ),

        array(

            'description' => "Category",

           'style' => "white-space: nowrap; text-align: center;",

           'sort' => "<T>.CATEGORY",

        ),

        array(

            'description' => "Item Group",

           'style' => "white-space: nowrap; text-align: center;",

           'sort' => "<T>.ITEM_GRP",

        ),


        array(

            'description' => "Action",'style' => "width: 1%; white-space: nowrap; text-align: center;",                'sort' => "",

        ),

        );


        $sort = "";
		if($this->input->post('S') != ""){
			$decrypted_s = $this->fm->decrypt($post['S']);
			$sort = $this->input->post('SD') != "1"? $decrypted_s:$this->fm->sort_inverse($decrypted_s);
		}
		
		if($sort == ""){
			foreach($data['header_array'] as $v){
				if(isset($v['sort']) && $v['sort'] != ""){
					$sort = $v['sort'];
					break;
				}
			}
		}
		
        $data['count'] = $this->item_model->data_count(array(
			'condition' => $condition,
		));
		
		$max_page = ceil($data['count'] / $config['per_page']);
		if($max_page <= 0) $max_page = 1;
		if($config['cur_page'] > $max_page){
			$config['cur_page'] = $max_page;
			$config['page'] = $max_page - 1;
		}
		$config['start'] = $config['page'] * $config['per_page'];

		if($this->input->post('print') == "1"){
			$limit = "999999";
		}else{
			$limit = $config['per_page'];
		}
		
		$additional_join = ""; 
        $additional_join .= "LEFT JOIN CATEGORY ON CATEGORY.CODE = <T>.CATEGORY";
        $additional_join .= " LEFT JOIN ITEM_GRP ON ITEM_GRP.CODE = <T>.ITEM_GRP";
		$data['list'] = $this->item_model->get_data(array(
			'condition' => $condition,
			'limit' => $limit,
			'offset' => $config['start'],
			'sort' => $sort,
			'additional_select' => "CATEGORY.DESCRIPT AS CATEGORY_DESCRIPT, ITEM_GRP.DESCRIPT AS ITEM_GRP_DESCRIPT",
			'additional_join' => $additional_join,
		));
        $data['total_item'] = $this->item_model->get_data(array(
			'condition' => $condition,
			'' => "",
		));

		//Company Profile
        $company = $this->company_profile_model->get_data(array(
            'condition' => "",
        ));
        $data['company'] = $company[0];

		$data['config'] = $config;
		$user = $this->fm->get_current_user();
        $data['username'] = $user->NAME;
        $data['userid'] = $user->CODE;
		
		//Access---
        $access_array = $this->fm->get_access(array(18, 19, 20));
        $data['can_create'] = isset($access_array[18]);
        $data['can_edit'] = isset($access_array[19]);
        $data['can_delete'] = isset($access_array[20]);
		//---------
		
		//Store Footprint---
		if($this->record_footprint) $this->footprint_model->record($this->router->fetch_class()."/".$this->router->fetch_method(), isset($_SERVER['QUERY_STRING'])? $_SERVER['QUERY_STRING']:"", isset($_POST)? $_POST:array());
		//------------------
		
		//Set parameter to avoid Filter Data lost---
		$this->session->set_flashdata($this->router->fetch_class().'_page_filter', $_SERVER['QUERY_STRING']);
		//------------------------------------------
	
		if($this->input->post('print') == "1"){
			$this->load->view($this->router->fetch_class()."/load_print", $data);}
		else{
			$this->load->view($this->router->fetch_class()."/load_data", $data);}

	}
}
