<?php 
class Order_model extends CI_Model {
	
	public function _consruct(){
		parent::_construct();
 	}

 	public function getOrders(){
    $this->db->select("ORD.*,PRD.product_name,
                       TRIM(CONCAT(CUST.first_name,' ',IFNULL(CUST.last_name,''))) as customer_name");
    $this->db->from('orders AS ORD');
    $this->db->join('products AS PRD','PRD.product_id = ORD.product_id');
    $this->db->join('customers AS CUST','CUST.customer_id = ORD.customer_id');
    $result = $this->db->get()->result();
    if(!empty($result)){
      return $result;
    }
  }

  public function getOrderDetails($order_id){
    if($order_id == ''){
      return 0;
    }
    $result = $this->db->query("SELECT ORD.*,PRD.product_name,PRD.short_description,PRDB.brand_name,
                                       TRIM(CONCAT(CUST.first_name,' ',IFNULL(CUST.last_name,''))) AS customer_name,
                                CASE WHEN ORD.status = 0 THEN 'Inactive'
                                WHEN ORD.status = 1 THEN 'Payment Processing'
                                WHEN ORD.status = 2 THEN 'Order Places'
                                WHEN ORD.status = 3 THEN 'Order Packed'
                                WHEN ORD.status = 4 THEN 'Order Shipped'
                                WHEN ORD.status = 5 THEN 'Ordered Delivered'
                                WHEN ORD.status = 6 THEN 'Returned'
                                WHEN ORD.status = 7 THEN 'Cancelled'
                                WHEN ORD.status = 8 THEN 'Deleted'
                                ELSE 'Payment Failed' END AS ord_status
                                FROM orders AS ORD 
                                JOIN products AS PRD on PRD.product_id = ORD.product_id 
                                JOIN product_brand AS PRDB on PRDB.brand_id = PRD.brand_id 
                                JOIN customers AS CUST on CUST.customer_id = ORD.customer_id 
                                WHERE ORD.order_id = $order_id");
    if(empty($result)){
      return;
    }
    return $result->row();
  }

  public function getProductImage($order_id){
    $result = $this->db->query("SELECT PRDI.image FROM orders AS ORD join product_images AS PRDI on PRDI.product_id = ORD.product_id WHERE ORD.order_id = $order_id");

    return (empty($result))?'':$result->result();
  }

  public function changeOrderStatus($data=array()){
    $order_id = decode_param($data['order_id']);
    if(empty($order_id) || $data['status'] == '' || empty($data['expected_date'])){
      return 0;
    }
    if($data['status'] == '3' || $data['status'] == '4'){
      $data['expected_delivery'] = $data['expected_date'];
    }else if($data['status'] == '5'){
      $data['delivered'] = $data['expected_date'];
    }
    unset($data['expected_date'],$data['order_id']);

    $status = 0;
    if($this->db->update('orders',$data,array('order_id'=>$order_id))){
      $status = 1;
    }
    return $status;
  }
}
?>
