<?php

class ControllerSaleCustomerImport extends Controller {

    private $error = array();

    public function index() {
        ini_set('display_errors', 1);
        ini_set('log_errors', 1);
        ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
        error_reporting(E_ALL);
        if (!isset($this->session->data['user_token'])) {
            $this->session->data['user_token'] = 0;
        }
        $data['user_token'] = $this->session->data['user_token'];

        $this->load->language('sale/customer_import');

        //$this->document->title = $this->language->get('heading_title');

        $this->load->model('sale/customer_import');

        if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) {
            if (is_uploaded_file($this->request->files['csv_import']['tmp_name'])) {
                $content = file_get_contents($this->request->files['csv_import']['tmp_name']);
                $filename = $this->request->files['csv_import']['tmp_name'];
            } else {
                $content = false;
            }

            if ($content) {
                $this->model_sale_customer_import->csvImport($filename);
                $this->session->data['success'] = $this->language->get('text_success');
                //die(0);
                $this->response->redirect(HTTPS_SERVER . 'index.php?route=sale/customer_import&user_token=' . $this->session->data['user_token']);
            } else {
                $this->error['warning'] = $this->language->get('error_empty');
            }
        }

        $data['heading_title'] = "Customer Import";

        $data['text_select_all'] = $this->language->get('text_select_all');
        $data['text_unselect_all'] = $this->language->get('text_unselect_all');

        $data['entry_export'] = $this->language->get('entry_export');
        $data['entry_import'] = $this->language->get('entry_import');

        $data['button_backup'] = $this->language->get('button_backup');
        $data['button_restore'] = $this->language->get('button_restore');

        $data['tab_general'] = $this->language->get('tab_general');

        if (isset($this->error['warning'])) {
            $data['error_warning'] = $this->error['warning'];
        } else {
            $data['error_warning'] = '';
        }

        if (isset($this->session->data['success'])) {
            $data['success'] = $this->session->data['success'];

            unset($this->session->data['success']);
        } else {
            $data['success'] = '';
        }

        $this->document->breadcrumbs = array();

        $this->document->breadcrumbs[] = array(
            'href' => HTTPS_SERVER . 'index.php?route=common/home&user_token=' . $this->session->data['user_token'],
            'text' => $this->language->get('text_home'),
            'separator' => FALSE
        );

        $this->document->breadcrumbs[] = array(
            'href' => HTTPS_SERVER . 'index.php?route=sale/customer_import&user_token=' . $this->session->data['user_token'],
            'text' => $this->language->get('heading_title'),
            'separator' => ' :: '
        );

        $data['restore'] = HTTPS_SERVER . 'index.php?route=sale/customer_import&user_token=' . $this->session->data['user_token'];

        $data['customer_import'] = HTTPS_SERVER . 'index.php?route=sale/customer_import&user_token=' . $this->session->data['user_token'];
        $data['customer_import_ch'] = $this->session->data['user_token'];

        $this->template = 'sale/customer_import.twig';
        $this->children = array(
            'common/header',
            'common/footer'
        );

        $data['header'] = $this->load->controller('common/header');
    		$data['column_left'] = $this->load->controller('common/column_left');
    		$data['footer'] = $this->load->controller('common/footer');

        $data['breadcrumbs'] = array();

    		$data['breadcrumbs'][] = array(
    			'text' => $this->language->get('text_home'),
    			'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true)
    		);

    		$data['breadcrumbs'][] = array(
    			'text' => $this->language->get('heading_title'),
    			'href' => $this->url->link('sale/order', 'user_token=' . $this->session->data['user_token'] . $url, true)
    		);

        // $this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
        $this->response->setOutput($this->load->view('sale/customer_import', $data));
    }

    public function csvExport() {
        if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate() && isset($this->request->post['csv_export'])) {

            $ReflectionResponse = new ReflectionClass($this->response);
            if ($ReflectionResponse->getMethod('addheader')->getNumberOfParameters() == 2) {
                $this->response->addheader('Pragma', 'public');
                $this->response->addheader('Expires', '0');
                $this->response->addheader('Content-Description', 'File Transfer');
                $this->response->addheader("Content-type', 'text/octect-stream");
                $this->response->addheader("Content-Disposition', 'attachment;filename=" . $this->request->post['csv_export'] . ".csv");
                $this->response->addheader('Content-Transfer-Encoding', 'binary');
                $this->response->addheader('Cache-Control', 'must-revalidate, post-check=0,pre-check=0');
            } else {
                $this->response->addheader('Pragma: public');
                $this->response->addheader('Expires: 0');
                $this->response->addheader('Content-Description: File Transfer');
                $this->response->addheader("Content-type:text/octect-stream");
                $this->response->addheader("Content-Disposition:attachment;filename=DMPG_Product_list.csv");
                $this->response->addheader('Content-Transfer-Encoding: binary');
                $this->response->addheader('Cache-Control: must-revalidate, post-check=0,pre-check=0');
            }

            $this->load->model('sale/csv');
            if ($_POST['export-type'] == 'price') {
                $this->response->setOutput($this->model_sale_customer_import->csvExport($this->request->post['csv_export']));
            } else if ($_POST['export-type'] == 'french') {
                $this->response->setOutput($this->model_sale_customer_import->csvFrenchExport($this->request->post['csv_export']));
            } else if ($_POST['export-type'] == 'french-category') {
                $this->response->setOutput($this->model_sale_customer_import->csvCategoryFrenchExport($this->request->post['csv_export']));
            }
        } else {
            return $this->forward('error/permission');
        }
    }

    private function validate() {
        if (!$this->user->hasPermission('modify', 'sale/customer_import')) {
            $this->error['warning'] = $this->language->get('error_permission');
        }

        if (!$this->error) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    public function urlalias() {
        $product_query = "Select p.product_id ProductID,name Name, price Price, length Length,width Width,height Height,weight Weight, minimum MOQ from op_product p, op_product_description d where p.product_id = d.product_id order by p.product_id";
        $result = $this->db->query($product_query);
        foreach ($result->rows as $row) {
            $product_id = $row['ProductID'];
            $product_name = $row['Name'];
            $product_name = trim($product_name);
            $product_name = str_replace(" ", "-", $product_name);
            $product_name = str_replace("/", "-", $product_name);
            $product_name = str_replace("\'", "", $product_name);
            $product_name = str_replace("\"", "", $product_name);
            $url_alias_query = "select * from op_url_alias where query='product_id=" . $product_id . "'";
            $results = $this->db->query($url_alias_query);
            if (count($results->rows) > 0) {
                $r = $results->rows[0];
                $url_alias = "update op_url_alias set keyword='" . $product_name . "' where url_alias_id=" . $r['url_alias_id'];
            } else {
                $query = "product_id=" . $product_id;
                $url_alias = "insert into op_url_alias (query,keyword) values ('$query','$product_name')";
            }
            $this->db->query($url_alias);
        }

        $product_query = "Select c.category_id category_id, cd.name name from op_category c, op_category_description cd where c.category_id = cd.category_id order by c.category_id";
        $result = $this->db->query($product_query);
        //print_r($result);
        foreach ($result->rows as $row) {
            $product_id = $row['category_id'];
            $product_name = $row['name'];
            $product_name = trim($product_name);
            $product_name = str_replace(" ", "-", $product_name);
            $product_name = str_replace("quot;", "", $product_name);
            $product_name = str_replace("amp;", "", $product_name);
            $product_name = str_replace("/", "-", $product_name);
            $product_name = str_replace("+", "-", $product_name);
            $product_name = str_replace("&", "and", $product_name);
            $product_name = str_replace("'", "", $product_name);
            $product_name = str_replace('"', "", $product_name);
            $url_alias_query = "select * from op_url_alias where query='category_id=" . $product_id . "'";
            $results = $this->db->query($url_alias_query);
            if (count($results->rows) > 0) {
                $r = $results->rows[0];
                $url_alias = "update op_url_alias set keyword='" . $product_name . "' where url_alias_id=" . $r['url_alias_id'];
            } else {
                $query = "category_id=" . $product_id;
                $url_alias = "insert into op_url_alias (query,keyword) values ('$query','$product_name')";
            }
            $this->db->query($url_alias);
        }

        echo 'CEO keywords updated';
    }

}

?>
