https://t.me/RX1948
Server : Apache/2.4.18 (Ubuntu)
System : Linux canvaswebdesign 3.13.0-71-generic #114-Ubuntu SMP Tue Dec 1 02:34:22 UTC 2015 x86_64
User : oppastar ( 1041)
PHP Version : 7.0.33-0ubuntu0.16.04.15
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,
Directory :  /var/www/rabbithabit.com/public_html/application/controllers/admin/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //var/www/rabbithabit.com/public_html/application/controllers/admin/Orders.php
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Orders extends Admin_Controller {
		
	function __construct() {
		parent::__construct();	
		$this->load->model('order_m');  
		$this->load->model('order_detail_m'); 
		$this->load->model('configuration_m');  
		$this->load->model('customer_m');  			 
	}

	public function print_invoice_pdf($id) {
		
		$q_order = $this->order_m->get_order($id);  
		$q_order_details = $this->order_detail_m->get_orders_detail($id); 

		if ($id == null || $q_order == null) {
			show_404();
		}

		//get website data
		$website_data = $this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1)->get()->row();

		$email_data['website_name'] = $website_data->website_name;
		$email_data['logo'] = $website_data->logo;

		$customer_id = $q_order->customer_id; 

		$this->db->select('name,phone,type,email')->from('customers')->where('id_customers', $customer_id);

		$email_data['customer'] = $this->db->get()->row(); 
		$email_data['email'] = $email_data['customer']->email;  
		$email_data['emails'] = $this->configuration_m->get_emails();

		$payment_type = $q_order->payment_type;
		if($payment_type == 'bank transfer BCA'){
			$email_data['bank'] = $this->db->select('bank')->from('configuration')->where('id_configuration', 1)->get()->row()->bank;
		
		} elseif($payment_type == 'bank transfer MANDIRI'){
			$email_data['bank'] = $this->db->select('bank1')->from('configuration')->where('id_configuration', 1)->get()->row()->bank1;
		}

		$email_data['subject'] = 'Order Confirmation'; 

		//get order detail and customer detail
		$email_data['order'] = $q_order;
		$email_data['order_details'] = $q_order_details;

		//get vouchers detail
		if ($q_order->redeemed_voucher_code != null) {
		  	$email_data['chosen_voucher_code'] = $q_order->redeemed_voucher_code;
		  	$email_data['chosen_voucher_type'] = $q_order->redeemed_voucher_type;
			$email_data['chosen_voucher_discount'] = $q_order->redeemed_voucher_value;  
			$email_data['redeemed_voucher_amount'] = $q_order->redeemed_voucher_amount;  
		 }   

		//get shipping fee total
		// $email_data['carrier_name'] = $this->session->userdata('carrier_name'); 
		// $email_data['total_shipping_fee'] = $this->session->userdata('total_shipping_fee'); 

		//add tax to email, if exist..
		if($q_order->ppn != '0.00') {
			$email_data['tax'] = $q_order->ppn;
		}

		//add point reward to email, if exist..
		// if($this->session->userdata('chosen_point')) {
		// 	$email_data['chosen_point'] = $this->session->userdata('chosen_point');
		// 	$email_data['chosen_point_discount'] = $this->session->userdata('chosen_point_discount');
		// }

		$view_file = 'shipping_invoice_pdf';
		// $view_file = 'email/english/bank_transfer_english';
		// $this->send_email($view_file, $email_data);

		$this->load->library('dompdf_gen');
		$html = $this->load->view($view_file, $email_data ,true);
		
		// echo $html;
		// die();

		$this->dompdf->load_html($html);
		$this->dompdf->set_paper('A4','potret');
		$this->dompdf->render(); 
		$this->dompdf->stream('shipping_invoice_pdf.pdf', array("Attachment" => 0));
		$output = $this->dompdf->output(); 
		$file_to_save = 'uploads/pdf/shipping_invoice_pdf.pdf'; 
		file_put_contents($file_to_save, $output);
	}	

	public function alldata() {

		$draw=$_REQUEST['draw'];
        $length=$_REQUEST['length'];
        $start=$_REQUEST['start'];
        $search=$_REQUEST['search']["value"];
        $total=$this->db->count_all_results("users");

        $filterkey = $this->security->xss_clean($this->input->post('filterkey'));
        $dataenter = $this->security->xss_clean($this->input->post('dataenter'));

        $output=array();

        $output['draw']=$draw;
        $output['recordsTotal']=$output['recordsFiltered']=$total;
        $output['data']=array();

        if($filterkey == 'date'){
        	$ex = explode('_', $dataenter);
        	$startdate = $ex[0].' 00:00:00';
        	$enddate = $ex[1].' 23:59:59';
        	$dataenter = $startdate.'_'.$enddate;
        }

        $query = $this->order_m->filterdata($search, $filterkey, $dataenter, $this->session->userdata('admin')['id'], $length, $start);

        $jum = $this->order_m->filterdata($search, $filterkey, $dataenter, $this->session->userdata('admin')['id'],'','');
        $output['recordsTotal']=$output['recordsFiltered']=$jum->num_rows();

        $nomor_urut=$start+1;
        foreach ($query->result() as $order) {
        	$final_grand_total = 0;
            $finalshippingfee = 0;
            $calculate_finalshippingfee = $order->shipping_fee - $order->free_shipping_fee;
            if($calculate_finalshippingfee > 0){
                $finalshippingfee = $calculate_finalshippingfee;
            }
            $grand_total =  ($order->total_amount - $order->redeemed_voucher_amount - $order->minus_reward_amount)+($finalshippingfee);
            if($grand_total > 0){
                $final_grand_total = $grand_total;
            } else {
				//check if finalshippingfee is > 0
				if($finalshippingfee > 0) {
					$final_grand_total = $finalshippingfee;
				}
			}  

			//check this order if it does contain indent item
            $count_indent = $this->db->select('is_backorder')->from('orders_detail')->where('orders_id', $order->id_orders)->where('is_backorder', 'yes')->get()->num_rows();

            if($count_indent > 0) {
                //indent exist.
                $is_indent = 'ya';
            } else {
                $is_indent = 'tidak';
            } 

            $wareid = $this->order_m->warestats($order->id_orders);
			$status = $this->order_m->paystats($order->payment_status); 
			
			if($order->doku_payment_channel == 15) {
				$doku_payment_channel = 'Credit Card';
				$paycon = $order->doku_approval_result . ' ' . $doku_payment_channel;
			} else {
				$paycon = $this->order_m->paymettype($order->payment_type,$order->payment_confirm,$order->payment_status_message);
			}
			
            $output['data'][]= array(
                $nomor_urut,
                $order->id_orders,
                date('j M Y H:i:s', strtotime($order->order_date)),
                ucwords($order->recipient_name),
                '<div style="text-align: right;">'.number_format($final_grand_total).'</div>',
                ucwords($order->payment_type),
                $status,
                $paycon,
                //$wareid,
                $is_indent,
                '<a style="text-decoration: underline;" href="'.base_url('admin/orders/view') . '/' . $order->id_orders.'">Lihat</a>', 
                $order->created_by
            );
            $nomor_urut++;
        }

        echo json_encode($output);
	}
	
	//this is to list all orders
	public function index() { 
		
		//pagination in action. 100 results per page
		$this->load->library('pagination');
		$config['base_url'] = base_url() . 'admin/orders/index';
		$config['per_page'] = 100;
		$config["uri_segment"] = 4; 

		//fetch all orders
		$config['total_rows'] = $this->order_m->record_count(); 
		$this->pagination->initialize($config);
   		$this->data['orders'] = $this->order_m->get_all_orders($config["per_page"], 
		$this->uri->segment(4));
	
		$this->data['total_sales_order'] = $this->order_m->record_count();	
		$this->data['marketplaces']	= $this->db->distinct()->select('marketplace_name')->from('orders')->where('marketplace_name !=',null)->order_by('marketplace_name','ASC')->get()->result();
		$this->data['customers'] 	= $this->db->distinct()->select('customer_id')->from('orders')->order_by('id_orders','ASC')->get()->result();			
		$this->data['product']	= $this->db->select('title,id_products')->from('products')->get()->result();	  
		//load view
		$this->data['subview'] = 'admin/orders/index';
		$this->load->view('admin/templates/header', $this->data_header); 
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer');	
    }

	//get all successful orders for specific customer only
	public function customer($customer_id) { 
		
		//pagination in action. 20 results per page
		$this->load->library('pagination');
		$config['base_url'] = base_url() . 'admin/orders/customer';
		$config['per_page'] = 100;
		$config['uri_segment'] = 4; 
 
		//check number of orders
		$this->db->select('id_orders');
		$this->db->from('orders');
		$this->db->where('customer_id', $customer_id);
		$this->db->where('(payment_status=3 or payment_status=4 or payment_status=5)');
		$config['total_rows'] = $this->db->get()->num_rows();
		$this->pagination->initialize($config);

		//get all orders
		$this->db->select('*');
		$this->db->from('orders');
		$this->db->where('customer_id', $customer_id);
        $this->db->where('(payment_status=3 or payment_status=4 or payment_status=5)');
		$this->db->order_by('order_date', 'DESC');
		//$this->db->limit($config['per_page'], $this->uri->segment($config['uri_segment']));
   		$this->data['orders'] = $this->db->get()->result();
	
		//get customer data
		$this->db->select('*')->from('customers')->where('id_customers', $customer_id);  
		$this->data['customer'] = $this->db->get()->row();

		//load view
		$this->data['subview'] = 'admin/orders/customer_orders';
		$this->load->view('admin/templates/header', $this->data_header); 
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer');	 
    }

    /*filter order by*/
    public function filter_order_by() {
    	if($this->security->xss_clean($this->input->post('filter_key'))){
    		$filter_key = $this->security->xss_clean($this->input->post('filter_key'));
    	}
    	else{
    		$filter_key	= $this->session->userdata('filter_key');
    	}
    	
    	$this->data['marketplaces']	= $this->db->distinct()->select('marketplace_name')->from('orders')->where('marketplace_name !=',null)->order_by('marketplace_name','ASC')->get()->result();
    	$this->data['customers'] 	= $this->db->distinct()->select('customer_id')->from('orders')->order_by('id_orders','ASC')->get()->result();
    	//pagination in action. 100 results per page
		$this->load->library('pagination');
		$config['base_url'] = base_url() . 'admin/orders/filter_order_by';
		$config['per_page'] = 100;
		$config["uri_segment"] = 4; 

    	if($filter_key == 'order_id'){
    		//fetch all orders
    		$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('id_orders',$this->security->xss_clean($this->input->post('order_id')));
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows(); 

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('id_orders',$this->security->xss_clean($this->input->post('order_id')));
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
	   		$this->data['orders'] = $this->db->get()->result(); 
    	}
    	elseif($filter_key == 'voucher'){
    		$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('redeemed_voucher_code !=',null);
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows(); 

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('redeemed_voucher_code !=',null);
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
	   		$this->data['orders'] = $this->db->get()->result(); 
    	}
    	elseif($filter_key == 'payment_status'){
    		if($this->security->xss_clean($this->input->post('payment_status'))){
    			$this->session->unset_userdata('filter_payment_status');
    			$payment_status = $this->security->xss_clean($this->input->post('payment_status'));
    		}
    		else{
    			$payment_status = $this->session->userdata('filter_payment_status');
    		}

    		$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('payment_status',$payment_status);
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows(); 

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('payment_status',$payment_status);
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
	   		$this->data['orders'] = $this->db->get()->result();

	   		$this->session->set_userdata('filter_payment_status',$payment_status);
    	}
    	elseif($filter_key == 'payment_type'){
    		if($this->security->xss_clean($this->input->post('payment_type'))){
    			$this->session->unset_userdata('filter_payment_type');
    			$payment_type = $this->security->xss_clean($this->input->post('payment_type'));
    		}
    		else{
    			$payment_type = $this->session->userdata('filter_payment_type');
    		}

    		$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('payment_type',$payment_type);
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows(); 

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('payment_type',$payment_type);
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
	   		$this->data['orders'] = $this->db->get()->result();

	   		$this->session->set_userdata('filter_payment_type',$payment_type);
    	}
    	elseif($filter_key == 'flashsale'){
    		$this->db->select('
    			orders.id_orders,
    			orders.order_date,
    			orders.recipient_name,
    			orders.total_amount,
    			orders.redeemed_voucher_amount,
    			orders.minus_reward_amount,
    			orders.shipping_fee,
    			orders.free_shipping_fee,
    			orders.payment_status,
    			orders.payment_type,
    			orders.payment_confirm,
    			orders.payment_status_message
    		');
			$this->db->from('orders');
			$this->db->join('orders_detail','orders_detail.orders_id = orders.id_orders');
			$this->db->where('orders_detail.is_flashsale','yes');
			$this->db->order_by('orders.id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows(); 

			$this->pagination->initialize($config);

			$this->db->select('
    			orders.id_orders,
    			orders.order_date,
    			orders.recipient_name,
    			orders.total_amount,
    			orders.redeemed_voucher_amount,
    			orders.minus_reward_amount,
    			orders.shipping_fee,
    			orders.free_shipping_fee,
    			orders.payment_status,
    			orders.payment_type,
    			orders.payment_confirm,
    			orders.payment_status_message
    		');
			$this->db->from('orders');
			$this->db->join('orders_detail','orders_detail.orders_id = orders.id_orders');
			$this->db->where('orders_detail.is_flashsale','yes');
			$this->db->order_by('orders.id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
	   		$this->data['orders'] = $this->db->get()->result(); 
    	}
    	elseif($filter_key == 'sale'){
    		$this->db->select('
    			orders.id_orders,
    			orders.order_date,
    			orders.recipient_name,
    			orders.total_amount,
    			orders.redeemed_voucher_amount,
    			orders.minus_reward_amount,
    			orders.shipping_fee,
    			orders.free_shipping_fee,
    			orders.payment_status,
    			orders.payment_type,
    			orders.payment_confirm,
    			orders.payment_status_message
    		');
			$this->db->from('orders');
			$this->db->join('orders_detail','orders_detail.orders_id = orders.id_orders');
			$this->db->where('orders_detail.is_sale','yes');
			$this->db->order_by('orders.id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows(); 

			$this->pagination->initialize($config);

			$this->db->select('
    			orders.id_orders,
    			orders.order_date,
    			orders.recipient_name,
    			orders.total_amount,
    			orders.redeemed_voucher_amount,
    			orders.minus_reward_amount,
    			orders.shipping_fee,
    			orders.free_shipping_fee,
    			orders.payment_status,
    			orders.payment_type,
    			orders.payment_confirm,
    			orders.payment_status_message
    		');
			$this->db->from('orders');
			$this->db->join('orders_detail','orders_detail.orders_id = orders.id_orders');
			$this->db->where('orders_detail.is_sale','yes');
			$this->db->order_by('orders.id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
	   		$this->data['orders'] = $this->db->get()->result(); 
		}
		elseif($filter_key == "date"){
			if($this->security->xss_clean($this->input->post('start_date'))){
    			$this->session->unset_userdata('filter_start_date');
    			$start_date = $this->security->xss_clean($this->input->post('start_date'));
    		}
    		else{
    			$start_date = $this->session->userdata('filter_start_date');
    		}

    		if($this->security->xss_clean($this->input->post('end_date'))){
    			$this->session->unset_userdata('filter_end_date');
    			$end_date = $this->security->xss_clean($this->input->post('end_date'));
    		}
    		else{
    			$end_date = $this->session->userdata('filter_end_date');
    		}


			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('order_date >=', date('Y-m-d 00:00:00', strtotime($start_date)));
			$this->db->where('order_date <=', date('Y-m-d 23:59:59', strtotime($end_date)));
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('order_date >=', date('Y-m-d 00:00:00', strtotime($start_date)));
			$this->db->where('order_date <=', date('Y-m-d 23:59:59', strtotime($end_date)));
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();

			$this->session->set_userdata('filter_start_date',$start_date);
			$this->session->set_userdata('filter_end_date',$end_date);
		}
		elseif($filter_key == "totalorder"){
			if($this->security->xss_clean($this->input->post('start_amt'))){
    			$this->session->unset_userdata('filter_start_amt');
    			$start_amt = $this->security->xss_clean($this->input->post('start_amt'));
    		}
    		else{
    			$start_amt = $this->session->userdata('filter_start_amt');
    		}

    		if($this->security->xss_clean($this->input->post('end_amt'))){
    			$this->session->unset_userdata('filter_end_amt');
    			$end_amt = $this->security->xss_clean($this->input->post('end_amt'));
    		}
    		else{
    			$end_amt = $this->session->userdata('filter_end_amt');
    		}


			$this->db->select('*');
			$this->db->from('orders');

			if($start_amt <> ""){
				$this->db->where('((`total_amount`+IFNULL(ABS(`sisa_kembali`),0))-IFNULL(`redeemed_voucher_value`,0))+(IFNULL(`shipping_fee`,0)-IFNULL(`free_shipping_fee`,0)) >=', $start_amt);
			}
			if($end_amt <> ""){
					$this->db->where('((`total_amount`+IFNULL(ABS(`sisa_kembali`),0))-IFNULL(`redeemed_voucher_value`,0))+(IFNULL(`shipping_fee`,0)-IFNULL(`free_shipping_fee`,0)) <=', $end_amt);
			}

			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			if($start_amt <> ""){
				$this->db->where('((`total_amount`+IFNULL(ABS(`sisa_kembali`),0))-IFNULL(`redeemed_voucher_value`,0))+(IFNULL(`shipping_fee`,0)-IFNULL(`free_shipping_fee`,0)) >=', $start_amt);
			}
			if($end_amt <> ""){
					$this->db->where('((`total_amount`+IFNULL(ABS(`sisa_kembali`),0))-IFNULL(`redeemed_voucher_value`,0))+(IFNULL(`shipping_fee`,0)-IFNULL(`free_shipping_fee`,0)) <=', $end_amt);
			}

			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();

			$this->session->set_userdata('filter_start_amt',$start_amt);
			$this->session->set_userdata('filter_end_amt',$end_amt);
		}
		elseif($filter_key == "marketplace"){
			if($this->security->xss_clean($this->input->post('marketplace_name'))){
    			$this->session->unset_userdata('filter_marketplace_name');
    			$marketplace_name = $this->security->xss_clean($this->input->post('marketplace_name'));
    		}
    		else{
    			$marketplace_name = $this->session->userdata('filter_marketplace_name');
    		}

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('marketplace_name',$marketplace_name);
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('marketplace_name',$marketplace_name);
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();

			$this->session->set_userdata('filter_marketplace_name',$marketplace_name);
		}
		elseif($filter_key == "customer"){
			if($this->security->xss_clean($this->input->post('customer_id'))){
    			$this->session->unset_userdata('filter_customer_id');
    			$customer_id = $this->security->xss_clean($this->input->post('customer_id'));
    		}
    		else{
    			$customer_id = $this->session->userdata('filter_customer_id');
    		}

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('customer_id',$customer_id);
			$this->db->order_by('id_orders', 'desc');
			$config['total_rows'] = $this->db->get()->num_rows();

			$this->pagination->initialize($config);

			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('customer_id',$customer_id);
			$this->db->order_by('id_orders', 'desc');
			$this->db->limit($config['per_page'], $this->uri->segment(4));
			$this->data['orders'] = $this->db->get()->result();

			$this->session->set_userdata('filter_customer_id',$customer_id);
		}
		$this->session->set_userdata('filter_key',$filter_key);

		$rowcount = $config['total_rows'];
		$this->data['total_sales_order'] = $rowcount;
	
		//load view
		$this->data['subview'] = 'admin/orders/index';
		$this->load->view('admin/templates/header', $this->data_header); 
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer');	
    }

    //add order form marketplace
    public function add_order(){

    	/*$this->data['customer_marketplace'] = $this->db->select('*')->from('customers')->where('(type="marketplace" or type="regular")')->order_by('id_customers','ASC')->get()->result();*/
        $this->data['customer_marketplace'] = $this->db->select('*')->from('customers')->order_by('id_customers','ASC')->get()->result();
    	$this->data['marketplace']			= $this->db->select('*')->from('marketplace')->order_by('id','ASC')->get()->result();
        $this->data['warehouses']           = $this->db->select('*')->from('warehouse')->order_by('id','ASC')->get()->result();

    	$config = $this->order_m->add_order_rules;

        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); //above is to add class to form validation error, to be styled

        $this->form_validation->set_rules($config); 
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');

        if($this->form_validation->run($this) == TRUE) {
        	/*get customer info detail*/
        	$customer_id 	= $this->security->xss_clean($this->input->post('customer_id'));
        	$customer 		= $this->db->select('*')->from('customers')->where('id_customers',$customer_id)->get()->row();
        	/*get customer info detail*/
			
			/*cek shipping customer untuk yang guest */
			if($customer->shipping_district == "" || $customer->shipping_district == null){
				$this->session->set_flashdata('success', '<br><p style="background:red; color:white; padding:5px; font-weight:bold;">District Empty</p>');
				redirect('admin/orders/add_order');
			}
			
			if($customer->shipping_subdistrict == "" || $customer->shipping_subdistrict == null){
				$this->session->set_flashdata('success', '<br><p style="background:red; color:white; padding:5px; font-weight:bold;">Sub-District Empty</p>');
				redirect('admin/orders/add_order');
			}
			
			if($customer->shipping_province == "" || $customer->shipping_province == null){
				$this->session->set_flashdata('success', '<br><p style="background:red; color:white; padding:5px; font-weight:bold;">Province</p>');
				redirect('admin/orders/add_order');
			}
			/*cek shipping customer untuk yang guest */
			
        	/*get marketplace name*/
        	$marketplace_name 		= null;
        	$marketplace_id 		= $this->input->post('marketplace_id');
        	$get_marketplace_name	= $this->db->select('name')->from('marketplace')->where('id',$marketplace_id)->get()->row();
        	if($get_marketplace_name != null){
        		$marketplace_name 	= $get_marketplace_name->name;
        	}
        	/*get marketplace name*/

        	$product 			= $this->security->xss_clean($this->input->post('id_product'));
        	$count_product		= count($product);
        	$marketplace_price 	= $this->security->xss_clean($this->input->post('marketplace_price'));
        	$quantitas_beli 	= $this->security->xss_clean($this->input->post('quantitas_beli'));

            $warehouse_id       = $this->security->xss_clean($this->input->post('warehouse_id'));

        	/*cek product dan qty kosong*/
        	if($product != 0){
        		for($a=0;$a<$count_product;$a++){
        			if($quantitas_beli[$a] == ""){
        				$this->session->set_flashdata('success', '<br><p style="background:red; color:white; padding:5px; font-weight:bold;">Not Set Product Quantity</p>');
						redirect('admin/orders/add_order');
        			}
        		}
        	}
        	else{
        		$this->session->set_flashdata('success', '<br><p style="background:red; color:white; padding:5px; font-weight:bold;">Not Product Found</p>');
				redirect('admin/orders/add_order');
        	}
        	/*cek product dan qty kosong*/

        	/*cek stock warehouse*/
        	for($cek=0;$cek<$count_product;$cek++){
        		$product_name	= $this->db->select('title')->from('products')->where('id_products',$product[$cek])->get()->row()->title;
				$stock = $this->db->select('stock,stock_virtual')->from('stock')->where('id_product',$product[$cek])->where('warehouse_id',$warehouse_id)->get()->row();
        		$warehouse = $this->db->select('*')->from('warehouse')->where('id', $warehouse_id)->get()->row();
        		if($warehouse->warehouse_type == 'virtual'){
        			if($quantitas_beli[$cek] > $stock->stock_virtual){
	        			$this->session->set_flashdata('success', '<br><p style="background:red; color:white; padding:5px; font-weight:bold;">Not Enough Stock for "'.$product_name.'"</p>');
						redirect('admin/orders/add_order');
	        		}
        		} else {
        			if($quantitas_beli[$cek] > $stock->stock){
						$this->session->set_flashdata('success', '<br><p style="background:red; color:white; padding:5px; font-weight:bold;">Not Enough Stock for "'.$product_name.'"</p>');
						redirect('admin/orders/add_order');
					}
				}
        	}
        	/*cek stock warehouse*/

        	/*hitung total amount*/
        	$this->load->helper('shipping');
        	$this->load->helper('rajaongkir');

        	$total_amount	= 0;
        	$subtotal		= 0;

        	for($sf=0;$sf<$count_product;$sf++){
        		/*$shipping_fee_info =  calculate_shipping_fee(3, 1, $product[$sf], $quantitas_beli[$sf], $customer->shipping_id_subdistrict);*/
        		/*$subtotal 		= ($marketplace_price[$sf] * $quantitas_beli[$sf]) + $shipping_fee_info['total_shipping_fee'];*/
                $subtotal       = ($marketplace_price[$sf] * $quantitas_beli[$sf]);
        		$total_amount	= $total_amount + $subtotal;
        	}

            //get customer district
           

        	/*hitung total amount*/
        	
        	$order = array(
        		'customer_id' 				=> $customer_id, 
        		'payment_status' 			=> 3, 
        		'payment_status_message'	=> NULL, 
        		'payment_confirm' 			=> 0, 
        		'payment_confirm_details' 	=> NULL, 
        		'total_amount' 				=> $total_amount, 
        		'payment_type' 				=> 'TOP', 
        		'payment_method' 			=> NULL, 
        		'payment_date' 				=> NULL, 
        		'cancel_date' 				=> NULL, 
        		'sent_date' 				=> NULL, 
        		'airway_bill' 				=> NULL, 
        		'recipient_name' 			=> $customer->recipient_name, 
        		'address' 					=> $customer->shipping_address, 
        		'district' 					=> $customer->shipping_district, 
        		'subdistrict'				=> $customer->shipping_subdistrict, 
        		'province'					=> $customer->shipping_province, 
        		'postcode'					=> $customer->shipping_postcode, 
        		'phone'						=> $customer->shipping_phone, 
                'email'                     => $customer->email, 
        		'country'					=> $customer->shipping_country, 
        		'redeemed_voucher_code'		=> NULL, 
        		'redeemed_voucher_amount'	=> NULL, 
        		'shipping_type'				=> "", 
        		'shipping_fee'				=> $this->input->post('shipping_fee'), 
        		'ppn'						=> 0, 
        		'plus_reward'				=> 0, 
        		'minus_reward'				=> 0, 
        		'minus_reward_amount'		=> NULL, 
        		'no_resi'					=> NULL, 
        		'customer_note'				=> "", 
        		'marketplace_name'			=> $marketplace_name,
        		'admin_note'				=> $this->security->xss_clean($this->input->post('admin_note')),
        		'created_by'                => $this->session->userdata('admin')['name']

        	);

        	$order_id = (int) $this->order_m->add_order($order);

        	/*insert into order detail*/
        	for($c=0;$c<$count_product;$c++){
        		$product_item = $this->db->select('title,is_backorder')->from('products')->where('id_products',$product[$c])->get()->row();
        		/*$shipping_fee_info =  calculate_shipping_fee(3, 1, $product[$c], $quantitas_beli[$c], $customer->shipping_id_subdistrict);*/

        		$order_detail = array(
        			'orders_id'			=> $order_id, 
        			'item_id' 			=> $product[$c], 
        			'item_name'			=> $product_item->title,
        			'item_price'		=> $marketplace_price[$c], 
        			'quantity'			=> $quantitas_beli[$c], 
        			/*'subtotal'			=> ($marketplace_price[$c] * $quantitas_beli[$c]) + $shipping_fee_info['total_shipping_fee'],*/
                    'subtotal'          => ($marketplace_price[$c] * $quantitas_beli[$c]),
        			'sku'				=> "",
        			'attributes'		=> "",
        			'warehouse_id'		=> $warehouse_id,
        			'chosen_shipping_id'=> 3,
        			/* 'shipping_fee'		=> $shipping_fee_info['total_shipping_fee'], */
                    'shipping_fee'      => $this->input->post('shipping_fee'),
        			'is_backorder'		=> 'no',
        			'status'			=> 0,
        			'no_resi'			=> "",
        		);

        		$this->db->insert('orders_detail',$order_detail);
        	}
        	/*insert into order detail*/

        	/*kurangi stock pada warehouse*/
        	for($d=0;$d<$count_product;$d++){

        		$curent_stock 	= $this->db->select('stock,stock_virtual')->from('stock')->where('id_product',$product[$d])->where('warehouse_id',$warehouse_id)->get()->row();

        		$warehouse = $this->db->select('*')->from('warehouse')->where('id', $warehouse_id)->get()->row();

        		if($warehouse->warehouse_type == 'virtual'){
        			$final_stock = array(
        			'stock_virtual' => $curent_stock->stock_virtual - $quantitas_beli[$d], 
        		);
        		$this->db->where('id_product',$product[$d]);
        		$this->db->where('warehouse_id',$warehouse_id);
	        		$this->db->update('stock',$final_stock);
        		} else {
        			$final_stock = array(
	        			'stock' => $curent_stock->stock - $quantitas_beli[$d], 
	        		);
	        		$this->db->where('id_product',$product[$d]);
	        		$this->db->where('warehouse_id',$warehouse_id);
					$this->db->update('stock',$final_stock);
					}
        	}
        	/*kurangi stock pada warehouse*/
			
			/*insert shipping session to shipping table*/
			$insert_shipping_session = array(
				'order_id' 		=> $order_id, 
				'warehouse_id' 	=> $warehouse_id,
				'shipping_fee' 	=> $this->input->post('shipping_fee'),
				'is_indent' 	=> 'no',
			);
			$this->db->insert('shipping',$insert_shipping_session);			
			/*insert shipping session to shipping table*/

        	$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Add Order Successful</p>');
			redirect('admin/orders');

        }

     	//load view
		$this->data['subview'] = 'admin/orders/add_order';
		$this->load->view('admin/templates/header', $this->data_header); 
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer');
    }

    function ajax_get_product_marketplace(){
    	$id 			= (int) $this->input->post('id_marketplace');
    	$data['product']= $this->db->select('*')->from('products')->join('marketplace_product_price', 'marketplace_product_price.product_id = products.id_products')->where('marketplace_product_price.marketplace_id',$id)->get()->result();
    	$this->load->view('admin/orders/ajax_get_product_marketplace', $data);
    }

	function ajax_get_address_customer_marketplace(){
    	$id 			= (int) $this->input->post('id_customers');
    	$data['customers'] = $this->db->select('*')->from('customers')->where('customers.id_customers',$id)->get()->result();
    	$this->load->view('admin/orders/ajax_get_address_customer_marketplace', $data);
    }
    
    function ajax_get_product_detail(){
    	$id 			= (int) $this->input->post('id_product');
    	$id_marketplace	= (int) $this->input->post('id_marketplace');
    	$id_warehouse	= (int) $this->input->post('id_warehouse');
		$data['product']= $this->db->select("products.*,marketplace_product_price.*,CASE WHEN warehouse.warehouse_type='virtual' THEN IFNULL(stock.stock_virtual,0) ELSE IFNULL(stock.stock,0) END stock")
								->from("products")
								->join("marketplace_product_price", "marketplace_product_price.product_id = products.id_products","left")
								->join("warehouse","warehouse.id = ".$id_warehouse,"left")
								->join("stock","stock.id_product = products.id_products and warehouse.id=stock.warehouse_id","left")
								->where("products.id_products",$id)->where("marketplace_product_price.marketplace_id",$id_marketplace)->get()->row();
    	echo json_encode($data);
    }
	
	//to VIEW and EDIT order in admin
	public function view($id) {

		if($id == null){
			redirect('admin/orders');
		}

		//get orders
		$this->db->select('*')->from('orders')->where('id_orders', $id);
		$current_order = $this->db->get()->row();

		if(count($current_order) < 1) {show_404();}

		if (isset($_POST['payment_status'])) {

			/* if($this->order_m->cek_order($id,$_POST['payment_status']) == FALSE){
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Order telah diproses</p>');
				redirect('admin/orders/view/' . $id);
			} */

			//var_dump($this->input->post('payment_status')); exit();

			if ($this->input->post('payment_status') == 2) {

				//Status CANCEL
				$data = array( 
					'payment_status' => 2,
					'cancel_date' => date('Y-m-d')
				);
				$this->db->where('id_orders', $id);
				$this->db->update('orders', $data);

				//return the quantity back to stock
				//get order details
				$order_details =  $this->order_detail_m->get_orders_detail($id);

                //get customer_id
                $this->db->select('customer_id')->from('orders')->where('id_orders', $id);
                $customer_id = (int) $this->db->get()->row()->customer_id;


				foreach ($order_details as $item) {

					//get current stock
					$this->db->select('stock, id')->from('stock')->where('id_product', $item->product_id)->where('id_product_detail', $item->item_id)->where('warehouse_id', $item->warehouse_id);
					$current_stock = $this->db->get()->row();
					$qty = 0;
					if($item->is_backorder == 'yes'){
						$qty = $qty + 0;
					}
					else{
						$qty = $qty + $item->quantity;
					}
					
					$data = array(
						'stock' => $current_stock->stock + $qty,
					);
					$this->db->where('id_product', $item->product_id);
					$this->db->where('id_product_detail', $item->item_id);
					$this->db->where('warehouse_id', $item->warehouse_id);
					$this->db->update('stock', $data);

					//get $stock_id
					$stock_id = $current_stock->id;

					//update stock_movement_table
					$movement_data = array(
						'stock_id' => $stock_id,
						'type' => '+',
						'stock_change' => (int) $qty,
						'remark' => 'Cancel Order No: ' . $id
					);
					$this->db->insert('stock_movement', $movement_data);

                    if($item->is_flashsale != 0){
                        //return flashsale counter & customer purchase
                        /*get purchase qty from flashsale_customer*/
                        $flashsale_purchase = $this->db->select('purchase_qty')->from('flashsale_customer')->where('customer_id',$customer_id)->where('flashsale_id',$item->is_flashsale)->where('flashsale_product_id',$item->item_id)->get()->row()->purchase_qty;
                        /*return counter and terjual from flashsale product*/
                        $current_flashsale_product = $this->db->select('counter,terjual')->from('flashsale_products')->where('flashsale_id',$item->is_flashsale)->where('product_id',$item->item_id)->get()->row();
                        $return_counter_terjual = array(
                            'counter' => $current_flashsale_product->counter + $flashsale_purchase, 
                            'terjual' => $current_flashsale_product->terjual - $flashsale_purchase,
                        );
                        $this->db->where('flashsale_id',$item->is_flashsale);
                        $this->db->where('product_id',$item->item_id);
                        $this->db->update('flashsale_products',$return_counter_terjual);
                        /*delete flashsale customer record*/
                        $this->db->where('customer_id',$customer_id);
                        $this->db->where('flashsale_id',$item->is_flashsale);
                        $this->db->delete('flashsale_customer');
                    }
				}

				//return customer point reward back to customers table because he cancel
				//get customer current point
				$this->db->select('current_pointreward')->from('customers')->where('id_customers', $customer_id);
				$current_point = (int) $this->db->get()->row()->current_pointreward;

				//get minus point from order
				$this->db->select('current_reward,sisa_reward,minus_reward')->from('orders')->where('id_orders', $id);
				$rewards = $this->db->get()->row();
				$minus_point 	= (int) $rewards->minus_reward;
				$current_reward = (int) $rewards->current_reward;
				$sisa_reward 	= (int) $rewards->sisa_reward;
				if (($sisa_reward + $minus_point) == $current_reward) {
					$updated_point = $current_point + $minus_point;

					//update point reward
					$data = array(
						'current_pointreward' => $updated_point
					);
					$this->db->where('id_customers', $customer_id);
					$this->db->update('customers', $data);
				}

				//----SEND EMAIL TO CUSTOMER 
				//get order detail and customer detail
				$data['order'] = $this->order_m->get_order($id);  
				$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);
				$data['minus_point'] = $minus_point;

				//get website data
				$this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1);
				$website_data = $this->db->get()->row();
				$data['logo'] = $website_data->logo;
				$data['website_name'] = $website_data->website_name;

				$data['emails'] = $this->configuration_m->get_emails(); 
				$data['title'] = 'Order Cancel'; 
				
				$email_data = $data;
				$email_data['email'] = $data['customer']->email; 
				$email_data['subject'] = 'Order Cancel'; 

				if($data['order']->order_language == 'english') {
					$view_file = 'email/english/order_cancel';	
				} else {
					$view_file = 'email/indonesian/order_cancel';		
				}	

				$this->send_email($view_file, $email_data); 
				//----end send email 

				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');
				redirect('admin/orders/view/' . $id);
			}

			if ($this->input->post('payment_status') == 1) {

				//Status NOT PAID
				$data = array( 
					'payment_status' => 1,
					'payment_date' => date('Y-m-d')
				);
				$this->db->where('id_orders', $id);
				$this->db->update('orders', $data);
				 
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');
				redirect('admin/orders/view/' . $id);
			}

			if ($this->input->post('payment_status') == 3) {

				//Status PAID
				$data = array( 
					'payment_status' => 3,
				);
				$this->db->where('id_orders', $id);
				$this->db->update('orders', $data);

				//update current point rewards
				//get customer_id
				$this->db->select('customer_id')->from('orders')->where('id_orders', $id);
				$customer_id = (int) $this->db->get()->row()->customer_id;

				//get add and minus point from order
				$this->db->select('plus_reward')->from('orders')->where('id_orders', $id);
				$rewards = $this->db->get()->row();
				$plus_point = (int) $rewards->plus_reward;

				//SEND EMAIL TO CUSTOMER
				$data['title'] = 'Payment Confirmation'; 
				//get order detail and customer detail
				$data['order'] = $this->order_m->get_order($id);
				$data['order_details'] = $this->order_detail_m->get_orders_detail($id); 

				$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);

				//get website data
				$this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1);
				$website_data = $this->db->get()->row();
				$data['logo'] = $website_data->logo;
				$data['website_name'] = $website_data->website_name;
				$data['emails'] = $this->configuration_m->get_emails(); 
				$data['plus_point'] = $plus_point;

				$email_data = $data;
				$email_data['email'] = $data['customer']->email; 
				$email_data['subject'] = 'Payment Received'; 

				if($data['order']->order_language == 'english') {
					$view_file = 'email/english/payment_confirmation';	
				} else {
					$view_file = 'email/indonesian/payment_confirmation';		
				}

				$this->send_email($view_file, $email_data);
				//----end send email   
 
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');
				redirect('admin/orders/view/' . $id);
			}

			//CONDITION FOR PARTIAL PAID
			if ($this->input->post('payment_status') == 6) {

				//Status PAID
				$data = array( 
					'payment_status' => 6,
				);
				$this->db->where('id_orders', $id);
				$this->db->update('orders', $data);

				//update current point rewards
				//get customer_id
				$this->db->select('customer_id')->from('orders')->where('id_orders', $id);
				$customer_id = (int) $this->db->get()->row()->customer_id;

				//get add and minus point from order
				$this->db->select('plus_reward')->from('orders')->where('id_orders', $id);
				$rewards = $this->db->get()->row();
				$plus_point = (int) $rewards->plus_reward;

				//SEND EMAIL TO CUSTOMER
				$data['title'] = 'Payment Confirmation'; 
				//get order detail and customer detail
				$data['order'] = $this->order_m->get_order($id);
				$data['order_details'] = $this->order_detail_m->get_orders_detail($id); 

				$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);

				//get website data
				$this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1);
				$website_data = $this->db->get()->row();
				$data['logo'] = $website_data->logo;
				$data['website_name'] = $website_data->website_name;
				$data['emails'] = $this->configuration_m->get_emails(); 
				$data['plus_point'] = $plus_point;

				$email_data = $data;
				$email_data['email'] = $data['customer']->email;
				$email_data['subject'] = 'Payment Received'; 
				
				if($data['order']->order_language == 'english') {
					$view_file = 'email/english/payment_confirmation';	
				} else {
					$view_file = 'email/indonesian/payment_confirmation';		
				}

				$this->send_email($view_file, $email_data);
				// var_dump($this->email->print_debugger());  
				// exit();
				//----end send email   
 
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');
				redirect('admin/orders/view/' . $id);
			}

			if ($this->input->post('payment_status') == 4) {


				//Status PROCESS
				$data = array( 
					'payment_status' => 4,
				);
				$this->db->where('id_orders', $id);
				$this->db->update('orders', $data);

				//update current point rewards
				//get customer_id
				$this->db->select('customer_id')->from('orders')->where('id_orders', $id);
				$customer_id = (int) $this->db->get()->row()->customer_id;

				//get customer current point
				$this->db->select('current_pointreward')->from('customers')->where('id_customers', $customer_id);
				$current_point = (int) $this->db->get()->row()->current_pointreward;
				
				$this->db->select('plus_reward')->from('orders')->where('id_orders', $id);
				$rewards = $this->db->get()->row();
				$plus_point = (int) $rewards->plus_reward;

				$updated_point = $current_point + $plus_point;

				//get plus reward already given status
				$this->db->select('plus_reward_given')->from('orders')->where('id_orders', $id);
				$plus_reward_given = $this->db->get()->row();

				if($plus_reward_given->plus_reward_given == 'no' || $plus_reward_given->plus_reward_given == NULL) {

					//update point reward
					$data = array(
						'current_pointreward' => $updated_point,
					);
					$this->db->where('id_customers', $customer_id);
					$this->db->update('customers', $data);

					$data_order = array(
						'plus_reward_given' => 'yes',	
					);
					$this->db->where('id_orders', $id);
					$this->db->update('orders', $data_order);
				}
 
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');
				redirect('admin/orders/view/' . $id);
			}

			if ($this->input->post('payment_status') == 5) {

				//Status DELIVERED
				$data = array( 
					'payment_status' => 5,
				);
				$this->db->where('id_orders', $id);
				$this->db->update('orders', $data);
 
				$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Status pembayaran berhasil diupdate</p>');
				redirect('admin/orders/view/' . $id);
			}
		}

		//get all provinces data from provinces table...
		$this->db->select('rajaongkir_province_id, province')->from('indonesia_provinces')->order_by('rajaongkir_province_id', 'ASC');
		$this->data['shipping_provinces'] = $this->db->get()->result();

		//get order detail and customer detail
		$this->data['order'] = $this->order_m->get_order($id);  
		$this->data['customer'] = $this->customer_m->get_customer($this->data['order']->customer_id);
		$this->data['order_details'] = $this->order_detail_m->get_orders_detail($id); 
		
		$this->data['subview'] = 'admin/orders/view';
		$this->load->view('admin/templates/header', $this->data_header); 
		$this->load->view('admin/_layout_main', $this->data);
		$this->load->view('admin/templates/footer');	
	}

	/*update order detail*/
	public function update_status(){

		if(!$this->input->post('id_order')) {
			redirect('admin/orders');
		}

		$id 		= $this->security->xss_clean($this->input->post('id_product_detail'));
		$id_order 	= $this->security->xss_clean($this->input->post('id_order'));
		$status		= $this->input->post('status');
		if($status == 0) {
			$order_details = array(
				'status' => $status, 
			);
		}
		elseif($status == 1) {
			
			if($this->security->xss_clean($this->input->post('backed_order')) == 'yes'){
				$cek_stock = 
				$this->db
				->select('stock')
				->from('stock')
				->where('id_product',$this->security->xss_clean($this->input->post('item_order')))
				->where('warehouse_id',$this->security->xss_clean($this->input->post('warehouse_order')))
				->get()
				->row()
				->stock;
				if($this->security->xss_clean($this->input->post('qty_order')) <= $cek_stock){
					$order_details = array(
						'status' => $status, 
					);
					$new_stock = array(
						'stock' => $cek_stock-$this->security->xss_clean($this->input->post('qty_order')), 
					);
					$this->db->where('id_product',$this->security->xss_clean($this->input->post('item_order')));
					$this->db->where('warehouse_id',$this->security->xss_clean($this->input->post('warehouse_order')));
					$this->db->update('stock',$new_stock);
				}
				else{
					$this->session->set_flashdata('success'.$this->security->xss_clean($this->input->post('id')), '<p style="color:red; font-weight:bold;">Stock Tidak Cukup</p>');
					redirect('admin/orders/view/' . $id_order);	
				}
			}
			else{
				$order_details = array(
					'status' => $status, 
					'no_resi' => $this->security->xss_clean($this->input->post('no_resi')),										  
				);
			}
		}
		elseif($status == 2) {
			
			$order_details = array(
				'status' => $status,
				'no_resi' => $this->security->xss_clean($this->input->post('no_resi')),
				'shipping_date' => date('Y-m-d H:i:s')
			);

			//SEND EMAIL TO CUSTOMER
			$data['title'] 			= 'Product Picked Up'; 
			//get order detail and customer detail
			$data['product_detail'] = $this->db->select('*')->from('orders_detail')->where('id_orders_detail',$id)->get()->row();
			$data['warehouse']		= $this->db->select('name')->from('warehouse')->where('id',$data['product_detail']->warehouse_id)->get()->row()->name;
			$data['shipping_method']= $this->db->select('name')->from('shipment_method')->where('id',$data['product_detail']->chosen_shipping_id)->get()->row()->name;
			$data['no_resi']		= $this->security->xss_clean($this->input->post('no_resi'));
			$customer_id 			= $this->db->select('customer_id')->from('orders')->where('id_orders',$id_order)->get()->row()->customer_id;
			$data['customer']		= $this->customer_m->get_customer($customer_id);

			//get website data
			$this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1);
			$website_data 			= $this->db->get()->row();
			$data['logo'] 			= $website_data->logo;
			$data['website_name'] 	= $website_data->website_name;
			$data['emails'] 		= $this->configuration_m->get_emails(); 

			//temporary comment 
			/*$this->load->library('email');
			//get email setting 
			$config['protocol'] 	= 'smtp';
			$config['smtp_host'] 	= $website_data->email_smtp_host; 
			$config['smtp_port'] 	= $website_data->email_smtp_port;
			$config['smtp_user'] 	= $website_data->email_smtp; 
			$config['smtp_pass'] 	= $website_data->email_smtp_password;
			$config['mailtype'] 	= 'html';
			$config['charset'] 		= 'iso-8859-1';
			$config['wordwrap'] 	= TRUE;
			$config['newline'] 		= "\r\n"; //use double quotes to comply with RFC 822 standard 
			$this->email->initialize($config);
			$this->email->from($data['emails']->from_email, $data['emails']->website_name);
			$this->email->to($data['customer']->email); 
			$this->email->subject('Payment Confirmation'); 
			$email = $this->load->view('email/indonesian/pickedup_confirmation', $data, TRUE);
			$this->email->message($email);	
			$this->email->send();    */
			//----end send email
		}
		
		$this->db->where('id_orders_detail',$id);
		$this->db->update('orders_detail',$order_details);

		//add no resi to shipping table
		$data_resi = array(
			'tracking_number' => $this->security->xss_clean($this->input->post('no_resi'))
		);
		$this->db->where('order_id', $this->security->xss_clean($this->input->post('id_order')));
		$this->db->where('warehouse_id', $this->security->xss_clean($this->input->post('warehouse_order')));
		$this->db->update('shipping', $data_resi);

		/*cek detail status to update order status*/
		$cek_status = 0;
		$all_order_detail_status = $this->db->select('status')->from('orders_detail')->where('orders_id',$id_order)->get()->result();
		foreach ($all_order_detail_status as $item) {
			if($item->status != 2){
				$cek_status = $cek_status + 1;
			}
			else{
				$cek_status = $cek_status;
			}
		}
		if($cek_status == 0){
			$data = array( 
				'payment_status' => 5,
			);
			$this->db->where('id_orders', $id_order);
			$this->db->update('orders', $data);

			//$this->sync_this_order($id_order);
		}
		
		$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">Update Order Status Success</p>');
		redirect('admin/orders/view/' . $id_order);
	}

	public function generate_invoice_pdf($id) {

		//add PDF attachment DOMPDF 
			  
		$data['title'] = 'Invoice'; 
		
		//get order
		$this->db->select('*')->from('orders')->where('id_orders', $id);
		$data['order'] = $this->db->get()->row();
		$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);
		$data['emails'] = $this->configuration_m->get_emails();  

		$data['bank'] = $this->configuration_m->get_bank();   

		$this->db->select('logo')->from('configuration')->where('id_configuration', 1);
		$data['logo'] = $this->db->get()->row()->logo;

		//get order detail and customer detail
		$this->db->select('*')->from('orders_detail')->where('orders_id', $id);
		$data['order_details'] = $this->db->get()->result();

		$this->load->library('dompdf_gen');
		$html= $this->load->view('invoice_pdf', $data ,true);
		$this->dompdf->load_html($html);
		$this->dompdf->render(); 
		$this->dompdf->stream('invoice.pdf', array("Attachment" => 0));
		$output = $this->dompdf->output(); 
		$file_to_save = 'uploads/pdf/invoice.pdf'; 
		file_put_contents($file_to_save, $output);  
	}

	public function generate_multiple_invoices() {

		if(!$this->input->post('generate_invoices')) { redirect('admin/orders');}

		$start_date_array = explode('-', $this->security->xss_clean($this->input->post('start_date')));
		$end_date_array = explode('-', $this->security->xss_clean($this->input->post('end_date')));
		//change to YYYY-MM-DD format for database insertion, and use php DatePeriod class
		$begin = new DateTime($start_date_array[2] . '-' . $start_date_array[1] . '-' . $start_date_array[0]);
		$end = new DateTime($end_date_array[2] . '-' . $end_date_array[1] . '-' . $end_date_array[0]);
		$end = $end->modify('+1 day'); 
		$interval = new DateInterval('P1D');
		$daterange = new DatePeriod($begin, $interval ,$end);

		$this->load->library('dompdf_gen');

		//create a new directory inside pdf folder
		if (!is_dir('./uploads/' . 'pdf/' . 'invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'))) { //check if directory already exist
			mkdir('./uploads/' . 'pdf/' . 'invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'));
			chmod('./uploads/' . 'pdf/' . 'invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'), 0777);  //change permission to writable 777, so can be deleted
		}

		$total_orders_found = 0;
		
		foreach($daterange as $date){

			//get orders from each particular date
			//DATE(order_date) is a mysql function, to get onlye date from timestamp, exclude h-m-s
			$this->db->select('*')->from('orders');
			$this->db->where('DATE(order_date)', $date->format('Y-m-d'));
			if($this->input->post('include_unpaid_orders') == 'no') {
				$this->db->group_start();
				$this->db->where('payment_status', 1);
				$this->db->or_where('payment_status', 3);
				$this->db->group_end();
			}
			$orders = $this->db->get()->result();

			if(count($orders) > 0) {
				
				//orders are available..then proceed 
				$total_orders_found = $total_orders_found + count($orders);

				foreach($orders as $data['order']) {

					//generate pdf for each order in this particular date
					//add PDF attachment DOMPDF 
					$data['title'] = 'Invoice ' . $data['order']->id_orders;
					$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);
					$data['emails'] = $this->configuration_m->get_emails();  
					$data['bank'] = $this->configuration_m->get_bank();   
					$this->db->select('logo')->from('configuration')->where('id_configuration', 1);
					$data['logo'] = $this->db->get()->row()->logo;
					//get order detail and customer detail
					$this->db->select('*')->from('orders_detail')->where('orders_id', $data['order']->id_orders);
					$data['order_details'] = $this->db->get()->result();
			
					$html= $this->load->view('invoice_pdf', $data ,true);
					//create a new dompdf instance (this is the crucial step)
					$this->dompdf = new DOMPDF();
					$this->dompdf->load_html($html);
					$this->dompdf->render();  //render html as pdf
					/* $this->dompdf->stream('invoice.pdf', array("Attachment" => 0)); //display to browser*/
					$output = $this->dompdf->output();  
					
					//add pdf file into directory
					$file_to_save = 'uploads/pdf/invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date') . '/invoice-orderid-' . $data['order']->id_orders . '.pdf'; 
					file_put_contents($file_to_save, $output);  //$output function to add files to folder

				}

			}
	
		}

		if($total_orders_found == 0) {
			//dont download files, but go back to orders page and give error notice..
			$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">No orders are found</p>');
				redirect('admin/orders');
		}

		//zip the generated pds and downlod the zip file
		$this->load->library('zip');
		$path = './uploads/' . 'pdf/' . 'invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date');
		$this->zip->read_dir($path, FALSE); //FALSE is to exclude entir path
		// Download the files to desktop. Name it "my_backup.zip"
		$this->zip->download('invoices-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date') . '.zip');

		//finally, delete the directory
		//THIS NOT WORKING YET......
		//rmdir('./uploads/' . 'pdf/' . 'invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'));

	}

	public function generate_deliveryslip_pdf($id) {

		//add PDF attachment DOMPDF 
			  
		$data['title'] = 'Delivery Slip'; 
		
		//get order
		$this->db->select('*')->from('orders')->where('id_orders', $id);
		$data['order'] = $this->db->get()->row();

		if($data['order']->dropship == 'yes') {
			//use dropshipper 
			$this->db->select('id_customers, name, email, phone, reseller_id, dropship, dropship_shop_name, dropship_shop_address, dropship_shop_phone, dropship_shop_email, dropship_shop_logo');
			$this->db->from('customers');
			$this->db->where('id_customers', $data['order']->customer_id);
			$data['customer'] = $this->db->get()->row();
			$data['logo'] = $data['customer']->dropship_shop_logo;
			$data['dropship_status'] = 'yes';
		
		} else {
			//non dropshipper
			$this->db->select('id_customers, name, email, phone, reseller_id');
			$this->db->from('customers');
			$this->db->where('id_customers', $data['order']->customer_id);
			$data['customer'] = $this->db->get()->row();
			$data['dropship_status'] = 'no';
			$this->db->select('logo')->from('configuration')->where('id_configuration', 1);
			$data['logo'] = $this->db->get()->row()->logo;
		} 

		$data['emails'] = $this->configuration_m->get_emails();  

		//$data['bank'] = $this->configuration_m->get_bank();   

		//get order detail and customer detail
		$this->db->select('*')->from('orders_detail')->where('orders_id', $id);
		$data['order_details'] = $this->db->get()->result();

		$this->load->library('dompdf_gen');
		$html= $this->load->view('deliveryslip_pdf', $data ,true);
		$this->dompdf->load_html($html);
		$this->dompdf->render(); 
		$this->dompdf->stream('deliveryslip.pdf', array("Attachment" => 0));
		$output = $this->dompdf->output(); 
		$file_to_save = 'uploads/pdf/deliveryslip.pdf'; 
		file_put_contents($file_to_save, $output);  
	}

	public function generate_multiple_deliveryslips() {

		if(!$this->input->post('generate_deliveryslips')) { redirect('admin/orders');}

		$start_date_array = explode('-', $this->security->xss_clean($this->input->post('start_date')));
		$end_date_array = explode('-', $this->security->xss_clean($this->input->post('end_date')));
		//change to YYYY-MM-DD format for database insertion, and use php DatePeriod class
		$begin = new DateTime($start_date_array[2] . '-' . $start_date_array[1] . '-' . $start_date_array[0]);
		$end = new DateTime($end_date_array[2] . '-' . $end_date_array[1] . '-' . $end_date_array[0]);
		$end = $end->modify('+1 day'); 
		$interval = new DateInterval('P1D');
		$daterange = new DatePeriod($begin, $interval ,$end);

		$this->load->library('dompdf_gen');

		//create a new directory inside pdf folder
		if (!is_dir('./uploads/' . 'pdf/' . 'deliveryslip-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'))) { //check if directory already exist
			mkdir('./uploads/' . 'pdf/' . 'deliveryslip-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'));
			chmod('./uploads/' . 'pdf/' . 'deliveryslip-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'), 0777);  //change permission to writable 777, so can be deleted
		}

		$total_orders_found = 0;
		
		foreach($daterange as $date) {

			//get orders from each particular date
			//DATE(order_date) is a mysql function, to get onlye date from timestamp, exclude h-m-s
			$this->db->select('*');
			$this->db->from('orders');
			$this->db->where('DATE(order_date)', $date->format('Y-m-d'));
			if($this->input->post('include_unpaid_orders') == 'no') {
				$this->db->group_start();
				$this->db->where('payment_status', 1);
				$this->db->or_where('payment_status', 3);
				$this->db->group_end();
			}
			$orders = $this->db->get()->result();

			if(count($orders) > 0) {
				
				$total_orders_found = $total_orders_found + count($orders);

				foreach($orders as $data['order']) {

					//add PDF attachment DOMPDF 
					$data['title'] = 'Delivery Slip'; 
					
					//get order
					$this->db->select('*')->from('orders')->where('id_orders', $data['order']->id_orders);
					$data['order'] = $this->db->get()->row();

					if($data['order']->dropship == 'yes') {
						//use dropshipper 
						$this->db->select('id_customers, name, email, phone, reseller_id, dropship, dropship_shop_name, dropship_shop_address, dropship_shop_phone, dropship_shop_email, dropship_shop_logo');
						$this->db->from('customers');
						$this->db->where('id_customers', $data['order']->customer_id);
						$data['customer'] = $this->db->get()->row();
						$data['logo'] = $data['customer']->dropship_shop_logo;
						$data['dropship_status'] = 'yes';
					
					} else {
						//non dropshipper
						$this->db->select('id_customers, name, email, phone, reseller_id');
						$this->db->from('customers');
						$this->db->where('id_customers', $data['order']->customer_id);
						$data['customer'] = $this->db->get()->row();
						$data['dropship_status'] = 'no';
						$this->db->select('logo')->from('configuration')->where('id_configuration', 1);
						$data['logo'] = $this->db->get()->row()->logo;
					} 

					$data['emails'] = $this->configuration_m->get_emails();  

					//$data['bank'] = $this->configuration_m->get_bank();   

					//get order detail and customer detail
					$this->db->select('*')->from('orders_detail')->where('orders_id', $data['order']->id_orders);
					$data['order_details'] = $this->db->get()->result();
					
					$html= $this->load->view('deliveryslip_pdf', $data ,true);
					//create a new dompdf instance (this is the crucial step)
					$this->dompdf = new DOMPDF();
					$this->dompdf->load_html($html);
					$this->dompdf->render(); 
					//$this->dompdf->stream('deliveryslip.pdf', array("Attachment" => 0));
					$output = $this->dompdf->output(); 

					//add pdf file into directory
					$file_to_save = 'uploads/pdf/deliveryslip-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date') . '/deliveryslip-orderid-' . $data['order']->id_orders . '.pdf'; 
					file_put_contents($file_to_save, $output);  //$output function to add files to folder

				}

			}
	
		}

		if($total_orders_found == 0) {
			//dont download files, but go back to orders page and give error notice..
			$this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">No orders are found</p>');
				redirect('admin/orders');
		}

		//zip the generated pds and downlod the zip file
		$this->load->library('zip');
		$path = './uploads/' . 'pdf/' . 'deliveryslip-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date');
		$this->zip->read_dir($path, FALSE); //FALSE is to exclude entir path
		// Download the files to desktop. 
		$this->zip->download('deliveryslips-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date') . '.zip');

		//finally, delete the directory
		//THIS NOT WORKING YET......
		//rmdir('./uploads/' . 'pdf/' . 'invoice-' . $this->input->post('start_date') . '-' .  $this->input->post('end_date'));

	}

	public function generate_shipping_mark($id){
		/*get order data*/
		$data['orders_detail'] 	= $this->db->select('*')->from('orders_detail')->where('id_orders_detail',$id)->get()->row();
		$data['orders']			= $this->db->select('*')->from('orders')->where('id_orders',$data['orders_detail']->orders_id)->get()->row();

		if($this->session->userdata('site_lang') == 'english') {
			$data['products_descr'] = $this->db->select('description_en as description')->get_where("products",array(
				'id_products'=>$data['orders_detail']->product_id,
			))->row()->description;
		}else{
			$data['products_descr'] = $this->db->select('description as description')->get_where("products",array(
				'id_products'=>$data['orders_detail']->product_id,
			))->row()->description;
		}

		/*get customer id with order id*/
		$customer_id			= $this->db->select('customer_id')->from('orders')->where('id_orders',$data['orders_detail']->orders_id)->get()->row()->customer_id;

		/*get customer detail*/
		$data['customer']		= $this->db->select('*')->from('customers')->where('id_customers',$customer_id)->get()->row();

		/*get warehouse detail*/
		$data['warehouse']		= $this->db->select('*')->from('warehouse')->where('id',$data['orders_detail']->warehouse_id)->get()->row();
		$data['district']		= $this->db->select('district')->from('indonesia_districts')->where('rajaongkir_id_district',$data['warehouse']->id_district)->get()->row()->district;
		$data['subdistrict']	= $this->db->select('subdistrict')->from('indonesia_subdistricts')->where('rajaongkir_id_subdistrict',$data['warehouse']->id_subdistrict)->get()->row()->subdistrict;
		$data['province']		= $this->db->select('province')->from('indonesia_provinces')->where('rajaongkir_province_id',$data['warehouse']->id_province)->get()->row()->province;

		//get websote name
		$data['website_name'] = $this->db->select('website_name')->from('configuration')->where('id_configuration',1)->get()->row()->website_name;

		//add PDF attachment DOMPDF 
		$data['title'] 		= 'Shipping Mark';

		$this->load->library('dompdf_gen');
		$html = $this->load->view('shipping_mark_pdf', $data ,true);
		// echo $html;die();
		$this->dompdf->load_html($html);
		$this->dompdf->set_paper('A4','landscape');
		$this->dompdf->render(); 
		$this->dompdf->stream('shipping_mark.pdf', array("Attachment" => 0));
		$output = $this->dompdf->output(); 
		$file_to_save = 'uploads/pdf/shipping_mark.pdf'; 
		file_put_contents($file_to_save, $output);

	}

	public function generate_invoice($id){
		/*get order data*/
		$data['orders']			= $this->db->select('*')->from('orders')->where('id_orders',$id)->get()->row();
		$data['orders_detail'] 	= $this->db->select('*')->from('orders_detail')->where('orders_id',$id)->get()->result();

		/*get customer id with order id*/
		$customer_id			= $this->db->select('customer_id')->from('orders')->where('id_orders',$id)->get()->row()->customer_id;

		/*get customer detail*/
		$data['customer']		= $this->db->select('*')->from('customers')->where('id_customers',$data['orders']->customer_id)->get()->row();

		//add PDF attachment DOMPDF 
		$data['title'] 		= 'Shipping Invoice';

		$this->load->library('dompdf_gen');
		$html = $this->load->view('shipping_invoice_pdf', $data ,true);
		echo $html;die();
		$this->dompdf->load_html($html);
		$this->dompdf->set_paper('A4','landscape');
		$this->dompdf->render(); 
		$this->dompdf->stream('shipping_mark.pdf', array("Attachment" => 0));
		$output = $this->dompdf->output(); 
		$file_to_save = 'uploads/pdf/shipping_mark.pdf'; 
		file_put_contents($file_to_save, $output);

	}

    public function update_noresi(){
        $order_detail_id = $this->input->post('id_orders_detail');
		/*get order id & warehouse*/
        $id_order = $this->db->select('orders_id')->from('orders_detail')->where('id_orders_detail',$order_detail_id)->get()->row()->orders_id;
        $warehouse_id = $this->db->select('warehouse_id')->from('orders_detail')->where('id_orders_detail',$order_detail_id)->get()->row()->warehouse_id;
        $is_backorder = $this->db->select('is_backorder')->from('orders_detail')->where('id_orders_detail',$order_detail_id)->get()->row()->is_backorder;
        /*get order id & warehouse*/
        $new_resi = array(
            'no_resi' => $this->input->post('no_resi'), 
        );

        $this->db->where('id_orders_detail',$order_detail_id);
        $this->db->update('orders_detail',$new_resi);
		
		$new_tracking_number = array(
			'tracking_number' => $this->input->post('no_resi'), 
		);

		$this->db->where('order_id',$id_order);
		$this->db->where('warehouse_id',$warehouse_id);
		$this->db->where('is_indent',$is_backorder);
		$this->db->update('shipping',$new_tracking_number);								
        $this->session->set_flashdata('success', '<br><p style="background:green; color:white; padding:5px; font-weight:bold;">No. Resi Updated</p>');
        redirect('admin/orders/view/' . $id_order); 
    }

	function jx_update_stt_withbutton(){
		$p_act = $this->input->post('p_act');
		$msg = "Gagal";
		$res = "";
		if(isset($p_act)){
			switch ($p_act) {
				case 'ready to send':
					$productid = $this->input->post('productid');
					$order_detailid = $this->input->post('order_detailid');
					$orderid = $this->input->post('orderid');
					$itemid = $this->input->post('itemid');
					$witch = $this->input->post('witch'); 

					if($witch === "indent") {

						//get warehouse id
						$order_detail = $this->db->select('warehouse_id, quantity')->from('orders_detail')->where('id_orders_detail', $order_detailid)->get()->row();
						$warehouse_id = $order_detail->warehouse_id;
						$qty = $order_detail->quantity;

						//deduct stock
						//get current stock
						$this->db->select('stock, id')->from('stock')->where('id_product', $productid)->where('id_product_detail', $itemid)->where('warehouse_id', $warehouse_id);
						$current_stock = $this->db->get()->row();
						
						$data = array(
							'stock' => $current_stock->stock - $qty,
						);
						
						$query_update = $this->db->where('id_product', $productid)
						->where('id_product_detail', $itemid)
						->where('warehouse_id', $warehouse_id)
						->update('stock', $data);

						//get $stock_id
						$stock_id = $current_stock->id;

						//update stock_movement_table
						$movement_data = array(
							'stock_id' => $stock_id,
							'type' => '-',
							'stock_change' => (int) $qty,
							'remark' => 'Indent Order No: ' . $orderid
						);
						$this->db->insert('stock_movement', $movement_data);

						//send email
						$indent_uniqe = $this->customer_m->hash($productid . ' ' .  $order_detailid . ' ' . $orderid);
						$data = array(
							'indent_uniqe_id' => $indent_uniqe
						);
						$this->db->where('id_orders', $orderid);
						$this->db->update('orders', $data);

						//get order data
						$order_data = $this->db->select('*')->from('orders')->where('id_orders', $orderid)->get()->row();
						$customer_id = $order_data->customer_id;

						$data['order'] = $order_data;  
						$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);

						$check_bank_bca = 
						$this->db->select('bank')
						->from('configuration')
						->where('id_configuration', 1)
						->where('bank_transfer', 1)
						->get();

						$check_bank_mandiri = 
						$this->db->select('bank1')
						->from('configuration')
						->where('id_configuration', 1)
						->where('bank_transfer1', 1)
						->get();

						$data['bank_active'] = [];
						if($check_bank_bca->num_rows() > 0){
							$data['bank_active'][0] = 
							$check_bank_bca->row()->bank;
						}
						if($check_bank_mandiri->num_rows() > 0){
							$data['bank_active'][1] = 
							$check_bank_mandiri->row()->bank1;
						}
						
						$email_data = $data;
						//get order details only contain indent
						$email_data['order_details'] = $this->db->select('*')->from('orders_detail')->where('orders_id', $orderid)->where('id_orders_detail', $order_detailid)->where('is_backorder', 'yes')->get()->result();
						// var_dump($email_data);
						// exit();
						//----SEND EMAIL TO CUSTOMER TO PAY FOR INDENT
						$this->db->select('name,customers.phone,type,email')->from('customers')->where('id_customers', $customer_id);
						$email_data['customer'] = $this->db->get()->row();

						$data['order_details'] = $email_data['order_details'];
						
						if($order_data->payment_type !== "midtran"){
							$data['bank'] = $order_data->payment_type; 
							if($data['bank'] == 'bank transfer BCA') {
								$bank_info = $this->db->select('bank')->from('configuration')->where('id_configuration', 1)->get()->row()->bank;
								$data['bank_info'] = $bank_info;
							}else{
								$bank_info = $this->db->select('bank1')->from('configuration')->where('id_configuration', 1)->get()->row()->bank1;
								$data['bank_info'] = $bank_info;
							}
						} 

						$email_data['email'] = $email_data['customer']->email;

						$email_data['emails'] = $this->configuration_m->get_emails();  

						$payment_type = $order_data->payment_type;

						if($payment_type == 'bank transfer BCA'){
							$email_data['bank'] = $this->db->select('bank')->from('configuration')->where('id_configuration', 1)->get()->row()->bank;
						
						} 
						if($payment_type == 'bank transfer MANDIRI'){
							$email_data['bank'] = $this->db->select('bank1')->from('configuration')->where('id_configuration', 1)->get()->row()->bank1;
						}

						$email_data['subject'] = 'Indent Product Ready'; 

						//get order detail and customer detail
						$email_data['order'] = $this->order_m->get_order($orderid);

						if($data['order']->order_language == 'english') {
							$view_file = 'email/english/indent_ready';	
						} else {
							$view_file = 'email/indonesian/indent_ready';		
						}
						// echo "<pre>";
						// var_dump($email_data['bank']);
						// exit();

						// $this->load->view('email/indonesian/indent_ready', $email_data);
						// echo "<pre>";
						// var_dump($data['bank_active']);
						// exit();

						$this->send_email($view_file, $email_data); //function in My_Controller		

					}
					if($witch === "instock"){

					}
					$w = array(
						"id_orders_detail"=>$order_detailid,
						"orders_id"=>$orderid,
						"item_id"=>$itemid,
						"product_id"=>$productid,
					);
					$dt = array(
						"status"=>1,
					);
					$res = $w; 
					$upd = $this->db->update("orders_detail",$dt,$w);
					if($upd){
						$msg = "Sukses"; 
					}
					break;

				case 'fully paid':
					$productid = $this->input->post('productid');
					$order_detailid = $this->input->post('order_detailid');
					$orderid = $this->input->post('orderid');
					$itemid = $this->input->post('itemid');

					$w = array(
						"id_orders_detail"=>$order_detailid,
						"orders_id"=>$orderid,
						"item_id"=>$itemid,
						"product_id"=>$productid,
						"status"=>1,
					);
					$res = $w; 
					$dt = array(
						"status"=>3,
					); 
					$upd = $this->db->update("orders_detail",$dt,$w);
					if($upd){
						$msg = "Sukses"; 
						// $this->db->select('customer_id')->from('orders')->where('id_orders', $orderid);
						// $customer_id = (int) $this->db->get()->row()->customer_id;

						//get add and minus point from order
						$this->db->select('plus_reward')->from('orders')->where('id_orders', $orderid);
						$rewards = $this->db->get()->row();
						$plus_point = (int) $rewards->plus_reward;

						$data['title'] = 'Fully Paid';  
						$data['order'] = $this->order_m->get_order($orderid);
						$data['order_details'] = $this->order_detail_m->get_orders_detail($orderid); 

						$data['customer'] = $this->customer_m->get_customer($data['order']->customer_id);

						//get website data
						$this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1);

						$website_data = $this->db->get()->row();
						$data['logo'] = $website_data->logo;
						$data['website_name'] = $website_data->website_name;
						$data['emails'] = $this->configuration_m->get_emails(); 
						$data['plus_point'] = $plus_point;

						$email_data = $data;
						$email_data['email'] = $data['customer']->email;
						$email_data['subject'] = 'Payment Fully Paid'; 
						if($data['order']->order_language == 'english') {
							$view_file = 'email/english/payment_confirmation';	
						} else {
							$view_file = 'email/indonesian/payment_confirmation';		
						}
						$this->send_email($view_file, $email_data);
					}
					break;
				case 'save noresi':
					$productid = $this->input->post('productid');
					$order_detailid = $this->input->post('order_detailid');
					$orderid = $this->input->post('orderid');
					$itemid = $this->input->post('itemid');
					$inp_noresi = $this->input->post('inp_noresi');
					$witch = $this->input->post('witch');
					$set_stt = 3;

					if($witch === "indent"){
						$set_stt = 3;

					}
					if($witch === "instock"){
						$set_stt = 1;

					}
					$w = array(
						"id_orders_detail"=>$order_detailid,
						"orders_id"=>$orderid,
						"item_id"=>$itemid,
						"product_id"=>$productid,
						"status"=>$set_stt,
					);
					$res = $w; 
					$dt = array(
						"no_resi"=>$inp_noresi,
					); 
					$upd = $this->db->update("orders_detail",$dt,$w);
					if($upd){
						$msg = "Sukses"; 
					}
					break;
				case 'sent':
					$productid = $this->input->post('productid');
					$order_detailid = $this->input->post('order_detailid');
					$inp_noresi = $this->input->post('inp_noresi');
					$orderid = $this->input->post('orderid');
					$itemid = $this->input->post('itemid');
					$witch = $this->input->post('witch');
					$set_stt = 3;

					$data['order'] = $this->db->select('*')->from('orders')->where('id_orders', $orderid)->get()->row();

					if($witch === "indent"){
						$set_stt = 3;
					}
					if($witch === "instock"){
						$set_stt = 1;
					}

					$w = array(
						"id_orders_detail"=>$order_detailid,
						"orders_id"=>$orderid,
						"item_id"=>$itemid,
						"product_id"=>$productid,
						"status"=>$set_stt,
					); 

					$res = $w; 
					$dt = array(
						"status"=>2,
					); 
					$upd = $this->db->update("orders_detail",$dt,$w);

					//SEND EMAIL TO CUSTOMER
					$data['product_detail'] = $this->db->select('*')->from('orders_detail')->where('id_orders_detail',$order_detailid)->get()->row();
					$data['title'] 			= 'Product Picked Up'; 
					//get order detail and customer detail
					$data['orders_detail'] = $this->db->select('*')->from('orders_detail')
					->where('id_orders_detail',$order_detailid)
					->get()->row();

					$data['warehouse']		= $this->db->select('name')->from('warehouse')
					->where('id',$data['orders_detail']->warehouse_id)->get()->row()->name;

					$data['shipping_method']= $this->db->select('name')->from('shipment_method')
					->where('id',$data['orders_detail']->chosen_shipping_id)->get()->row()->name;

					$data['no_resi']		= $this->security->xss_clean($inp_noresi);

					$customer_id 			= $this->db->select('customer_id')->from('orders')->where('id_orders',$orderid)->get()->row()->customer_id;

					$data['customer']		= $this->customer_m->get_customer($customer_id);

					//get website data
					$this->db->select('logo, from_email, website_name, email_smtp_host, email_smtp_port, email_smtp_password, email_smtp')->from('configuration')->where('id_configuration', 1);
					$website_data 			= $this->db->get()->row();
					$data['logo'] 			= $website_data->logo;
					$data['website_name'] 	= $website_data->website_name;
					$data['emails'] 		= $this->configuration_m->get_emails(); 
					
					$email_data = $data;
					$email_data['email'] = $email_data['customer']->email;
					$email_data['subject'] = 'Product Sent'; 

					if($data['order']->order_language == 'english') {
						$view_file = 'email/english/pickedup_confirmation';	
					} else {
						$view_file = 'email/indonesian/pickedup_confirmation';		
					}

					$this->send_email($view_file, $email_data); //function in My_Controller	
					//----end send email

					if($upd){
						$msg = "Sukses"; 								
						$w = array(
							// "id_orders_detail"=>$order_detailid,
							"orders_id"=>$orderid,
							// "item_id"=>$itemid,
							// "product_id"=>$productid,
							// "status"=>2
						);   
						$cek_sttnow = 2;
						$query_sttwo = $this->db->get_where('orders_detail', $w);

						// $res['data_order_details']= $query_sttwo->result();
						foreach ($query_sttwo->result() as $key) {
							if((int)$key->status !== 2){
								$cek_sttnow = (int)$key->status;
								$res['hasil_status'][]= (int)$key->status;
							} 
						}

						$res['akhir_hasil_status']= $cek_sttnow;
						if($cek_sttnow === 2){
							$upd2 = $this->db->update("orders",array(
								"payment_status"=>5,
							),array(
								"id_orders"=>$orderid,
							)); 
							if($upd2){
								$msg = "Sukses"; 								
							}else{
								$msg = "Gagal"; 
							}
						}
					}

					break;
				
				default:
					# code...
					break;
			}
		}

		$rs = $res;
		$rs["msg"] = $msg;
		echo json_encode($rs);
	}

	function ajax_update_status() {
		
		$return 			= 'false';
    	$id_orders 			= $this->input->post('id_orders');
		$barcode_validate 	= $this->input->post('barcode_validate');
		$item_id			= $this->input->post('id_products');
		$is_backorder		= $this->input->post('is_backorder');
		$warehouse_id		= $this->input->post('warehouse_id');
		$id_order_detail	= $this->input->post('id_order_detail');

		//get product id
		$product_id = $this->db->select('product_id')->from('orders_detail')->where('item_id',$item_id)->where('orders_id',$id_orders)->get()->row()->product_id;

		//get product code
		$this->db->select('sku')->from('product_details')->where('id', $item_id);
		$product_code = $this->db->get()->row()->sku;

		$this->db->select('orders.*,orders_detail.*,warehouse.*');
		$this->db->from('orders');
		$this->db->join('orders_detail','id_orders=orders_id');
		$this->db->join('warehouse','orders_detail.warehouse_id=warehouse.id');
		$this->db->where('id_orders',$id_orders);
		$this->db->where('id_orders_detail',$id_order_detail);
		$this->db->where('orders_detail.is_backorder',$is_backorder	);
		$this->db->where('orders_detail.warehouse_id',$warehouse_id	);
		$order = $this->db->get()->row();

		if($product_code == $barcode_validate) {

			if($this->order_m->cek_orderdetail($order->id_orders_detail,0) == true){
				$return = 'false';
			if($order->is_backorder == 'yes'){	
				$cek_stock = 
				$this->db
				->select('stock,stock_virtual')
				->from('stock')
				->where('id_product',$product_id)
				->where('id_product_detail',$item_id)
				->where('warehouse_id',$order->warehouse_id)
				->get()
				->row();				
	
				if($order->warehouse_type == 'virtual'){
					if($order->quantity <= $cek_stock->stock_virtual){
						$order_details = array(
							'status' => 1, 
						);
						$new_stock = array(
							'stock_virtual' => $cek_stock->stock-$order->quantity, 
						);
						$return = "true";
					}else{
						$return = "stok tidak cukup";
					}
				}else{
					if($order->quantity <= $cek_stock->stock){
						$order_details = array(
							'status' => 1, 
						);
						$new_stock = array(
							'stock' => $cek_stock->stock-$order->quantity, 
						);
						
						$return = "true";
					}else{
						$return = "stok tidak cukup";
					}
				}	
				
				if($return == "true"){
					$this->db->where('id_product',$product_id);
					$this->db->where('id_product_detail',$order->item_id);
					$this->db->where('warehouse_id',$order->warehouse_id);
					$this->db->update('stock',$new_stock);
				}				
				
				}else{		
				$order_details = array(
					'status' => 1, 
				);
				$return = "true";
			}
			}else{
				$return = "order telah proses";
			}
			
			if($return == "true"){
				$this->db->where('id_orders_detail',$order->id_orders_detail);
				$this->db->update('orders_detail',$order_details);
			}
			
			echo $return;
		}else{
			echo "Barcode salah, harap cek kembali";					   
		}
	}

	function add_note($id) {

    	if(!isset($_POST['add_note'])) { show_404(); }
    	if($id == NULL) { show_404(); }

    	//check if id is exist
    	$this->db->select('id_orders')->from('orders')->where('id_orders', $id);
    	$count_id = $this->db->get()->num_rows();
    	if($count_id == 0) { show_404(); }

    	$data = array(
    		'admin_note' => $this->security->xss_clean($this->input->post('admin_note'))
    	);	
    	$this->db->where('id_orders', $id);
    	$this->db->update('orders', $data);

    	$this->session->set_flashdata('success', "<br><p style='background:green; color:white; padding:5px; font-weight:bold;'>Update Note Success.</p>");
        redirect('admin/orders/view/' . $id);	
    }

	function ajax_check_stock(){
    	$pr 	= $this->input->post('prod');
    	$qty 	= $this->input->post('qty');
		$wh 	=  $this->input->post('wh');
		
		if(!$this->order_m->cek_stok($pr,$qty,$wh)){
			echo  '<span class="label label-semi">stock tidak cukup</span>';
		}else{
			echo '';
		}
	}

	function change_indent_address() {

		if(!$_POST['change_indent_address']) {
			redirect('admin/orders');
		}

		$order_id = $this->input->post('inp_order_id');
		$customer_id = $this->input->post('inp_customer_id');
		$order_detail_id = $this->input->post('order_detail_id');
		$address = $this->security->xss_clean($this->input->post('address'));
		$province_id = $this->input->post('shipping_province');
		$district_id = $this->input->post('shipping_district');
		$subdistrict_id = $this->input->post('shipping_subdistrict');

		//calculate new shipping fee 
		$this->load->helper('shipping');
		$this->load->helper('rajaongkir');

		$free_shipping_type = 
		$this->db->select('free_shipping_type')
		->from('configuration')
		->where('id_configuration',1)->get()->row()
		->free_shipping_type;

		$condition_freeshipping = false;
		if($free_shipping_type == 'region') {
			$selected_region_province = 
			$this->db->select('*')
			->from('free_shipping_region')
			->where('configuration_id',1)
			->where('province_id',$province_id)
			->get();

			if($selected_region_province->num_rows() > 0){
				$condition_freeshipping = true; 
			}
		}

		//get product detail info
		$order_detail = $this->db->select('*')->from('orders_detail')->where('id_orders_detail', $order_detail_id)->get()->row();

		$shipping_info = calculate_shipping_fee($order_detail->chosen_shipping_id, $order_detail->warehouse_id, $order_detail->product_id, $order_detail->item_id, $order_detail->quantity, $subdistrict_id);

		//add new info into orders_detail table
		$data = array(
			'new_address' => $address,
			'new_province_id' => $province_id,
			'new_district_id' => $district_id,
			'new_subdistrict_id' => $subdistrict_id,
			'shipping_fee' => $shipping_info['total_shipping_fee']
		); 

		$query_customers = $this->db->select("*")
		->from("customers")
		->where('id_customers',$customer_id)
		->get();

		$query_orders = $this->db->select("*")
		->from("orders")
		->where('id_orders',$order_id)
		->get();

		$indent_shipping_fee_remaining = $data['shipping_fee'];

		if($query_customers->num_rows() > 0){
			if($query_customers->row()->type == "regular"){
				if($condition_freeshipping == true){
					$data['shipping_fee'] = 0;
					$indent_shipping_fee_remaining = $data['shipping_fee'];
				}
			}
		}

		// echo "<pre>";
		// var_dump($indent_shipping_fee_remaining); 
		// exit();
		
		$this->db->where('id_orders_detail', $order_detail_id);
		$this->db->update('orders_detail', $data);
		
		$this->db->where('id_orders', $order_id);
		$this->db->update('orders', array(
			"indent_shipping_fee"=>$indent_shipping_fee_remaining,
		));

		$this->session->set_flashdata('success', "<br><p style='background:green; color:white; padding:5px; font-weight:bold;'>Indent Address Changed.</p>");
        redirect('admin/orders/view/' . $order_detail->orders_id);
	}
	
}

https://t.me/RX1948 - 2025