<?php

class Orders extends Admin_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->model(array('order/order_model', 'products/product_model'));
    $this->load->helper(array('cart/cart', 'file', 'category/category'));
    $this->load->library(array('Dmailer'));
  }

    public function index($page = NULL) {
    $pagesize = (int) $this->input->get_post('pagesize');
    $config['limit'] = ( $pagesize > 0 ) ? $pagesize :$pagesize;
    $offset = ( $this->input->get_post('per_page') > 0 ) ? $this->input->get_post('per_page') : 0;
    $base_url = current_url_query_string(array('filter' => 'result'), array('per_page'));
    //.........order searching and sorting start..............................
    if ($this->input->get_post('category_id')) {
      $parent_segment = (int) $this->input->get_post('category_id');
    } else {
      $parent_segment = (int) $this->input->get_post('category_id');
    }
    $page_segment = find_paging_segment();
    $parent_id = ( $parent_segment > 0 ) ? $parent_segment : '0';
    $condtion['status'] = '1';
    $page_title = "Products List";
    if ($parent_id > 0) {
      $condtion['category_id'] = $parent_id;
      $cat_res = get_db_single_row('wps_categories', '*', " category_id='$parent_id'");
      $page_title = $cat_res['category_name'];
      $data['catid'] = $parent_id;
    }
    if ($this->input->get_post('keyword') != '') {
      $product_name = $this->input->get_post('keyword');
      $prod_res = get_db_single_row('wps_products', '*', " product_name ='$product_name'");
      $products_idd = $prod_res['products_id'];
      $condtion['product_id'] = $products_idd;
      $_POST['product_id']=$products_idd;
    }       
        $res_array = $this->order_model->get_orders($offset, $config['limit']);
   //.........end order searching and sorting.................................. 
    $config['total_rows'] = $this->order_model->total_rec_found;
    $data['page_links'] = dashboard_pagination($base_url, $config['total_rows'], $config['limit'], $offset);
    /* Order oprations  */
    if ($this->input->post('unset_as') != '') {
      $this->set_as('wps_order', 'order_id', array('payment_status' => 'Unpaid'));
    }
    if ($this->input->post('ord_status') != '') {
      $posted_order_status = $this->input->post('ord_status');
      switch ($posted_order_status) {
        case '8': {
            $this->set_as('wps_order', 'order_id', array('order_status' => '8', 'order_delivery_date' => date("Y-m-d H:i:s")));
            break;
          }
        case '7': {
            $this->set_as('wps_order', 'order_id', array('order_status' => '6', 'order_returned_date' => date("Y-m-d H:i:s")));
            break;
          }
        case '1': {
            $this->set_as('wps_order', 'order_id', array('order_status' => '1', 'order_confirmed_date' => date("Y-m-d H:i:s")));
            break;
          }
        case '2': {
            $this->set_as('wps_order', 'order_id', array('order_status' => '2', 'order_dispatched_date' => date("Y-m-d H:i:s")));
            break;
          }
        case '3': {
            $this->set_as('wps_order', 'order_id', array('order_status' => '3', 'order_in_transit_date' => date("Y-m-d H:i:s")));
            break;
          }
        case '4': {
            $this->set_as('wps_order', 'order_id', array('order_status' => '4', 'order_out_for_delivery_date' => date("Y-m-d H:i:s")));
            break;
          }

        case '5': {
            $this->set_as('wps_order', 'order_id', array('order_status' => '5', 'order_cancelled_date' => date("Y-m-d H:i:s")));
            break;
          } default: break;
      }
    }

    $status_array = [
        '1' => ['status_title' => 'Confirmed', 'status_date' => 'order_confirmed_date', 'date_title' => 'Order Confirmed On'],
        '0' => ['status_title' => 'Placed', 'status_date' => 'order_received_date', 'date_title' => 'Order Received On'],
        '2' => ['status_title' => 'Dispatched', 'status_date' => 'order_dispatched_date', 'date_title' => 'Order Dispatched On'],
        '3' => ['status_title' => 'In Transit', 'status_date' => 'order_in_transit_date', 'date_title' => 'In Transit Date'],
        '4' => ['status_title' => 'Out for delivery', 'status_date' => 'order_out_for_delivery_date', 'date_title' => 'Order Out For Delivery On'],
        '5' => ['status_title' => 'Cancelled', 'status_date' => 'order_cancelled_date', 'date_title' => 'Order Cancelled On'],
        '6' => ['status_title' => 'Returned', 'status_date' => 'order_returned_date', 'date_title' => 'Order Returned On'],
        '7' => ['status_title' => 'Requested For Return', 'status_date' => 'order_request_for_return_date', 'date_title' => 'Order Requested For Return On'],
        '8' => ['status_title' => 'Delivered', 'status_date' => 'order_delivery_date', 'date_title' => 'Order Delivered On'],
    ];

    $data['status_array'] = $status_array;

    if ($this->input->post('Delete') != '') {
      $posted_order_status = $this->input->post('ord_status');
      $this->set_as('wps_order', 'order_id', array('order_status' => '9'));
      //$this->set_as('wps_order', 'order_id', array('order_status' => 'Deleted'));
    }
    /* End order oprations */
    $data['headingTitle'] = 'Order Lists';
    // print_r($res_array);
    $data['res'] = $res_array;
    $this->load->view('order/view_order_list', $data);
  }

    public function user_order($page = NULL) {
    $pagesize = (int) $this->input->get_post('pagesize');
    $config['limit'] = ( $pagesize > 0 ) ? $pagesize : $this->config->item('pagesize');
    $offset = ( $this->input->get_post('per_page') > 0 ) ? $this->input->get_post('per_page') : 0;
    $base_url = current_url_query_string(array('filter' => 'result'), array('per_page'));
    //.........order searching and sorting start..............................
 
    $page_segment = find_paging_segment();
   // $parent_id = ( $parent_segment > 0 ) ? $parent_segment : '0';
    $condtion['status'] = '1';
    $page_title = "Products List";
        $ordId = (int) $this->uri->segment(4);
        //echo $ordId; exit();
        if ($this->input->get_post('keyword') != '') {
          $res_array = $this->order_model->get_orders($offset, $config['limit']);
        }else{
        $res_array = $this->order_model->get_user_order_master($ordId);
        }
      // echo "<pre>"; print_r($res_array);die;
   //.........end order searching and sorting.................................. 
    $config['total_rows'] = $this->order_model->total_rec_found;
    $data['page_links'] = dashboard_pagination($base_url, $config['total_rows'], $config['limit'], $offset);
   $status_array = [
        '1' => ['status_title' => 'Confirmed', 'status_date' => 'order_confirmed_date', 'date_title' => 'Order Confirmed On'],
        '0' => ['status_title' => 'Placed', 'status_date' => 'order_received_date', 'date_title' => 'Order Received On'],
        '2' => ['status_title' => 'Dispatched', 'status_date' => 'order_dispatched_date', 'date_title' => 'Order Dispatched On'],
        '3' => ['status_title' => 'In Transit', 'status_date' => 'order_in_transit_date', 'date_title' => 'In Transit Date'],
        '4' => ['status_title' => 'Out for delivery', 'status_date' => 'order_out_for_delivery_date', 'date_title' => 'Order Out For Delivery On'],
        '5' => ['status_title' => 'Cancelled', 'status_date' => 'order_cancelled_date', 'date_title' => 'Order Cancelled On'],
        '6' => ['status_title' => 'Returned', 'status_date' => 'order_returned_date', 'date_title' => 'Order Returned On'],
        '7' => ['status_title' => 'Requested For Return', 'status_date' => 'order_request_for_return_date', 'date_title' => 'Order Requested For Return On'],
        '8' => ['status_title' => 'Delivered', 'status_date' => 'order_delivery_date', 'date_title' => 'Order Delivered On'],
    ];

    $data['status_array'] = $status_array;
    /* End order oprations */
    $data['headingTitle'] = 'Order Lists';
    $data['res'] = $res_array;
    $this->load->view('order/user_order_list', $data);
  }
  public function vieworder() {
    $id = (int) $this->uri->segment(4);
    $ordmaster = $this->db->query("SELECT * FROM wps_order WHERE order_id = '" . $id . "'")->row_array();
    $ordDetails = $this->db->query("SELECT * FROM wps_orders_products WHERE order_id = '" . $id . "'")->result_array();

    $data['ordmaster'] = $ordmaster;
    $data['ordDetails'] = $ordDetails;

    $data['headingTitle'] = 'Order Details - Order# ' . $ordmaster['invoice_number'];
    $this->load->view('order/view_order_details', $data);
  }

 public function make_paid($order_id) {
   
    $order_id = (int) $order_id;
    $where = "order_id = '" . $order_id . "'";
    $this->order_model->safe_update('wps_order', array('payment_status' => 'Paid'), $where, FALSE);
    $this->update_stocks($order_id);

    $ordmaster = $this->order_model->get_order_master($order_id);
    $orddetail = $this->order_model->get_order_detail($order_id);

    /* Start  send mail */

    ob_start();
    $mail_subject = $this->config->item('site_name') . " Order overview";
    $from_email = $this->admin_info->admin_email;
    $from_name = $this->config->item('site_name');
    
    $first_name = $ordmaster['first_name'];
    $mail_to = $ordmaster['email'];
    $order_id=$ordmaster['invoice_number'];
    $mobile = $ordmaster['billing_phone'];
    // $sms_message="Dear ".$first_name." , Your Order has been Received With Order id " . $order_id . " ,Thank you Pentimer Publication Team";
    //sendSms($mobile,$sms_message);

    $body = invoice_content_print($ordmaster, $orddetail);
    $msg = ob_get_contents();

    $mail_conf = array(
        'subject' => $this->config->item('site_name') . " Order overview",
        'to_email' => $mail_to,
        'from_email' => $from_email,
        'from_name' => $this->config->item('site_name'),
        'body_part' => $msg);				
    $this->dmailer->mail_notify($mail_conf);
    /* End  send mail */

    $this->session->set_userdata(array('msg_type' => 'success'));
    $this->session->set_flashdata('success', $this->config->item('payment_success'));
    redirect('wps-admin/orders', '');
  }
  
  public function update_stocks($order_id) {
    $order_id = (int) $order_id;
    $condtion = array('field' => "products_id,quantity", 'condition' => "order_id ='$order_id'", 'index' => 'products_id');
    $orders_res = $this->order_model->findAll('wps_orders_products', $condtion);
    if (is_array($orders_res) && !empty($orders_res)) {
      foreach ($orders_res as $v) {
        $qty = $v['quantity'];
      }
    }
  }

    public function export_orderCsv(){ 
        //echo "hhhhhhhh";die;
        // file name 
        $filename = 'sellreport_'.date('Ymd').'.csv'; 
        header("Content-Description: File Transfer"); 
        header("Content-Disposition: attachment; filename=$filename"); 
        header("Content-Type: application/csv; ");
       // get data 
        $ordId = (int) $this->uri->segment(4);
       // echo $ordId; exit();
        $ordmaster[] = $this->order_model->get_order_masterCsv($ordId);   
        if(!empty($ordmaster)){
        $file = fopen('php://output','w');
        $header = array("Order Id","Invoice Number","Amount","First Name","Last Name","Phone","Mobile","Email","Billing Title","Billing Address","Billing City","Billing State","Billing Country","Billing Zipcode","Shipping Address"); 
        fputcsv($file, $header);
        foreach ($ordmaster as $key=>$line){ 
            fputcsv($file,$line); 
        }
        fclose($file); 
        exit; 
        }
    }

    public function export_totalOrder_csv(){ 
        // file name 
        $filename = 'users_'.date('Ymd').'.csv'; 
        header("Content-Description: File Transfer"); 
        header("Content-Disposition: attachment; filename=$filename"); 
        header("Content-Type: application/csv; ");
       // get data       
        //$ordId = (int) $this->uri->segment(4);
        $ordmaster = $this->order_model->get_ordersInCsv();    
        if(!empty($ordmaster)){
        $file = fopen('php://output','w');
        $header = array("Order Id","Invoice Number","Amount","First Name","Last Name","Phone","Mobile","Email","Billing Title","Billing Address","Billing City","Billing State","Billing Country","Billing Zipcode","Shipping Address"); 
        fputcsv($file, $header);
        foreach ($ordmaster as $key=>$line){ 
            fputcsv($file,$line); 
        }
        fclose($file); 
        exit; 
        }
    }

      public function returned_orders($page = NULL) {
    $pagesize = (int) $this->input->get_post('pagesize');
    $config['limit'] = ( $pagesize > 0 ) ? $pagesize : $this->config->item('pagesize');
    $offset = ( $this->input->get_post('per_page') > 0 ) ? $this->input->get_post('per_page') : 0;
    $base_url = current_url_query_string(array('filter' => 'result'), array('per_page'));
    $res_array = $this->order_model->get_orders($offset, $config['limit'], $condition = " AND order_status = 'Returned'");
    $config['total_rows'] = $this->order_model->total_rec_found;
    $data['page_links'] = admin_pagination($base_url, $config['total_rows'], $config['limit'], $offset);


    $data['heading_title'] = 'Order Lists';
    $data['res'] = $res_array;
    $this->load->view('order/view_order_list', $data);
  }

  public function tracking_details() {
    $id = $this->uri->segment(4);

    $this->form_validation->set_rules('tracking_code', 'Tracking Code', 'trim|required|max_length[250]');
    $this->form_validation->set_rules('courier_partner', 'Courier Partner', 'trim|required|max_length[250]');
    $this->form_validation->set_rules('expected_delivery_date', 'Expected Delivery Date', 'required');
    $this->form_validation->set_rules('tracking_text', 'Tracking Details', 'trim|required|max_length[450]');
    $this->form_validation->set_error_delimiters("<div class='required fs12'>", "</div>");
    if ($this->form_validation->run() == TRUE) {
      $posted_data = array(
          'tracking_code' => $this->input->post('tracking_code'),
          'courier_partner' => $this->input->post('courier_partner'),
          'expected_delivery_date' => $this->input->post('expected_delivery_date'),
          'order_status' => 'Dispatched',
          'tracking_text' => $this->input->post('tracking_text'),
      );
      $where = "order_id = " . $id;
      $this->order_model->safe_update('wps_order', $posted_data, $where, FALSE);
      $this->session->set_userdata(array('msg_type' => 'success'));
      $this->session->set_flashdata('success', 'Tracking Details have been Updated!!!');
      redirect('wps-admin/orders/tracking_details/' . $id, '');
    }

    $sql = "SELECT tracking_code, courier_partner, expected_delivery_date, tracking_text, invoice_number FROM wps_order WHERE order_id = '" . $id . "'";
    $result = $this->db->query($sql)->row_array();
    $data['result'] = $result;
    $data['heading_title'] = "Manage Shipping and COD";
    $this->load->view('order/view_tracking_details', $data);
  }
  public function ajx_dtl($id) {
    $ord = get_db_single_row('wps_order', '*', "`order_id`='$id'");
    echo json_encode($ord);
    die;
  }
  
  public function update_dispatch_dtl() {
     
    $resp['status'] = 'F';
    $resp['msg'] = '';
    
      $v = $this->form_validation;
      $v->set_rules('package_length', 'Package Length', 'required|numeric');
      $v->set_rules('package_width', 'Package Width', 'required|numeric');
      $v->set_rules('package_height', 'Package Height', 'required|numeric');
      $v->set_rules('package_weight', 'Package Weight', 'required|numeric');
      $v->set_rules('order_id', 'Order not selected', 'required|numeric');
      if ($v->run()) {
        $data_ins = array(
            "package_length" => $this->input->post('package_length'),
            "package_width" => $this->input->post('package_width'),
            "package_height" => $this->input->post('package_height'),
            "package_weight" => $this->input->post('package_weight'),
        );
        $order_id = $this->input->post('order_id');
        $this->order_model->safe_update('wps_order', $data_ins, "`order_id`='$order_id'");
        $resp['status'] = 'T';
        $resp['order_id'] = $order_id;
      } else {
        $resp['status'] = 'F';
        $resp['msg'] = validation_errors();
      }

    echo json_encode($resp);
    die;
  }
  
   public function dispacth($ord_id) {

    $ord = $this->order_model->get_order_master($ord_id);
    $prds = $this->order_model->get_order_detail($ord['order_id']);

    if ($ord['tracking_code'] == '') {

      $pkg_weight = (float) @$ord['package_weight'];
      $pkg_len = (float) @$ord['package_length'];
      $pkg_height = (float) @$ord['package_height'];
      $pkg_width = (float) @$ord['package_width'];

      $ord_type = "Prepaid";
      $grandTotal = 0;
      $total_order_value = 1;
      if ($ord['payment_method'] == 'Cash' || $ord['payment_method'] == 'COD') {
        $ord_type = "COD";
      }
      $grandTotal = $ord['total_amount'];
      $total_order_value = $grandTotal;
      $collectableAmount = ($ord_type == 'COD') ? $total_order_value : 0;

      $dataArray = array();
      $proArray = array();
      foreach ($prds as $k => $r) {
        $proArray[] = array(
            "name" => $r['product_name'],
            "sku" => $r['product_code'],
            "units" => $r['quantity'],
            "selling_price" => $r['product_price']
        );
      }

//      trace($ord);
//      exit;
      $dataArray = array(
          "order_id" => $ord['order_id'],
          "order_date" => $ord['order_received_date'],
          "channel_id" => "2071865",
          "billing_customer_name" => $ord['shipping_name'],
          "billing_last_name" => "",
          "billing_address" => $ord['shipping_address'],
          "billing_city" => $ord['shipping_city'],
          "billing_pincode" => $ord['shipping_zipcode'],
          "billing_state" => $ord['shipping_state'],
          "billing_country" => "India",
          "billing_email" => $ord['email'],
          "billing_phone" => $ord['shipping_phone'],
          "shipping_is_billing" => true,
          "order_items" => $proArray,
          "payment_method" => $ord_type,
          "sub_total" => $grandTotal,
          "length" => $pkg_len,
          "breadth" => $pkg_width,
          "height" => $pkg_height,
          "weight" => $pkg_weight,
          "pickup_location" => "Delhi",
          "vendor_details" => array(
              "email" => "support@toyzoo.co.in",
              "phone" => "9717813544",
              "name" => "Toyzoo",
              "address" => "9762, Gali Neem Wali, Nawab Ganj, Azad Market",
              "address_2" => "",
              "city" => "New Delhi",
              "state" => "Delhi",
              "country" => "India",
              "pin_code" => "110006",
              "pickup_location" => "Delhi",
          ),
      );
      //
//      trace($dataArray);
//      exit;
      echo json_encode($dataArray);
      $response = $this->shiprocket->createWrapper($dataArray);
      echo '<br /><br />';
      echo $response;
      $resp = (array) json_decode($response);
//      trace($resp);
//      exit;
      //start processing
      if ($resp['status'] == 1) {
        $update_data = array(
            'shiprocketRequest' => json_encode($dataArray),
            'shiprocketResponse' => $response,
            'tracking_code' => $resp['awb_code']
        );
        $this->order_model->safe_update('wps_order', $update_data, "`order_id`='$ord_id'");
        $ret_data['status'] = TRUE;

        $this->session->set_userdata(array('msg_type' => 'success'));
        $this->session->set_flashdata('success', 'Dispatch Order Created at Shiprocket Successfully.  Order No. ' . $ord_id);
      } else {
        $update_data = array(
            'shiprocketRequest' => json_encode($dataArray),
            'shiprocketResponse' => $response,
        );
        $this->order_model->safe_update('wps_order', $update_data, "`order_id`='$ord_id'");

        $this->session->set_userdata(array('msg_type' => 'error'));
        $this->session->set_flashdata('error', 'Dispatch Order not created, Please Try Again OR Contact Shiprocket Team. Order No. ' . $ord_id);
      }
    } else {
      $this->session->set_userdata(array('msg_type' => 'error'));
      $this->session->set_flashdata('error', 'Dispatch Order already Created. Order No. ' . $ord_id);
    }
    redirect('wps-admin/orders/', '');
  }

  public function track($ord_id) {
    $ord = get_db_single_row('wps_order', 'shipping_tracking_id,shipping_tracking_dtl_id');
    track_order($ord->shipping_tracking_dtl_id);
    $data['heading_title'] = 'Track Delivery';
    $this->load->view('order/track_delivery');
  }
}

// End of controller