<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Hauling_recap extends MY_Controller {

	function __construct()
	{
		parent::__construct();
		date_default_timezone_set('Asia/Jakarta');
		$this->load->model('hauling_model');
		$this->load->model('hauling_recap_model');
		$this->load->model('master/vendor_model');
		$this->load->model('sealmis/misel_purch_order_model');
		$this->load->model('sealmis/misel_purch_order_detail_model');
		$this->load->model('sealmis/misel_vendor_model');
		$this->bc->set_title('Hauling Recap');
		$this->bc->add('Hauling',base_url().'hauling');
		$this->bc->add('Recap',base_url().'hauling/hauling_recap');
	}
	
	public function index()
	{
		$data = array(
			'content' => 'recap/main'
		);
		$this->load->view('tpl',$data);
	}

    public function load_hauling_process()
	{
		
		$data = array(
			'content' => 'recap/process',
		);
		$this->load->view($data['content'], $data);
	}

	public function load_hauling_report()
	{
		
		$data = array(
			'content' => 'recap/report',
		);
		$this->load->view($data['content'], $data);
	}

    public function listPageProcess()
	{
		$draw = $this->input->post('draw') ?: 0;
		$start = $this->input->post('start');
		$rowperpage  = $this->input->post('length') ?: 0;
		$columnIndex   = $_POST['order'][0]['column'];
		$columnName    = $_POST['columns'][$columnIndex]['data'];
		$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
		$searchValue = $_POST['search']['value']; // Search value
		$filter_vendor 	= $this->input->post('filter_vendor');
		$date_start = validate_input($this->input->post('filter_date_start'),
            array(
                'name' => 'Date Start',
                'required' => true,
                'type' => 'date',
            )
        );
		$date_end = validate_input($this->input->post('filter_date_end'),
            array(
                'name' => 'Date End',
                'required' => true,
                'type' => 'date',
            )
        );
		$filter_date_start 	= getSQLDate($date_start);
		$filter_date_end 	= getSQLDate($date_end);

		$where = array();

		if ($filter_date_start) {
			$where['hauling_date >= ' . quotedStr($filter_date_start) . ''] = null;
		}
		if ($filter_date_end) {
			$where['hauling_date <= ' . quotedStr($filter_date_end) . ''] = null;
		}

		if ($filter_vendor){
			$where['tbl.vendor_mis'] = $filter_vendor;
		}

		$where["(
			tbl.hauling_number LIKE '%$searchValue%'
			OR tbl.vehicle_id LIKE '%$searchValue%'
			OR tbl.vendor_mis LIKE '%$searchValue%'
			OR tbl.vendor_id LIKE '%$searchValue%'
			OR tbl.vehicle_number LIKE '%$searchValue%'
			OR sts.status LIKE '%$searchValue%'
		)"] = NULL;

		$this->hauling_model->set_where($where);
		
		$list_count = $this->hauling_model->count();
		$this->hauling_model->set_limit($rowperpage);
		$this->hauling_model->set_offset($start);
		$this->hauling_model->set_order(array($columnName => $columnSortOrder));
		$list_data  = $this->hauling_model->get_list();
		// echo $this->db->last_query(); die;
			
		$response = array(
			"post" => $this->input->post(),
			"draw" => intval($draw),
			"iTotalRecords" => $list_count,
			"iTotalDisplayRecords" => $list_count,
			"aaData" => $list_data->result_array()
		);

		header('Content-type: application/json');
		echo json_encode($response);
	}

    public function listPageReport()
	{
		$draw = $this->input->post('draw') ?: 0;
		$start = $this->input->post('start');
		$rowperpage  = $this->input->post('length') ?: 0;
		$columnIndex   = $_POST['order'][0]['column'];
		$columnName    = $_POST['columns'][$columnIndex]['data'];
		$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
		$searchValue = $_POST['search']['value']; // Search value
		$filter_vendor 	= $this->input->post('filter_vendor');
		$date_start = validate_input($this->input->post('filter_date_start'),
            array(
                'name' => 'Date Start',
                'required' => true,
                'type' => 'date',
            )
        );
		$date_end = validate_input($this->input->post('filter_date_end'),
            array(
                'name' => 'Date End',
                'required' => true,
                'type' => 'date',
            )
        );
		$filter_date_start 	= getSQLDate($date_start);
		$filter_date_end 	= getSQLDate($date_end);

		$where = array();

		if ($filter_date_start) {
			$where['hauling_recapdate >= ' . quotedStr($filter_date_start) . ''] = null;
		}
		if ($filter_date_end) {
			$where['hauling_recapdate <= ' . quotedStr($filter_date_end) . ''] = null;
		}

		if ($filter_vendor){
			$where['tbl.vendor_mis'] = $filter_vendor;
		}

		$where["(
			tbl.hauling_recapnum LIKE '%$searchValue%'
			OR tbl.hauling_number LIKE '%$searchValue%'
            OR sts.status LIKE '%$searchValue%'
		)"] = NULL;

		$this->hauling_recap_model->set_where($where);
		
		$list_count = $this->hauling_recap_model->count();
		$this->hauling_recap_model->set_limit($rowperpage);
		$this->hauling_recap_model->set_offset($start);
		$this->hauling_recap_model->set_order(array($columnName => $columnSortOrder));
		$list_data  = $this->hauling_recap_model->get_list();
		// echo $this->db->last_query(); die;
			
		$response = array(
			"post" => $this->input->post(),
			"draw" => intval($draw),
			"iTotalRecords" => $list_count,
			"iTotalDisplayRecords" => $list_count,
			"aaData" => $list_data->result_array()
		);

		header('Content-type: application/json');
		echo json_encode($response);
	}

	function recap_data()
    {
        $filter_vendor 	= $this->input->post('t_filter_vendor_process');
		$date_start = validate_input($this->input->post('t_filter_date_start_process'),
            array(
                'name' => 'Date Start',
                'required' => true,
                'type' => 'date',
            )
        );
		$date_end = validate_input($this->input->post('t_filter_date_end_process'),
            array(
                'name' => 'Date End',
                'required' => true,
                'type' => 'date',
            )
        );
		$filter_date_start 	= getSQLDate($date_start);
		$filter_date_end 	= getSQLDate($date_end);

		$where = array();

		if ($filter_date_start) {
			$where['hauling_date >= ' . quotedStr($filter_date_start) . ''] = null;
		}
		if ($filter_date_end) {
			$where['hauling_date <= ' . quotedStr($filter_date_end) . ''] = null;
		}

		if ($filter_vendor){
			$where['tbl.vendor_mis'] = $filter_vendor;
		}

        $where['tbl.hauling_status'] = 2;

        $this->hauling_model->set_where($where);
        $hauling_recap_data = $this->hauling_model->get_list_summary();
        
        $this->db->trans_start();

        if ($hauling_recap_data->num_rows() > 0){
			foreach($hauling_recap_data->result_array() as $row)
			{
                $prefix =  date('y') . date('m')  . '.HLR.';
                $transnum = $this->hauling_recap_model->gen_transaction_number($prefix);
                $vendor = $row['vendor_mis'];

				$data_detail					 = array();
				$data_detail['hauling_recapnum'] = $transnum;
				$data_detail['vendor_mis']	 	 = $row['vendor_mis'];
				$data_detail['gross_weight'] 	 = $row['gross_weight'];
				$data_detail['tare_weight'] 	 = $row['tare_weight'];
				$data_detail['net_weight'] 		 = $row['net_weight'];
				$data_detail['hauling_recapdate'] = date('Y-m-d');
				$data_detail['hauling_recaptime'] = date('H:i:s');
				$data_detail['hauling_status']   = 3;
				// simpan detail
                
				$save = $this->hauling_recap_model->save($data_detail);

                if($save){
                    $this->hauling_model->update_header($transnum,$filter_date_start,$filter_date_end,$vendor);
				// kirim ke misel
					$data_vendor = $this->vendor_model->get(array('vendor_mis'=>$vendor));
					$ongkos = $data_vendor['stockr_cost'];
					$qty = $data_detail['net_weight'];
					$this->send_to_misel($transnum,$vendor,$data_detail['hauling_recapdate'],$ongkos,$qty);
                }
			}
		}

        $this->db->trans_complete();

		if ($this->db->trans_status() === false) {
			$this->db->trans_rollback();
			$error = $this->db->error();
			$this->error($error);
		} else {
			$this->db->trans_commit();
			$this->success('Simpan Berhasil');
		}
    }

	public function print_doc_pdf($p_transnum='',$debug=0)
	{
		$trx_num = $this->input->get('transnum')?:decode($p_transnum);
				
		$where_recap = array();
        $where_recap['hauling_recapnum'] = $trx_num;
		$this->hauling_recap_model->set_where($where_recap);
		$listdata_hauling_recap = $this->hauling_recap_model->get_list_get($where_recap);

		$where = array();
        $where['hauling_recapnum'] = $trx_num;
		$this->hauling_model->set_where($where);
		$countdata_hauling = $this->hauling_model->count($where);
		$listdata_hauling = $this->hauling_model->get_list($where);

		$start_date = $this->hauling_model->get_startdate($trx_num);
		$end_date = $this->hauling_model->get_enddate($trx_num);

		$data = array(
			'content' 	=> 'recap/print', 
			'trxnum'	=> $trx_num,
			'data_hauling' => $listdata_hauling,
			'data_hauling_recap' => $listdata_hauling_recap,
			'count_hauling' => $countdata_hauling,
			'start_date' => $start_date,
			'end_date' => $end_date,
		);

		$option = array(
			'paper_size' => 'A4' 
		);
		
		$this->load_pdf($data['content'], $data, $option);
	}

	function send_to_misel($recap_number,$vendor,$orderdate,$ongkos,$qty)
	{
		$prefix =  date('y') . date('m')  . '.POJ.';
        $transnum = $this->misel_purch_order_model->gen_transaction_number($prefix);
		$subtotal = $ongkos * $qty ;

		$misel_vendor=$this->misel_vendor_model->get(array('vendor_code' => $vendor));
		$vendorid = $misel_vendor['userid'];

		$this->db->trans_start();

		$data = array();
		$data['pur_order_name'] = 'Jasa Hauling '.$recap_number;
		$data['vendor'] = $vendorid;
		$data['estimate'] = 0;
		$data['pur_order_number'] = $transnum;
		$data['order_date'] = $orderdate;
		$data['status'] = 1;
		$data['approve_status'] = 1;
		$data['datecreated'] = date('Y-m-d');
		$data['days_owed'] = 0;
		$data['subtotal'] = $subtotal;
		$data['total_tax'] = 0;
		$data['total'] = $subtotal;
		$data['addedfrom'] = 17;
		$data['buyer'] = 17;
		$data['status_goods'] = 0;
		$data['discount_type'] = 'after_tax';
		$data['currency'] = 3;
		$data['order_status'] = 'new';
		$data['currency_rate'] = 1;

		$save_header = $this->misel_purch_order_model->save($data);

		if ($save_header) 
		{
			$po = $this->misel_purch_order_model->get(array('pur_order_number' => $transnum));
			$id_header = $po['id']; 

			$data_detail = array();
			$data_detail['pur_order'] = $id_header;
			$data_detail['item_code'] = 7;
			$data_detail['description'] = $recap_number;
			$data_detail['unit_id'] = 6;
			$data_detail['unit_price'] = $ongkos;
			$data_detail['quantity'] = $qty;
			$data_detail['into_money'] = $subtotal;
			$data_detail['total'] = $subtotal;
			$data_detail['discount_%'] = 0;
			$data_detail['discount_money'] = 0;
			$data_detail['total_money'] = $subtotal;
			$data_detail['tax_value'] = 0;
			$data_detail['item_name'] = 'HA003_Ongkos Jasa Hauling';

			$save_detail = $this->misel_purch_order_detail_model->save($data_detail);
		}

		$this->db->trans_complete();

		if ($this->db->trans_status() === false) {
			$this->db->trans_rollback();
			$error = $this->db->error();
			$this->error($error);
		} else {
			$this->db->trans_commit();
			$this->success('Success');
		}
	}

	// function send_email_recap($transnum,$vendor,$email)
	function send_email_recap()
	{
		$this->load->model('sealmis/misel_vendor_model');
		$this->load->model('sealmis/misel_vendor_contacts_model');
		$transnum = $this->input->post('id');
		$data = array();
		$data['subject'] = ' Rekap Data Hauling'; 

		$data_rekap = $this->hauling_recap_model->get(array('hauling_recapnum' => $transnum));
		$vendorid = $data_rekap['vendor_id'];

		$data_vendor_sealmis = $this->misel_vendor_model->get(array('vendor_code' => $vendorid));
		$user_id_vendor = $data_vendor_sealmis['userid'];

		$data_vendor_contacts_sealmis = $this->misel_vendor_contacts_model->get(array('userid' => $user_id_vendor));
		$email_vendor = $data_vendor_contacts_sealmis['email'];

		$config = array();
		$config['protocol'] = 'smtp';
		$config['smtp_host'] = 'ssl://sealmis.com';
		$config['smtp_user'] = 'support@sealmis.com';
		$config['smtp_pass'] = 'Seal@0773';
		$config['smtp_port'] = 465;
		$config['smtp_timeout'] = 100;
		// $config['smtp_crypto'] = 'ssl';
		$config['wordwrap'] = TRUE;
		$config['wrapchars'] = 76;
		$config['mailtype'] = 'html';
		$config['charset'] = 'utf-8';
		$config['validate'] = FALSE;
		$config['priority'] = 3;
		$config['crlf'] = "\r\n";
		$config['newline'] = "\r\n";
		$config['bcc_batch_mode'] = FALSE;
		$config['bcc_batch_size'] = 200;

        $this->email->initialize($config);
        $this->email->from('support@sealmis.com','seal');
        // $this->email->to($get_operator['Email']?$get_operator['Email']:$get_customer['Email']);  asalnya ganti dulu ke ict
        $this->email->to($email_vendor);
		// matikan dulu email
		// $this->email->cc('indrasyah@elcorps.com, suprihatin@elcorps.com, account.sales@elcorps.id, data.analytics@elcorps.id, ict@elcorps.id');
		// $this->email->bcc(''); 
		// $data['email_user'] 		= $get_operator['Email']?$get_operator['Email']:$get_customer['Email'];  asalnya ganti dulu ke ict
		// $data['email_user'] 	= 'ict@sealmis.com';
		$data['email_user'] 	= $email_vendor;
		$data['transnum']		= $transnum;
		
		
		$url=site_url();
		$message = $this->load->view('recap/format_email_recap',$data,TRUE);
		
		$this->email->subject($data['subject']);
        $this->email->message($message);
		// $attachment_url	= base_url().'excel_temp/'.$transnum.'.xls';
		// $attachment_url	= base_url().'pdf_temp/'.$transnum.'.pdf';
		// $this->email->attach($attachment_url);
		$this->success('Proses Kirim email Berhasil');
		// command dulu
		if(!$this->email->send()){
			$this->result['field']='';
			$this->result['error']= 'Failed sent email !';
			$this->result['header']='error';
			$this->result['success']='';
			// $this->error('failed to send email');
			// echo json_encode($this->result);
			// return;
			return true;
	    	}else{
			$this->result['field']='';
			$this->result['error']='';
			$this->result['header']='success';
			$this->result['success']='Email has been sent !';
			return true;

		}	
	}

}