<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class purchase 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("purchase_model");
        $this->load->model("puritem_model");

        $post = $this->input->post();
        
        //To prevent loss---
        $this->fm->keep_all_page_filter();
        //------------------
        
        $data = array();
        
        //Access---
        $access_array = $this->fm->get_access(array(82, 83, 84));
        $data['can_create'] = isset($access_array[82]);
        $data['can_edit'] = isset($access_array[83]);
        $data['can_delete'] = isset($access_array[84]);
        //---------
        
        $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->purchase_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->puritem_model->get_data(array(
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                    'sort' => "",
                    '' => "",
                    'additional_select' => "GOLD.NAME AS GOLD_NAME, GOLD.BAL",
                    'additional_join' => $additional_join,
                ));


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

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

                //Total gold weight
                $gold_total = array();
                foreach($gold as $lv){
                    array_push($gold_total, $lv->WEIGHT);
                }
                $data['gold_total'] = array_sum($gold_total);

                //Total gold GST
                $gold_gst = array();
                foreach($gold as $lv){
                    array_push($gold_gst, $lv->GST);
                }
                $data['gold_gst'] = array_sum($gold_gst);

                //Total gold Amount
                $gold_amt = array();
                foreach($gold as $lv){
                    array_push($gold_amt, $lv->AMT);
                }
                $data['gold_amt'] = array_sum($gold_amt);


            }
        }

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

        $this->load->model("tt_model");
        $data['all_tt'] = $this->tt_model->get_data( array(
            'sort' => "<T>.TT",
            '' => "",
        ));

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

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

        $this->load->model("taxcode_model");
        $data['all_taxcode'] = $this->taxcode_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",
            '' => "",
        ));

        $this->load->model("paytype_model");
        $data['all_paytype'] = $this->paytype_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("purchase_model");
        $this->load->model("puritem_model");
        $this->load->model("gold_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->purchase_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['SUB_TAXCODE'][$x])) $sub_data['TAXCODE'] = $post['SUB_TAXCODE'][$x];
                    if(isset($post['SUB_PERCEN'][$x])) $sub_data['PERCEN'] = $post['SUB_PERCEN'][$x];
                    if(isset($post['SUB_GST'][$x])) $sub_data['GST'] = $post['SUB_GST'][$x];
                    if(isset($post['SUB_AMT'][$x])) $sub_data['AMT'] = $post['SUB_AMT'][$x];
                    if(isset($post['SUB_INCLUSIVE'][$x])) $sub_data['INCLUSIVE'] = $post['SUB_INCLUSIVE'][$x];
                    if(isset($post['UNIQID'])) $sub_data['UNIQID'] = $post['UNIQID'];

					$return = $this->puritem_model->save($sub_data);
					
				}

                foreach($sub_post['SUB_PKKEY'] as $x=>$sub_pkkey){
                    unset($sub_golddata);
                    if(isset($post['SUB_GOLD'][$x])) $sub_golddata['CODE'] = $post['SUB_GOLD'][$x];
                    if(isset($post['SUB_BAL'][$x])) $sub_golddata['BAL'] = $post['SUB_BAL'][$x];

                    $this->gold_model->save($sub_golddata);
                }
			}
			
			if(isset($post['DEL_SUB_PKKEY'])){
				foreach($post['DEL_SUB_PKKEY'] as $del_pkkey){
					$this->puritem_model->remove($del_pkkey);
				}
			}

		}
		
		if($return['pk'] != "" && isset($post['UNIQID'])){
            $uniqid_array = $this->puritem_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->puritem_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, <T>.BAL",
                'sort' => "<T>.CODE DESC",
                'limit' => "1",
                'additional_join' => $additional_join,

            ));
        }

        echo json_encode($data);
    }

    public function get_tax_gold(){
        $this->load->model("taxcode_model");

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

        $tax = "";
        $condition = "";
        if($this->input->post('TAXCODE') != ""){
            $condition = $this->fm->append($condition, "<T>.CODE = '".$post['TAXCODE']."' ");
        }
        
        $data = $this->taxcode_model->get_data( array(
            'condition' => $condition,
        ));
        
        if(count($data) > 0){
            $tax = $data[0]->PERCEN;
        }
        echo $tax;
    }
	
	public function delete(){
        $this->load->model("purchase_model");
        $this->load->model("puritem_model");
		$post = $this->input->post();
		
		//To prevent loss---
		$this->fm->keep_all_page_filter();
		//------------------
		
        $pk = $this->purchase_model->sql_get_pk();
        if(isset($post[$pk]) && $this->purchase_model->remove($post[$pk])){
        	$sub_array = $this->puritem_model->get_data(array(
				'condition' => "<T>.REFNO = '".$post[$pk]."' ",
			));
			if(count($sub_array) > 0){
				foreach($sub_array as $sub){
					$this->puritem_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("purchase_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->purchase_model->get_data(array(
				'condition' => $condition,
			));
			
			if(count($data_array) == 0){
				echo "1";
			}
		}
	}

    public function load_print(){
        $this->load->model("purchase_model");
        $this->load->model("puritem_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') != ""){

            $additional_join = ""; 
            $additional_join .= "LEFT JOIN CREDITOR ON CREDITOR.CODE = <T>.CREDITOR";
            $data_array = $this->purchase_model->get_data(array(
                'condition' => "<T>.<PK> = '".$this->fm->str_esc($post['REFNO'], 1)."'",
                'additional_select' => "CREDITOR.NAME AS CREDITOR_NAME, CREDITOR.ADD1 AS CREDITOR_ADD1",
                'additional_join' => $additional_join,
              
            ));
            
            if(count($data_array) > 0){
                $data['data'] = $data_array[0];
                
                $additional_join = ""; 
                $additional_join .= "LEFT JOIN PURCHASE ON PURCHASE.REFNO = <T>.REFNO";
                $data['list'] = $this->puritem_model->get_data(array(
                    'condition' => "<T>.REFNO = '".$data['data']->REFNO."'",
                    'sort' => "<T>.REFNO",
                    'additional_select' => "",
                    'additional_join' => $additional_join,  
                    '' => "",
                ));

                //Calculate total
                $gold = $this->puritem_model->get_data(array(
                    'select' => "<T>.GOLDPRICE, <T>.GST, <T>.AMT",
                    '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);

                //Total gold GST
                $gold_gst = array();
                foreach($gold as $lv){
                    array_push($gold_gst, $lv->GST);
                }
                $data['gold_gst'] = array_sum($gold_gst);

                //Total gold Amount
                $gold_amt = array();
                foreach($gold as $lv){
                    array_push($gold_amt, $lv->AMT);
                }
                $data['gold_amt'] = array_sum($gold_amt);

                //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("purchase_model");
		$this->load->model("puritem_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' => "Creditor",
                'style' => "width: 1%; white-space: nowrap; text-align: center;",
                'sort' => "<T>.CREDITOR",
            ),

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

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

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

		$additional_join = ""; 
        $additional_join .= "LEFT JOIN TT ON TT.TT = <T>.TT";
        $additional_join .= " LEFT JOIN STAFF ON STAFF.CODE = <T>.STAFF";
        $additional_join .= " LEFT JOIN CREDITOR ON CREDITOR.CODE = <T>.CREDITOR";
		$data['list'] = $this->purchase_model->get_data(array(
			'condition' => $condition,
			'limit' => $config['per_page'],
			'offset' => $config['start'],
			'sort' => $sort,
            'additional_select' => "TT.TTNAME, STAFF.NAME AS STAFF_NAME, CREDITOR.NAME AS CREDITOR_NAME",
            'additional_join' => $additional_join,
		));
		$data['config'] = $config;
		
		//Access---
        $access_array = $this->fm->get_access(array(82, 83, 84));
        $data['can_create'] = isset($access_array[82]);
        $data['can_edit'] = isset($access_array[83]);
        $data['can_delete'] = isset($access_array[84]);
        //---------
		
		//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);
	}
}