<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Admin_Controller extends MY_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->library(array(
        'sitepanel/jquery_pagination', 'dmailer'
    ));
    $this->load->model(array(
        'utils_model'
    ));
    $this->admin_lib->is_admin_logged_in();
  }

  public function update_status($table, $auto_field = 'id') {
    $action = $this->input->post('status_action', TRUE);
    $arr_ids = $this->input->post('arr_ids', TRUE);
    $category_count = $this->input->post('category_count', TRUE);
    $product_count = $this->input->post('product_count', TRUE);
    $gallery_count = $this->input->post('gallery_count', TRUE);
    $controller = $this->router->fetch_class();
    $method = $this->router->fetch_method();

    if (is_array($arr_ids)) {
      $str_ids = implode(',', $arr_ids);
      if ($action == 'Activate') {
        foreach ($arr_ids as $k => $v) {
          $data = array(
              'status' => '1'
          );
          if ($controller == "members") {
            $data = array(
                'status' => '1',
                'is_verified' => '1'
            );
          } else {
            $data = array(
                'status' => '1'
            );
          }
          if ($controller == 'products') {
            // mail to user for uploading new product.
            $productDets = get_db_single_row($table, 'product_name, customers_id', "products_id = '" . $v . "'");
            $toEmail = get_db_single_row('wps_customers', 'user_email', "customers_id = '" . $productDets['customers_id'] . "'");
            if ($toEmail['user_email']) {
              $content = file_get_contents(site_url() . 'mailer/product-activate.html');
              $subject = 'New Product Activated @ Natural Therapy India';
              $body = $content;
              $name = 'Member';
              $body = str_replace('{mem_name}', $name, $body);
              $body = str_replace('{product_name}', $productDets['product_name'], $body);
              $body = str_replace('{admin_email}', $this->admin_info->admin_email, $body);
              $body = str_replace('{site_name}', $this->config->item('site_name'), $body);

              $mail_conf = array(
                  'subject' => $subject,
                  'to_email' => $toEmail,
                  'from_email' => $this->admin_info->admin_email,
                  'from_name' => $this->config->item('site_name'),
                  'body_part' => $body
              );
              // trace($mail_conf);
              // exit;
              $this->dmailer->mail_notify($mail_conf);
              // mail end here
            }
          }
          if ($controller == 'members') {
            activateAllProductsByMember($v);
          }
          $where = "$auto_field ='$v'";
          $this->utils_model->safe_update($table, $data, $where, FALSE);
          $this->session->set_userdata(array(
              'msg_type' => 'success'
          ));
          $this->session->set_flashdata('success', lang('activate'));
        }
      }
      if ($action == 'Deactivate') {
        foreach ($arr_ids as $k => $v) {
          $countChild = 0;
          if ($controller == 'category') {
            //$countChild = count_record('wps_products', "FIND_IN_SET (" . $v . ",category_links) AND status !='2'");
            //change status of category 
            $this->db->query("UPDATE wps_products SET status = '0' WHERE FIND_IN_SET (" . $v . ",category_links) AND status !='0'");
            //change status of Products
            changeCategoryStatus($v);
          }
          if ($countChild > 0) {
            $this->session->set_userdata(array(
                'msg_type' => 'error'
            ));
            $this->session->set_flashdata('error', lang('child_to_deactivate'));
          } else {

            if ($controller == 'products') {
              // mail to user for uploading new product.
              $productDets = get_db_single_row($table, 'product_name, customers_id', "products_id = '" . $v . "'");
              $toEmail = get_db_single_row('wps_customers', 'user_email', "customers_id = '" . $productDets['customers_id'] . "'");
              if ($toEmail['user_email']) {
                $content = file_get_contents(site_url() . 'mailer/product-deactivate.html');
                $subject = 'Attention! Product Deactivated @ Natural Therapy India';
                $body = $content;
                $name = 'Member';
                $body = str_replace('{mem_name}', $name, $body);
                $body = str_replace('{product_name}', $productDets['product_name'], $body);
                $body = str_replace('{admin_email}', $this->admin_info->admin_email, $body);
                $body = str_replace('{site_name}', $this->config->item('site_name'), $body);

                $mail_conf = array(
                    'subject' => $subject,
                    'to_email' => $toEmail,
                    'from_email' => $this->admin_info->admin_email,
                    'from_name' => $this->config->item('site_name'),
                    'body_part' => $body
                );
                // trace($mail_conf);
                // exit;
                $this->dmailer->mail_notify($mail_conf);
                // mail end here
              }
            }
            if ($controller == 'members') {
              deactivateAllProductsByMember($v);
              // mail to user for uploading new product.
              $memberDets = get_db_single_row($table, 'first_name, last_name, user_email', "customers_id = '" . $v . "'");
              $toEmail = $memberDets['user_email'];
              if ($toEmail) {
                $content = file_get_contents(site_url() . 'mailer/member-deactivate.html');
                $subject = 'Attention! Account Dectivated @ Natural Therapy India';
                $body = $content;
                $name = $memberDets['first_name'] . ' ' . $memberDets['last_name'];
                $body = str_replace('{mem_name}', $name, $body);
                $body = str_replace('{admin_email}', $this->admin_info->admin_email, $body);
                $body = str_replace('{site_name}', $this->config->item('site_name'), $body);

                $mail_conf = array(
                    'subject' => $subject,
                    'to_email' => $toEmail,
                    'from_email' => $this->admin_info->admin_email,
                    'from_name' => $this->config->item('site_name'),
                    'body_part' => $body
                );
                // trace($mail_conf);
                // exit;
                $this->dmailer->mail_notify($mail_conf);
                // mail end here
              }
            }

            $data = array(
                'status' => '0'
            );
            $where = "$auto_field ='$v'";
            $this->utils_model->safe_update($table, $data, $where, FALSE);
            $this->session->set_userdata(array(
                'msg_type' => 'success'
            ));
            $this->session->set_flashdata('success', lang('deactivate'));
          }
        }
      }

      if ($action == 'Delete') {
        foreach ($arr_ids as $k => $v) {
          $countChild = 0;
          if ($controller == 'category') {
            $countChild = count_record('wps_products', "FIND_IN_SET (" . $v . ",category_links) AND status !='2'");
          }

          //Start Delete process
          if ($countChild > 0) {
            $this->session->set_userdata(array(
                'msg_type' => 'error'
            ));
            $this->session->set_flashdata('error', lang('child_to_delete'));
          } else {

            //Delete Respective Images
            //delete all products and images of member
            if ($controller == 'members') {
              deleteAllProductsByMember($v);
            }

            if ($controller == 'banners') {
              $imageName = get_db_field_value($table, "banner_image", "WHERE " . $auto_field . " = '" . $v . "'");
              $unlink_image = array('source_dir' => "banner", 'source_file' => $imageName);
              removeImage($unlink_image);
            }
            if ($controller == 'category') {
              $imageName = get_db_field_value($table, "category_image", "WHERE " . $auto_field . " = '" . $v . "'");
              $unlink_image = array('source_dir' => "category", 'source_file' => $imageName);
              removeImage($unlink_image);

              $imageName1 = get_db_field_value($table, "bg_image", "WHERE " . $auto_field . " = '" . $v . "'");
              $unlink_image1 = array('source_dir' => "category", 'source_file' => $imageName1);
              removeImage($unlink_image1);

              $imageName2 = get_db_field_value($table, "category_icon", "WHERE " . $auto_field . " = '" . $v . "'");
              $unlink_image2 = array('source_dir' => "category", 'source_file' => $imageName2);
              removeImage($unlink_image2);
            }
            if ($controller == 'products') {
              $resPm = $this->db->query("SELECT id, media FROM wps_products_media WHERE products_id = '" . $v . "'")->result_array();
              foreach ($resPm as $pmRes) {
                $imageName = $pmRes['media'];
                $unlink_image = array('source_dir' => "product_images", 'source_file' => $imageName);
                $unlink_image1 = array('source_dir' => "product_images/thumb", 'source_file' => $imageName);
                //trace($unlink_image);
                removeImage($unlink_image);
                removeImage($unlink_image1);
                $this->db->query("DELETE FROM wps_products_media WHERE id = '" . $pmRes['id'] . "'");
              }
            }
            if ($controller == 'blog') {
              $imageName = get_db_field_value($table, "article_image", "WHERE " . $auto_field . " = '" . $v . "'");
              $unlink_image = array('source_dir' => "blog", 'source_file' => $imageName);
              removeImage($unlink_image);
            }
            //Remove Cache
            $path = IMG_CACH_DIR;
            $this->load->helper("file");
            delete_files($path);
            //Done
            //End Here

            $where = array(
                $auto_field => $v
            );
            $this->utils_model->safe_delete($table, $where, TRUE);
            $this->session->set_userdata(array(
                'msg_type' => 'success'
            ));
            $this->session->set_flashdata('success', lang('deleted'));
          }
        }
      }
      if ($action == 'Mark as Verified') { //Enquiry
        $data = array(
            'is_verified' => '1'
        );
        $where = "$auto_field IN ($str_ids)";
        $this->utils_model->safe_update($table, $data, $where, FALSE);

        // Send Email to Base Vendor
        foreach ($arr_ids as $k => $v) {
          $productID = get_db_field_value($table, 'products_id', "WHERE id = '" . $v . "'");
          // Insert Into enquiry Table
          $custIDList = get_db_field_value($table, 'customers_id', "WHERE id = '" . $v . "'");
          $custIDArr = explode(',', $custIDList);
          $custID = $custIDArr[0];
          $this->db->query("INSERT INTO wps_vendor_enquiry SET id = '" . $v . "', customers_id = '" . $custID . "'");
          // End here

          $product = $this->db->query("SELECT u.user_email FROM wps_customers as u LEFT JOIN wps_products as p ON u.customers_id = p.customers_id WHERE p.products_id = '" . $productID . "'")->row_array();
          $details = array();
          $dets = get_db_single_row($table, '*', "id = '" . $v . "'");

          $details['emailAddress'] = $dets['email'];
          $details['fullName'] = $dets['first_name'];
          $details['mobileNumber'] = $dets['mobile_number'];
          $details['enquiryMessage'] = $dets['message'];
          $details['productQuantity'] = $dets['quantity'];
          $details['post_url'] = $dets['post_url'];
          $details['productID'] = $dets['products_id'];

          sendAdminEnquiryEmail('New Enquiry Received from Natural Therapy India', $emailIds = array(
              "0" => $product['user_email']
                  ), $details);
        }

        $this->session->set_userdata(array(
            'msg_type' => 'success'
        ));
        $this->session->set_flashdata('success', 'Enquiry have been set as Verified!');
      }

      if ($action == 'Mark as Un-Verified') { //Enquiry
        $data = array(
            'is_verified' => '0'
        );
        $where = "$auto_field IN ($str_ids)";
        $this->utils_model->safe_update($table, $data, $where, FALSE);
        $this->session->set_userdata(array(
            'msg_type' => 'error'
        ));
        $this->session->set_flashdata('error', 'Enquiry have been set as Un-Verified!');
      }

      if ($action == 'Verified Manufaturer') {
        $data = array(
            'is_manufacturer' => '1'
        );
        foreach ($arr_ids as $k => $v) {

          //create Template URLs
          $compName = get_db_field_value('wps_customers', 'company_name', "WHERE customers_id = '" . $v . "'");
          $pageUrl = seo_url_title($compName);
          $countCompUrl = count_record("wps_meta_tags", "entity_id = '" . $v . "' AND is_fixed = 'C' AND entity_type = 'wpstemplate'");
          if ($countCompUrl == 0) {
            //Update url in main table
            $this->db->query("UPDATE wps_customers SET website_url = '" . $pageUrl . "', website_activation = '1' WHERE customers_id = '" . $v . "'");
            //insert in url table
            $this->db->query("INSERT INTO wps_company_website_urls SET website_url = '" . $pageUrl . "', customers_id = '" . $v . "'");
          }
          //for new and old user
          createTemplateUrls($v);
          //End here
          //get member details
          $memberDets = get_db_single_row($table, 'first_name, last_name, user_email, is_manufacturer', "customers_id = '" . $v . "'");

          $where = "$auto_field = $v";
          $this->utils_model->safe_update($table, $data, $where, FALSE);

          //send verification email
          // mail to user for uploading new product.

          $toEmail = $memberDets['user_email'];
          if ($toEmail && $memberDets['is_manufacturer'] != '1') {
            $content = file_get_contents(site_url() . 'mailer/member-activate.html');
            $subject = 'Congrats! Account Activated @ Natural Therapy India';
            $body = $content;
            $name = $memberDets['first_name'] . ' ' . $memberDets['last_name'];
            $body = str_replace('{mem_name}', $name, $body);
            $body = str_replace('{admin_email}', $this->admin_info->admin_email, $body);
            $body = str_replace('{site_name}', $this->config->item('site_name'), $body);

            $mail_conf = array(
                'subject' => $subject,
                'to_email' => $toEmail,
                'from_email' => $this->admin_info->admin_email,
                'from_name' => $this->config->item('site_name'),
                'body_part' => $body
            );
            // trace($mail_conf);
            // exit;
            //$this->dmailer->mail_notify($mail_conf);
            // mail end here
          }
        }
        $this->session->set_userdata(array(
            'msg_type' => 'success'
        ));
        $this->session->set_flashdata('error', 'Select Members have been Marked as Verified Manufacturer.');
      }
      if ($action == 'Not Verified Manufaturer') {
        $data = array(
            'is_manufacturer' => '2'
        );
        //trace($data); die;
        $where = "$auto_field IN ($str_ids)";
        //trace($where); die;
        $this->utils_model->safe_update($table, $data, $where, FALSE);
        //echo_sql(); die;
        $this->session->set_userdata(array(
            'msg_type' => 'error'
        ));
        $this->session->set_flashdata('error', 'Select Members have been Marked as Not Verified Manufacturer.');
      }

      if ($action == 'Block') {
        $data = array(
            'is_blocked' => '1'
        );
        $where = "$auto_field IN ($str_ids)";
        $this->utils_model->safe_update($table, $data, $where, FALSE);
        $this->session->set_userdata(array(
            'msg_type' => 'success'
        ));
        $this->session->set_flashdata('success', 'Members have been set as blocked!');
      }
      if ($action == 'Unblock') {
        $data = array(
            'is_blocked' => '0'
        );
        $where = "$auto_field IN ($str_ids)";
        $this->utils_model->safe_update($table, $data, $where, FALSE);
        $this->session->set_userdata(array(
            'msg_type' => 'success'
        ));
        $this->session->set_flashdata('success', 'Members have been set as unblocked!');
      }

      if ($action == 'Tempdelete') {
        $data = array(
            'status' => '2'
        );
        $where = "$auto_field IN ($str_ids)";
        $this->utils_model->safe_update($table, $data, $where, FALSE);
        $this->session->set_userdata(array(
            'msg_type' => 'success'
        ));
        $this->session->set_flashdata('success', lang('deleted'));
      }
    }
    redirect($_SERVER['HTTP_REFERER'], '');
  }

  public function set_as($table, $auto_field = 'id', $data = array()) {
    $arr_ids = $this->input->post('arr_ids', TRUE);
    if (is_array($arr_ids)) {
      $str_ids = implode(',', $arr_ids);
      if (is_array($data) && !empty($data)) {
        $data = $data;
        $where = "$auto_field IN ($str_ids)";
        $this->utils_model->safe_update($table, $data, $where, FALSE);

        $current_controller = $this->router->fetch_class();
        if ($current_controller == "orders" && $this->input->post("ord_status") != "" && ($this->input->post("ord_status") != "Pending" && $this->input->post("ord_status") != "Closed")) {

          $this->load->library("dmailer");
          $mail_subject = $this->config->item('site_name') . " Order overview";
          $from_email = $this->admin_info->admin_email;
          $from_name = $this->config->item('site_name');
          foreach ($arr_ids as $key => $val) {
            $order = get_db_single_row("wps_order", '*', " order_id = " . $val);
            $courier_details = "";

            if ($this->input->post("ord_status") == 'Delivered') {
              $data = array(
                  'payment_status' => 'Paid',
                  'order_delivery_date' => $this->config->item('config.date.time')
              );
              $where = "order_id = '" . $val . "'";
              $this->utils_model->safe_update('wps_order', $data, $where, FALSE);

              $mail_to = $order["email"];
              $from_email = $this->admin_info->admin_email;
              $content = '<table width="1024" border="0" cellpadding="0" cellspacing="0" style="padding:10px;">
                <tr>
                <td style="">
                Dear ' . $order['first_name'] . ',<br /><br />
                  Your order no ' . $order['invoice_number'] . ', is delivered at your address,. Thank you for using Mercadomoz.com. We are waiting for your next order. Give us chance to serve you.
                  <br /><br />
                  Keep using www.mercadomoz.com.<br />
                  Thank you for trust.<br />
                  Helpline: Mcel 833055555, Voda 853055555, Movitel 873055555<br /><br />
                  Best Regards<br />
                  Team - Mercadomoz
                  </td>
                  </tr>
                  <tr><td style="">&nbsp;</td></tr>
                  <tr>
                  <td colspan="2" style="">
                  Caro ' . $order['first_name'] . ',<br /><br />
                    O seu pedido não ' . $order['invoice_number'] . ', é entregue no seu endereço. Obrigado por usar Mercadomoz.com. Estamos à espera do seu próximo pedido. Dê-nos a oportunidade de atendê-lo.
                    <br /><br />
                    continue usando www.mercadomoz.com.<br />
                    Obrigado pela preferência.<br />
                    Linha de ajuda: Mcel 833055555, Voda 853055555, Movitel 873055555<br /><br />
                    Cumprimentos<br />
                  </td>
                </tr>
              </table>';

              $mail_conf = array(
                  'subject' => $this->config->item('site_name') . " Order " . $this->input->post("ord_status"),
                  'to_email' => $mail_to,
                  'from_email' => $from_email,
                  'from_name' => $this->config->item('site_name'),
                  'body_part' => $content
              );
              // trace($mail_conf);
              // exit;
              $this->dmailer->mail_notify($mail_conf);
            }

            if ($this->input->post("ord_status") == 'Canceled') {
              // update stock
              $orders = $this->db->query("SELECT store, products_id, quantity FROM wps_orders_products WHERE " . $where)->result_array();
              foreach ($orders as $ord) {
                $qty = $ord['quantity'];
                $this->db->query("UPDATE wps_product_attributes SET quantity=quantity+$qty WHERE store_id = '" . $ord['store'] . "' AND product_id = '" . $ord['products_id'] . "'");
              }
              // End here
            }

            if ($this->input->post("ord_status") == 'Dispatched') {
              $new_time = date("Y-m-d H:i:s", strtotime('+24 hours'));
              $dt = explode(' ', $new_time);
              $mail_to = $order["email"];
              $from_email = $this->admin_info->admin_email;
              $content = '<table width="1024" border="0" cellpadding="0" cellspacing="0" style="padding:10px;">
                <tr>
                <td style="">
                Dear ' . $order['first_name'] . ',<br /><br />
                  Your order no ' . $order['invoice_number'] . ', is dispatched for delivery, your billed amount is ' . display_price($order['total_amount']) . '. You can pay by cash OR by Debit/Credit Card. Estimated delivery time is ' . getDateFormat($dt[0], 3) . ', by ' . $dt[1] . '.
                  <br /><br />
                  Keep using www.mercadomoz.com.<br />
                  Thank you for trust.<br />
                  Helpline: Mcel 833055555, Voda 853055555, Movitel 873055555<br /><br />
                  Best Regards<br />
                  Team - Mercadomoz
                  </td>
                  </tr>
                  <tr><td style="">&nbsp;</td></tr>
                  <tr>
                  <td colspan="2" style="">
                  Prezado ' . $order['first_name'] . ',<br /><br />
                    o seu pedido nr ' . $order['invoice_number'] . ', foi despachado para entrega, seu valor faturado é ' . display_price($order['total_amount']) . '. Você pode pagar em dinheiro OU por cartão de débito/crédito. O tempo estimado de entrega é ' . getDateFormat($dt[0], 3) . ', até ' . $dt[1] . '.
                    <br /><br />
                    continue usando www.mercadomoz.com.<br />
                    Obrigado pela preferência.<br />
                    Linha de ajuda: Mcel 833055555, Voda 853055555, Movitel 873055555<br /><br />
                    Cumprimentos<br />
                  </td>
                </tr>
              </table>';

              $mail_conf = array(
                  'subject' => $this->config->item('site_name') . " Order " . $this->input->post("ord_status"),
                  'to_email' => $mail_to,
                  'from_email' => $from_email,
                  'from_name' => $this->config->item('site_name'),
                  'body_part' => $content
              );
              // trace($mail_conf);
              // exit;
              $this->dmailer->mail_notify($mail_conf);
            }
          }
        }
        $this->session->set_userdata(array(
            'msg_type' => 'success'
        ));
        $this->session->set_flashdata('success', "Record has been updated/deleted successfully.");
      }
      redirect($_SERVER['HTTP_REFERER'], '');
    }
  }

  public function update_displayOrder($tblname, $fldname, $fld_id) {
    $posted_order_data = $this->input->post('ord');
    while (list ($key, $val) = each($posted_order_data)) {
      if ($val != '') {
        $val = (int) $val;
        $data = array(
            $fldname => $val
        );
        $where = "$fld_id=$key";
        $this->utils_model->safe_update($tblname, $data, $where, TRUE);
      }
    }
    $this->session->set_userdata(array(
        'msg_type' => 'success'
    ));
    $this->session->set_flashdata('success', lang('order_updated'));
    redirect($_SERVER['HTTP_REFERER'], '');
  }

}
