<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class adj extends MY_Controller{
	public function index(){
        $data = "";
        $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->model("adj_model");
        $this->load->model("adjitem_model");

        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------
        
        $data = array();
        
        //Access---
        $access_array = $this->fm->get_access(array(87, 88, 89));
        $data['can_create'] = isset($access_array[87]);
        $data['can_edit'] = isset($access_array[88]);
        $data['can_delete'] = isset($access_array[89]);
        //---------
        
        $user = $this->fm->get_current_user();
        $data['username'] = $user->NAME;
        $data['userid'] = $user->CODE;
        $data['userpkkey'] = $user->PKKEY;

        $data['sub_array'] = array();

        if($this->input->post('REFNO') != "0"){
            
            $data_array = $this->adj_model->get_data(array(
                'condition' => "<T>.REFNO = '".$this->fm->str_esc($post['REFNO'], 1)."'",
                '' => "",
            ));
            
            if(count($data_array) > 0){
                $data['data'] = $data_array[0];

                $this->load->model("User_model");

                $additional_join = ""; 
                $additional_join .= "LEFT JOIN GOLD ON GOLD.CODE = <T>.GOLD";
                $data['sub_array'] = $this->adjitem_model->get_data(array(
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                    'sort' => "",
                    '' => "",
                    'additional_select' => "GOLD.NAME AS GOLD_NAME",
                    'additional_join' => $additional_join,
                ));

                //Calculate total
                $gold = $this->adjitem_model->get_data(array(
                    'select' => "<T>.GOLDPRICE",
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                ));

                //Total gold price amount (Excluded gst)
                $gold_total = array();
                foreach($gold as $lv){
                    array_push($gold_total, $lv->GOLDPRICE);
                }
                $data['gold_total'] = array_sum($gold_total);
            }
        }

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

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

        if(($data['can_create'] && $this->input->post('REFNO') == "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->model("adj_model");
        $this->load->model("adjitem_model");

		$post = $this->input->post();
		//print_r($post);return;
		
		//To prevent loss---
		$this->fm->keep_all_page_filter();
		//------------------
		
		$main_post = array();
		$sub_post = array();
		foreach($post as $index=>$value){
			if(! in_array($index, array('DEL_SUB_PKKEY'))){
				if(substr($index, 0, strlen("SUB_")) == "SUB_"){
					$sub_post[$index] = $value;
				}
				else{
					$main_post[$index] = $value;
				}
			}
		}


		if($return = $this->adj_model->save($main_post)){
			$invoice_pkkey = $return['pk'];
		
        	if(isset($sub_post['SUB_PKKEY'])){
				foreach($sub_post['SUB_PKKEY'] as $x=>$sub_pkkey){
					unset($sub_data);

					$sub_data['REFNO'] = $invoice_pkkey;
					if($sub_pkkey != "")$sub_data['PKKEY'] = $sub_pkkey;
					if(isset($post['SUB_GOLD'][$x])) $sub_data['GOLD'] = $post['SUB_GOLD'][$x];
                    if(isset($post['SUB_DESCRIPT'][$x])) $sub_data['DESCRIPT'] = $post['SUB_DESCRIPT'][$x];
                    if(isset($post['SUB_WEIGHT'][$x])) $sub_data['WEIGHT'] = $post['SUB_WEIGHT'][$x];
                    if(isset($post['SUB_UNIT_W'][$x])) $sub_data['UNIT_W'] = $post['SUB_UNIT_W'][$x];
                    if(isset($post['SUB_RATE'][$x])) $sub_data['RATE'] = $post['SUB_RATE'][$x];
                    if(isset($post['SUB_GOLDPRICE'][$x])) $sub_data['GOLDPRICE'] = $post['SUB_GOLDPRICE'][$x];
                    if(isset($post['UNIQID'])) $sub_data['UNIQID'] = $post['UNIQID'];

					$return = $this->adjitem_model->save($sub_data);
					
				}
			}
			
			if(isset($post['DEL_SUB_PKKEY'])){
				foreach($post['DEL_SUB_PKKEY'] as $del_pkkey){
					$this->adjitem_model->remove($del_pkkey);
				}
			}

		}
		
		if($return['pk'] != "" && isset($post['UNIQID'])){
            $uniqid_array = $this->adjitem_model->get_data(array(
                'condition' => "<T>.UNIQID = '".$post['UNIQID']."'",
            ));

            foreach($uniqid_array as $v){
                unset($data_uniqid);
                $data_uniqid['PKKEY'] = $v->PKKEY;
                $data_uniqid['REFNO'] = $invoice_pkkey;

                $this->adjitem_model->save($data_uniqid);
            }
        }
		
		if($return['error'] == ""){
            $action = ! isset($post['REFNO'])? "Create":"Update";
			$this->session->set_flashdata('success', $action." Successful!");
		}
		else{
			$this->session->set_flashdata('error', $return['error']);
		}
		
		if(isset($post['REFNO'])){
			$redirect_params = "";
			$redirect_params .= "/edit/".$post['REFNO'];
        	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 get_gold_detail(){
        $this->load->model("gold_model");

        $post = $this->input->post();

        $info = "";
        $condition = "";

        if($this->input->post('id') != ""){
            $condition = $this->fm->append($condition, "<T>.CODE = '".$post['id']."' ");
            
            $additional_join = ""; 
            $additional_join .= "LEFT JOIN TAXCODE ON TAXCODE.CODE = <T>.TAXCODE";
            $data = $this->gold_model->get_data( array(
                'condition' => $condition,
                'select' => "<T>.CODE, <T>.NAME, <T>.DESCRIPT, <T>.RATE, <T>.TAXCODE, TAXCODE.PERCEN",
                'sort' => "<T>.CODE DESC",
                'limit' => "1",
                'additional_join' => $additional_join,

            ));
        }

        echo json_encode($data);
    }
	
	public function delete(){
        $this->load->model("adj_model");
        $this->load->model("adjitem_model");
		$post = $this->input->post();
		
		//To prevent loss---
		$this->fm->keep_all_page_filter();
		//------------------
		
        $pk = $this->adj_model->sql_get_pk();
        if(isset($post[$pk]) && $this->adj_model->remove($post[$pk])){
        	$sub_array = $this->adjitem_model->get_data(array(
				'condition' => "<T>.REFNO = '".$post[$pk]."' ",
			));
			if(count($sub_array) > 0){
				foreach($sub_array as $sub){
					$this->adjitem_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("adj_model");
		$post = $this->input->post();
		
		//To prevent loss---
		$this->fm->keep_all_page_filter();
		//------------------
		
		if($this->input->post('unique') != ""){
			$condition = "<T>.REFNO = '".$this->fm->str_esc($post['unique'], 1)."'";
			if(isset($post['pk'])) $condition .= " AND <T>.<PK> != '".$post['pk']."'";
			$data_array = $this->adj_model->get_data(array(
				'condition' => $condition,
			));
			
			if(count($data_array) == 0){
				echo "1";
			}
		}
	}

    public function load_print(){
        $this->load->model("adj_model");
        $this->load->model("adjitem_model");
        $this->load->model("company_profile_model");
        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------

        $data = array();
        $user = $this->fm->get_current_user();
        $data['username'] = $user->NAME;
        $data['userid'] = $user->CODE;

        if($this->input->post('REFNO') != ""){
            $data_array = $this->adj_model->get_data(array(
                'condition' => "<T>.<PK> = '".$this->fm->str_esc($post['REFNO'], 1)."'",
              
            ));
            
            if(count($data_array) > 0){
                $data['data'] = $data_array[0];
                
                $data['list'] = $this->adjitem_model->get_data(array(
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                    'sort' => "<T>.REFNO",
                    '' => "",
                ));

                //Calculate total
                $gold = $this->adjitem_model->get_data(array(
                    'select' => "<T>.GOLDPRICE",
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                ));

                //Total gold price amount (Excluded gst)
                $gold_total = array();
                foreach($gold as $lv){
                    array_push($gold_total, $lv->GOLDPRICE);
                }
                $data['gold_total'] = array_sum($gold_total);
                
                //Company Profile
                $company = $this->company_profile_model->get_data(array(
                    'condition' => "",
                ));
                $data['company'] = $company[0];
                
                $this->load->view($this->router->fetch_class()."/load_print", $data);
                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("adj_model");
		$this->load->model("adjitem_model");

		$post = $this->input->post();
		
//		print_r($post);
		
		//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('REFNO') != ""){
			$condition = $this->fm->append($condition, "<T>.REFNO LIKE '%".$this->fm->str_esc($post['REFNO'], 1)."%'");
		}

		
		//---------
		
		$data['header_array'] = array(
			array(
				'description' => "#",
				'style' => "width: 1%; white-space: nowrap; text-align: center;",
				'sort' => "",
			),

			array(
				'description' => "Ref.No",
				'style' => "width: 1%; white-space: nowrap; text-align: center;",
				'sort' => "<T>.REFNO DESC",
			),

            array(
                'description' => "Date",
                'style' => "width: 1%; white-space: nowrap; text-align: center;",
                'sort' => "<T>.DATE",
            ),

            array(
                'description' => "Reason",
                'style' => "width: 1%; white-space: nowrap; text-align: center;",
                'sort' => "<T>.REASON",
            ),

            array(
                'description' => "Remarks",
                'style' => "width: 1%; white-space: nowrap; text-align: center;",
                'sort' => "<T>.REMARKS",
            ),

			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->adj_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'];

		$data['list'] = $this->adj_model->get_data(array(
			'condition' => $condition,
			'limit' => $config['per_page'],
			'offset' => $config['start'],
			'sort' => $sort,
		));
		$data['config'] = $config;
		
		//Access---
        $access_array = $this->fm->get_access(array(87, 88, 89));
        $data['can_create'] = isset($access_array[87]);
        $data['can_edit'] = isset($access_array[88]);
        $data['can_delete'] = isset($access_array[89]);
        //---------
		
		//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->view($this->router->fetch_class()."/load_data", $data);
	}
}