<?php

defined('ABSPATH') || die('Access Denied');

class EcommercewdModelOrders extends EcommercewdModel {
  ////////////////////////////////////////////////////////////////////////////////////////
  // Events                                                                             //
  ////////////////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////////////
  // Constants                                                                          //
  ////////////////////////////////////////////////////////////////////////////////////////
  const MAX_PRODUCT_NAME_LENGTH = 20;
  const MAX_PRODUCT_NAMES_LENGTH = 30;

  ////////////////////////////////////////////////////////////////////////////////////////
  // Variables                                                                          //
  ////////////////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////////////
  // Constructor & Destructor                                                           //
  ////////////////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////////////
  // Public Methods                                                                     //
  ////////////////////////////////////////////////////////////////////////////////////////
  public function get_order_row($order_id = 0) {
    $model_options = WDFHelper::get_model('options');
    $options = $model_options->get_options();
    if ($order_id == 0) {
      $order_id = get_query_var($options->option_endpoint_orders_displayorder);
      if (!$order_id) {
        $order_id = get_query_var($options->option_endpoint_orders_printorder);
        if (!$order_id) {
          $order_id = WDFInput::get('order_id', 0, 'int');
        }
      }
    }
    $decimals = $options->option_show_decimals == 1 ? 2 : 0;
    $j_user = wp_get_current_user();

    // get order row
    $row_order = WDFDb::get_row_by_id('orders', $order_id);
    if ($row_order->id == 0) {
      WDFHelper::show_error(2);
    }

    // check if user can access this order
    $can_user_access = false;
    if (is_user_logged_in()) {
      if ($row_order->j_user_id == $j_user->ID) {
        $can_user_access = true;
      }
    }
    else {
      $order_rand_ids = WDFInput::cookie_get_array('order_rand_ids');
      if ((empty($order_rand_ids) == false) && (in_array($row_order->rand_id, $order_rand_ids))) {
        $can_user_access = true;
      }
    }
    if ($can_user_access == false) {
      $model_options->enqueue_message(__('Wrong request', 'wde'), 'danger');
      wp_redirect(get_permalink($options->option_orders_page));
      exit;
    }
    if ($row_order->shipping_type == 'per_order') {
      $row_order->shipping_method_price_text = WDFText::wde_number_format($row_order->shipping_method_price, $decimals);
      $row_order->shipping_method_price_text .= $row_order->currency_code;
    }
    else {
      $row_order->shipping_method_price_text = '';
    }
    // add order products data, total price and currency
    $row_order = $this->add_order_products_data($row_order, true);
    if ($row_order === false) {
      WDFHelper::show_error(2);
    }
    return $row_order;
  }

  public function add_order_products_data($row_order, $max_product_name_length = false ) {
    global $wpdb;

    $model_options = WDFHelper::get_model('options');
    $options = $model_options->get_options();

    $decimals = $options->option_show_decimals == 1 ? 2 : 0;

    // order products
    $query = 'SELECT T_ORDERP_RODUCTS.product_id AS id';
    $query .= ', T_ORDERP_RODUCTS.product_name AS name';
    $query .= ', T_ORDERP_RODUCTS.product_image AS image';
    $query .= ', T_ORDERP_RODUCTS.currency_code';
    $query .= ', T_ORDERP_RODUCTS.product_price AS price';
    $query .= ', T_ORDERP_RODUCTS.tax_price';
    $query .= ', T_ORDERP_RODUCTS.shipping_method_id';
    $query .= ', T_ORDERP_RODUCTS.shipping_method_name';
    $query .= ', T_ORDERP_RODUCTS.shipping_method_price';
    $query .= ', T_ORDERP_RODUCTS.product_count AS count';
    $query .= ', T_ORDERP_RODUCTS.product_parameters AS parameters';
    // $query .= ', T_PRODUCTS.enable_shipping';
    $query .= ' FROM ' . $wpdb->prefix . 'ecommercewd_orderproducts AS T_ORDERP_RODUCTS';
    // $query .= ' LEFT JOIN ' . $wpdb->prefix . 'ecommercewd_products AS T_PRODUCTS ON T_ORDERP_RODUCTS.product_id = T_PRODUCTS.id';
    $query .= ' WHERE T_ORDERP_RODUCTS.order_id = ' . $row_order->id;
    $row_order->product_rows = $wpdb->get_results($query);

    if ($wpdb->last_error) {
      return false;			
    }

    $products_price = 0;
    $tax_price = 0;
    $shipping_price = 0;
    $total_price = 0;
    if (is_array($row_order->product_rows)) {
      foreach ($row_order->product_rows as $product_row) {
        $product_row->enable_shipping = esc_attr(get_post_meta($product_row->id, 'wde_enable_shipping', TRUE));
        if ($max_product_name_length == false) {
          if (strlen($product_row->name) > self::MAX_PRODUCT_NAME_LENGTH) {
            $product_row->name = WDFTextUtils::truncate($product_row->name, self::MAX_PRODUCT_NAME_LENGTH);
          }
        }

        // subtotal
        $product_row->subtotal = ($product_row->price + $product_row->tax_price) * $product_row->count + $product_row->shipping_method_price;

        // prices
        $product_row->price_text = WDFText::wde_number_format($product_row->price, $decimals);
        $product_row->tax_price_text = WDFText::wde_number_format($product_row->tax_price, $decimals);
        if ($row_order->shipping_type != 'per_order' && $product_row->shipping_method_id) {
          $product_row->shipping_method_price_text = WDFText::wde_number_format($product_row->shipping_method_price, $decimals);
        }
        else {
          $product_row->shipping_method_price_text = '';
        }
        $product_row->subtotal_text = WDFText::wde_number_format($product_row->subtotal, $decimals);

        // currency codes
        $product_row->price_text .= $product_row->currency_code;
        $product_row->tax_price_text .= $product_row->currency_code;
        if ($product_row->shipping_method_price_text) {
          $product_row->shipping_method_price_text .= $product_row->currency_code;
        }
        $product_row->subtotal_text .= $product_row->currency_code;

        // order prices
        $products_price += $product_row->price * $product_row->count;
        $tax_price += $product_row->tax_price * $product_row->count;
        $shipping_price += $product_row->shipping_method_price;
        $total_price += $product_row->subtotal;
      }
    }

    // total price text and currency symbol
    $row_order->products_price = $products_price;
    $row_order->tax_price = $tax_price;
    $row_order->shipping_price = $shipping_price;
    $row_order->total_price = $total_price;
    $row_order->products_price = WDFText::wde_number_format($row_order->products_price, $decimals) . $row_order->currency_code;
    $row_order->tax_price = WDFText::wde_number_format($row_order->tax_price, $decimals) . $row_order->currency_code;
    $row_order->shipping_price = WDFText::wde_number_format($row_order->shipping_price, $decimals) . $row_order->currency_code;
    $row_order->total_price_text = WDFText::wde_number_format($row_order->total_price, $decimals) . $row_order->currency_code;

    return $row_order;
  }

  public function get_orders_data() {
      $pagination = $this->get_orders_pagination();
      $order_rows = $this->get_order_rows($pagination);

      $data = array();
      $data['pagination'] = $pagination;
      $data['order_rows'] = $order_rows;
      return $data;
  }

  public function get_order_rand_id() {
    global $wpdb;
    $query = 'SELECT rand_id FROM ' . $wpdb->prefix . 'ecommercewd_orders';
    $existing_rand_ids = $wpdb->get_col($query);

    if ($wpdb->last_error) {
      return FALSE;
    }

    do {
      $rand_id = rand(10000000, 99999999);
    } while (in_array($rand_id, $existing_rand_ids) == true);
    return $rand_id;
  }

  public function get_print_order() {
    $order_row = $this->get_order_row();	
    $product_names_invoice = array();
    $row = new stdClass();
    $row->id = $order_row->id;
    $row->checkout_date = $order_row->checkout_date;
    $row->payment_method = $order_row->payment_method;
    $row->billing_data_first_name = $order_row->billing_data_first_name;
    $row->billing_data_middle_name = $order_row->billing_data_middle_name;
    $row->billing_data_last_name = $order_row->billing_data_last_name;
    $row->billing_data_address = $order_row->billing_data_address;
    $row->billing_data_state = $order_row->billing_data_state;
    $row->billing_data_zip_code = $order_row->billing_data_zip_code;
    $row->billing_data_city = $order_row->billing_data_city;
    $row->billing_data_country = $order_row->billing_data_country;
    $row->billing_data_email = $order_row->billing_data_email;
    $row->billing_data_phone = $order_row->billing_data_phone;
    $row->billing_data_fax = $order_row->billing_data_fax;
    $row->shipping_data_first_name = $order_row->shipping_data_first_name;
    $row->shipping_data_middle_name = $order_row->shipping_data_middle_name;
    $row->shipping_data_last_name = $order_row->shipping_data_last_name;
    $row->shipping_data_address = $order_row->shipping_data_address;
    $row->shipping_data_state = $order_row->shipping_data_state;
    $row->shipping_data_zip_code = $order_row->shipping_data_zip_code;
    $row->shipping_data_city = $order_row->shipping_data_city;
    $row->shipping_data_country = $order_row->shipping_data_country;
    $row->shipping_type = $order_row->shipping_type;
    $row->shipping_method_price = $order_row->shipping_method_price;
    $row->shipping_method_price_text = $order_row->shipping_method_price_text;

    if (is_array($order_row->product_rows)) {
      foreach ($order_row->product_rows as $order_product) {
        $product_names_invoice[] = array(
                'product_name'               => $order_product->name,
                'product_price_text'         => $order_product->price_text,
                'tax_price_text'             => $order_product->tax_price_text,
                'shipping_method_price_text' => $order_product->shipping_method_price_text,
                'product_count'              => $order_product->count,
                'subtotal_text'              => $order_product->subtotal_text,
                'currency_code'              => $order_product->currency_code
                );	

      }
    }
    $row->product_names_invoice = $product_names_invoice;
    return $row;
  }

  ////////////////////////////////////////////////////////////////////////////////////////
  // Getters & Setters                                                                  //
  ////////////////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////////////////
  // Private Methods                                                                    //
  ////////////////////////////////////////////////////////////////////////////////////////
  private function get_orders_pagination() {
    global $wpdb;

    $theme = WDFHelper::get_model('theme')->get_theme_row();

    // get orders count
    $query = 'SELECT COUNT(*)';
    $query .= ' FROM ' . $wpdb->prefix . 'ecommercewd_orders';
    if (is_user_logged_in()) {
      $j_user = wp_get_current_user();
      $query .= ' WHERE j_user_id = ' . $j_user->ID;
    } else {
      $order_rand_ids = WDFInput::cookie_get_array('order_rand_ids', array());
      if (empty($order_rand_ids) == false) {
        $query .= ' WHERE j_user_id = 0';
        $query .= ' AND rand_id IN (' . implode(',', $order_rand_ids) . ')';
      } else {
        $query .= ' WHERE 0';
      }
    }
    $orders_count = $wpdb->get_var($query);

    if ($wpdb->last_error) {
      WDFHelper::show_error(2);
    }

    $limit_start = WDFInput::get('pagination_limit_start', 0, 'int');
    $limit = WDFInput::get('pagination_limit', $theme->products_count_in_page, 'int');
    $limit = $limit ? $limit : $theme->products_count_in_page;

    $pagination = new stdClass();
    $pagination->limitstart = $limit_start;
    $pagination->limit = $limit;
    $pagination->current = $limit_start / $limit + 1;
    $pagination->start = 1;
    $pagination->stop = ceil($orders_count / $limit);
    $pagination->total = $pagination->stop;
    return $pagination;
  }

  private function get_order_rows($pagination) {
    global $wpdb;

    $model_options = WDFHelper::get_model('options');
    $options = $model_options->get_options();

    $decimals = $options->option_show_decimals == 1 ? 2 : 0;

    $query = 'SELECT T_ORDERS.id';
    $query .= ', GROUP_CONCAT(T_ORDER_PRODUCTS.id SEPARATOR ",") AS str_order_product_ids';
    $query .= ', GROUP_CONCAT(DISTINCT T_ORDER_PRODUCTS.product_name SEPARATOR ", ") AS product_names';
    $query .= ', T_ORDERS.checkout_date';
    $query .= ', T_ORDERS.status_name';
    $query .= ', SUM(T_ORDER_PRODUCTS.product_price * T_ORDER_PRODUCTS.product_count) AS price';
    $query .= ', SUM(T_ORDER_PRODUCTS.tax_price * T_ORDER_PRODUCTS.product_count) AS tax_price';
    $query .= ', SUM(T_ORDER_PRODUCTS.shipping_method_price) + T_ORDERS.shipping_method_price AS shipping_price';
    $query .= ', T_ORDERS.currency_code';
    $query .= ' FROM ' . $wpdb->prefix . 'ecommercewd_orders AS T_ORDERS';
    $query .= ' LEFT JOIN ' . $wpdb->prefix . 'ecommercewd_orderproducts AS T_ORDER_PRODUCTS ON T_ORDER_PRODUCTS.order_id = T_ORDERS.id';
    if (is_user_logged_in()) {
      $j_user = wp_get_current_user();
      $query .= ' WHERE T_ORDERS.j_user_id = ' . $j_user->ID;
    } else {
      $order_rand_ids = WDFInput::cookie_get_array('order_rand_ids', array());
      if (empty($order_rand_ids) == false) {
        $query .= ' WHERE T_ORDERS.j_user_id = 0';
        $query .= ' AND T_ORDERS.rand_id IN (' . implode(',', $order_rand_ids) . ')';
      } else {
        $query .= ' WHERE 0';
      }
    }
    $query .= ' GROUP BY T_ORDERS.id';
    $query .= ' ORDER BY T_ORDERS.checkout_date DESC';
    $query .= ' LIMIT ' . $pagination->limitstart . ', ' . $pagination->limit;
    $order_rows = $wpdb->get_results($query);

    if ($wpdb->last_error) {
      WDFHelper::show_error(2);
    }

    // additional data
    if (is_array($order_rows)) {
      foreach ($order_rows as $order_row) {
        // order_link
        $order_row->order_link = WDFPath::add_pretty_query_args(get_permalink($options->option_orders_page), $options->option_endpoint_orders_displayorder, $order_row->id, TRUE); 
        $order_row->print_orders_link = WDFPath::add_pretty_query_args(get_permalink($options->option_orders_page), $options->option_endpoint_orders_printorder, $order_row->id, TRUE); 
        $order_row->pdf_invoice_link = ''; 

        // order product ids
        $order_row->order_product_ids = explode(',', $order_row->str_order_product_ids);

        // product names
        if (strlen($order_row->product_names) > self::MAX_PRODUCT_NAMES_LENGTH) {
          $order_row->product_names = WDFTextUtils::truncate($order_row->product_names, self::MAX_PRODUCT_NAMES_LENGTH);
        }

        // product images
        $product_images = array();
        if (is_array($order_row->order_product_ids)) {
          foreach ($order_row->order_product_ids as $order_product_id) {
            $row_order_product = WDFDb::get_row_by_id('orderproducts', $order_product_id);
            $product_images[] = $row_order_product->product_image;
          }
        }
        $order_row->product_images = $product_images;
        $order_row->subtotal = $order_row->price + $order_row->tax_price + $order_row->shipping_price ;
        // prices
        $order_row->price_text = WDFText::wde_number_format($order_row->price, $decimals);
        $order_row->tax_price_text = WDFText::wde_number_format($order_row->tax_price, $decimals);
        $order_row->shipping_price_text = WDFText::wde_number_format($order_row->shipping_price, $decimals);
        $order_row->total_price_text = WDFText::wde_number_format($order_row->subtotal, $decimals);

        // currency codes
        $order_row->price_text .= $order_row->currency_code;
        $order_row->tax_price_text .= $order_row->currency_code;
        $order_row->shipping_price_text .= $order_row->currency_code;
        $order_row->total_price_text .= $order_row->currency_code;
      }
    }

    return $order_rows;
  }

  ////////////////////////////////////////////////////////////////////////////////////////
  // Listeners                                                                          //
  ////////////////////////////////////////////////////////////////////////////////////////
}