<?php


require_once DIR_SYSTEM . "picqer" . DIRECTORY_SEPARATOR . "php-barcode-generator" . DIRECTORY_SEPARATOR . "generate-verified-files.php";

require_once DIR_SYSTEM . 'dompdf/autoload.inc.php';


class ControllerSalePreparedOrders extends Controller
{


    private $error = array();


    public function index()
    {


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


        $this->document->setTitle($this->language->get('heading_title'));


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


        $this->getList();

    }


    public function getList()
    {


        if (isset($this->request->get['filter_order_id'])) {
            $filter_order_id = $this->request->get['filter_order_id'];
        } else {
            $filter_order_id = null;
        }


        if (isset($this->request->get['filter_customer'])) {
            $filter_customer = $this->request->get['filter_customer'];
        } else {
            $filter_customer = null;
        }


        if (isset($this->request->get['filter_order_status'])) {
            $filter_order_status = $this->request->get['filter_order_status'];
        } else {
            $filter_order_status = null;
        }


        if (isset($this->request->get['filter_date_added'])) {
            $filter_date_added = $this->request->get['filter_date_added'];
        } else {
            $filter_date_added = null;
        }


        if (isset($this->request->get['filter_date_modified'])) {
            $filter_date_modified = $this->request->get['filter_date_modified'];
        } else {
            $filter_date_modified = null;
        }


        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        } else {
            $sort = 'o.order_id';
        }


        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
        } else {
            $order = 'ASC';
        }


        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }
$data['pageno'] = $page;

        $url = '';

        if (isset($this->request->get['filter_order_id'])) {
            $url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
        }


        if (isset($this->request->get['filter_customer'])) {
            $url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
        }


        if (isset($this->request->get['filter_order_status'])) {
            $url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
        }


        if (isset($this->request->get['filter_date_added'])) {
            $url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
        }


        if (isset($this->request->get['filter_date_modified'])) {
            $url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
        }


        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }


        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }


        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }


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

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


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


        ///Buraya islemlerin linki gelcek


        $data['kargo_firma'] = 'YURTICI';

        if ($this->config->get('yurticikargo_status')) {
            $data['yurticikargo_status'] = $this->config->get('yurticikargo_status');
        } else {
            $data['yurticikargo_status'] = false;
        }


        $filter_by = '';
        if (isset($this->request->get['filter_by'])) {
            $filter_by = $this->request->get['filter_by'];
        }
        $data['filter_by_personalized'] = $this->url->link('sale/prepared_orders', 'token=' . $this->session->data['token'] . '&filter_by=personalized', true);
        $data['filter_by_reprinted'] = $this->url->link('sale/prepared_orders', 'token=' . $this->session->data['token'] . '&filter_by=reprinted', true);
        $data['all_products'] = $this->url->link('sale/prepared_orders', 'token=' . $this->session->data['token'], true);
        $data['bulkdownload'] = $this->url->link('sale/prepared_orders/bulkDownload', 'token=' . $this->session->data['token'], true);

        $data['orders'] = array();
$config_limit_admin = 1750;

        


        /*$sql = "SELECT o.order_id, CONCAT(o.firstname, ' ', o.lastname) AS customer, o.row_color_code,
        (SELECT os.name FROM ps_order_status os WHERE os.order_status_id = o.order_status_id AND os.language_id = '" . (int)$this->config->get('config_language_id') . "') AS order_status,
		o.shipping_code, o.total, o.currency_code, o.currency_value, o.date_added, o.date_modified, o.status FROM ps_order o WHERE o.status = 0 AND o.row_color_code = '#ABFF72' ORDER BY o.date_added ASC ";


        $total_orders = $this->db->query($sql)->rows; */


        $start = ($page - 1) * $config_limit_admin;



        $sql = "SELECT o.order_id, CONCAT(o.firstname, ' ', o.lastname) AS customer, o.row_color_code,
        (SELECT os.name FROM ps_order_status os WHERE os.order_status_id = o.order_status_id AND os.language_id = '" . (int)$this->config->get('config_language_id') . "') AS order_status,
		o.shipping_code, o.total, o.currency_code, o.currency_value, o.date_added, o.date_modified, o.status, o.comment FROM ps_order o WHERE o.status = 0 AND o.row_color_code = '#ABFF72' ORDER BY o.date_added ASC  LIMIT " . (int)$start . "," . (int)$config_limit_admin;


        $results = $this->db->query($sql)->rows;


        $order_total = 0;


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

        $this->load->model('extension/module/yurticikargo');

        foreach ($results as $result) {

            $order_customer_id = 0;
            $order_customer_id = $this->model_sale_order->getOrderCustomerId($result['order_id']);
            $order_products = $this->model_sale_order->getOrderProducts($result['order_id']);

            if ($order_products) {

                /* Mükerrer Hesaplama - @toturkmen - Başlangıç */

                $OrderIDs = array();

                foreach ($order_products as $Result)

                    $OrderIDs [] = $Result ['order_id'];

                $Mukerrer = array_count_values($OrderIDs);

                /* Mükerrer Hesaplama - @toturkmen - Bitiş */

                $this->load->model('tool/image');

                foreach ($order_products as $order_product) {

                    $image = $this->db->query("SELECT image FROM ps_product WHERE product_id='" . $order_product['product_id'] . "' ")->row;
                    $case_image=$image['image'];
                    $image = isset($image['image']) ? $this->model_tool_image->resize($image['image'], 100, 100) : '';
                    // Order Options
                    $option_data = array();
                    $options = $this->model_sale_order->getOrderOptions($order_product['order_id'], $order_product['order_product_id']);
                    foreach ($options as $option) {
                        $option_data[] = array(
                            'name' => $option['name'],
                            'value' => $option['value'],
                            'type' => $option['type']
                        );
                    }

                    // Order Options
                    $case_pattern_image = $this->model_tool_image->resize($order_product['case_order_image'], 100, 100);

                     $customcase_image =  '';

                if ($order_product['customcase_image'] != '') {

                    $str = explode('***', $order_product['customcase_image']);

                    $customcase_image = ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $str[1];

                    if($case_image!='' &&  file_exists(DIR_IMAGE.$case_image))
                    $case_image = ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/'.$case_image;
                  
                    else
                     $case_image = ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/personal/' . $str[0] . '.png';
                }

                    $total_customer_orders = 0;
                    if ($order_customer_id > 0) {
                        $total_customer_orders = $this->model_sale_order->getTotalOrdersByCustomer($order_customer_id);
                    }


                    $customer_pattern_data = json_decode($order_product['customer_pattern_data'], true);
                    if (isset($customer_pattern_data['pattern_text'])) {
                        $case_text = $customer_pattern_data['pattern_text'];
                    } else {
                        $case_text = '';
                    }


                    $order_comment = $result['comment'];


                    if ($result ['status'] != 1 AND !$order_product['return_status']) {

                        if ($filter_by == 'personalized' && $case_text != '') {
                            $order_total++;
                            $data['products'][] = array(
                                'order_product_id' => $order_product['order_product_id'],
                                'product_id' => $order_product['product_id'],
                                'order_id' => $result['order_id'],
                                'model' => $order_product['model'],
                                'product_type' => $customer_pattern_data['product_type'],
                                'name' => $order_product['name'],
                                'image' => $image,
                                'case_order_image' => ($order_product['case_order_image'] != '' ? ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $order_product['case_order_image'] : ''),
                                'customer_pattern_data' => $order_product['customer_pattern_data'],
                                'case_text' => $case_text,
                                'admin_pattern_image' => ($order_product['admin_pattern_image'] != '' ? ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $order_product['admin_pattern_image'] : ''),
                                'admin_gradient_pattern_image' => ($order_product['admin_gradient_pattern_image'] != '' ? ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $order_product['admin_gradient_pattern_image'] : ''),
                                'customcase_image' => $customcase_image,
                                'case_image' => $case_image,
                                'customer' => $result['customer'],
                                'product_model' => $order_product['model'],
                                'comment' => $order_comment,
                                'option' => array(),
                                'quantity' => $order_product['quantity'],
                                'total_customer_orders' => $total_customer_orders,
                                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                                'date_modified' => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
                                'order_status' => $result['order_status'] ? $result['order_status'] : $this->language->get('text_missing'),
                                'status' => $order_product['status'],
                                'reprint' => $order_product['reprint'],
                                'kargo_talepno' => $this->model_extension_module_yurticikargo->getShippingData($result['order_id']),
                                'kargo_barcode' => $this->url->link('sale/prepared_orders/invoice', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$result['order_id'], true),
                                'order_href' => $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$result['order_id'], true),
                                'mukerrer' => $Mukerrer [$result ['order_id']] != 1,
                                'options' => $options,
                                'shipping_code' => $result['shipping_code'],
                                'return_status' => $order_product['return_status'],
                            );
                        } elseif ($filter_by == 'reprinted' && $order_product['reprint']) {
                            $order_total++;
                            $data['products'][] = array(
                                'order_product_id' => $order_product['order_product_id'],
                                'product_id' => $order_product['product_id'],
                                'order_id' => $result['order_id'],
                                'model' => $order_product['model'],
                                'product_type' => $customer_pattern_data['product_type'],
                                'name' => $order_product['name'],
                                'image' => $image,
                                'case_order_image' => ($order_product['case_order_image'] != '' ? ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $order_product['case_order_image'] : ''),
                                'customer_pattern_data' => $order_product['customer_pattern_data'],
                                'case_text' => $case_text,
                                'admin_pattern_image' => ($order_product['admin_pattern_image'] != '' ? ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $order_product['admin_pattern_image'] : ''),
                                'admin_gradient_pattern_image' => ($order_product['admin_gradient_pattern_image'] != '' ? ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $order_product['admin_gradient_pattern_image'] : ''),
                                'customcase_image' => $customcase_image,
                                'case_image' => $case_image,
                                'customer' => $result['customer'],
                                'product_model' => $order_product['model'],
                                'comment' => $order_comment,
                                'option' => array(),
                                'quantity' => $order_product['quantity'],
                                'total_customer_orders' => $total_customer_orders,
                                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                                'date_modified' => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
                                'order_status' => $result['order_status'] ? $result['order_status'] : $this->language->get('text_missing'),
                                'status' => $order_product['status'],
                                'reprint' => $order_product['reprint'],
                                'kargo_talepno' => $this->model_extension_module_yurticikargo->getShippingData($result['order_id']),
                                'kargo_barcode' => $this->url->link('sale/prepared_orders/invoice', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$result['order_id'], true),
                                'order_href' => $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$result['order_id'], true),
                                'mukerrer' => $Mukerrer [$result ['order_id']] != 1,
                                'options' => $options,
                                'shipping_code' => $result['shipping_code'],
                                'return_status' => $order_product['return_status'],
                            );
                        } elseif ($filter_by == '') {
                            $order_total++;
                            $data['products'][] = array(
                                'order_product_id' => $order_product['order_product_id'],
                                'product_id' => $order_product['product_id'],
                                'order_id' => $result['order_id'],
                                'model' => $order_product['model'],
                                'product_type' => $customer_pattern_data['product_type'],
                                'name' => $order_product['name'],
                                'image' => $image,
                                'case_order_image' => ($order_product['case_order_image'] != '' ? ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $order_product['case_order_image'] : ''),
                                'customer_pattern_data' => $order_product['customer_pattern_data'],
                                'case_text' => $case_text,
                                'admin_pattern_image' => ($order_product['admin_pattern_image'] != '' ? ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $order_product['admin_pattern_image'] : ''),
                                'admin_gradient_pattern_image' => ($order_product['admin_gradient_pattern_image'] != '' ? ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $order_product['admin_gradient_pattern_image'] : ''),
                                'customcase_image' => $customcase_image,
                                'case_image' => $case_image,
                                'customer' => $result['customer'],
                                'product_model' => $order_product['model'],
                                'comment' => $order_comment,
                                'option' => array(),
                                'quantity' => $order_product['quantity'],
                                'total_customer_orders' => $total_customer_orders,
                                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                                'date_modified' => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
                                'order_status' => $result['order_status'] ? $result['order_status'] : $this->language->get('text_missing'),
                                'status' => $order_product['status'],
                                'reprint' => $order_product['reprint'],
                                'kargo_talepno' => $this->model_extension_module_yurticikargo->getShippingData($result['order_id']),
                                'kargo_barcode' => $this->url->link('sale/prepared_orders/invoice', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$result['order_id'], true),
                                'order_href' => $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$result['order_id'], true),
                                'mukerrer' => $Mukerrer [$result ['order_id']] != 1,
                                'options' => $options,
                                'shipping_code' => $result['shipping_code'],
                                'return_status' => $order_product['return_status'],
                            );
                        }

                    }

                }


            }
            if (1 == 2) { // temporary blocked

                $total_customer_orders = 0;

                if ($order_customer_id > 0) {

                    $total_customer_orders = $this->model_sale_order->getTotalOrdersByCustomer($order_customer_id);

                }


                $data['orders'][] = array(
                    'order_id' => $result['order_id'],
                    'image' => $image,
                    'customer' => $result['customer'],
                    'customer_id' => $order_customer_id,
                    'total_customer_orders' => $total_customer_orders,
                    'order_status' => $result['order_status'] ? $result['order_status'] : $this->language->get('text_missing'),
                    'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                    'date_modified' => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
                    'status' => $result['status'],

                );

            }

        }

        


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


        $data['text_list'] = $this->language->get('text_list');
        $data['text_no_results'] = $this->language->get('text_no_results');
        $data['text_confirm'] = $this->language->get('text_confirm');
        $data['text_missing'] = $this->language->get('text_missing');
        $data['text_loading'] = $this->language->get('text_loading');


        $data['column_order_id'] = $this->language->get('column_order_id');
        $data['column_customer'] = $this->language->get('column_customer');
        $data['column_status'] = $this->language->get('column_status');
        $data['column_product_name'] = $this->language->get('column_product_name');
        $data['column_product_model'] = $this->language->get('column_product_model');
        $data['column_quantity'] = $this->language->get('column_quantity');

        $data['column_comment'] = $this->language->get('column_comment');
        $data['column_date_added'] = $this->language->get('column_date_added');
        $data['column_date_modified'] = $this->language->get('column_date_modified');
        $data['column_action'] = $this->language->get('column_action');
        $data['column_image'] = $this->language->get('column_image');


        $data['entry_order_id'] = $this->language->get('entry_order_id');
        $data['entry_customer'] = $this->language->get('entry_customer');
        $data['entry_order_status'] = $this->language->get('entry_order_status');
        $data['entry_date_added'] = $this->language->get('entry_date_added');
        $data['entry_date_modified'] = $this->language->get('entry_date_modified');


        $data['button_invoice_print'] = $this->language->get('button_invoice_print');
        $data['button_shipping_print'] = $this->language->get('button_shipping_print');
        $data['button_filter'] = $this->language->get('button_filter');
        $data['button_view'] = $this->language->get('button_view');
        $data['button_ip_add'] = $this->language->get('button_ip_add');
        $data['button_delete'] = $this->language->get('button_delete');
        $data['delete'] = $this->url->link('sale/prepared_orders/delete', 'token=' . $this->session->data['token'], true);


        $data['token'] = $this->session->data['token'];


        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'] = '';
        }


        if (isset($this->request->post['selected'])) {
            $data['selected'] = (array)$this->request->post['selected'];
        } else {
            $data['selected'] = array();
        }


        $url = '';


        if (isset($this->request->get['filter_order_id'])) {

            $url .= '&filter_order_id=' . $this->request->get['filter_order_id'];

        }


        if (isset($this->request->get['filter_customer'])) {

            $url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));

        }


        if (isset($this->request->get['filter_order_status'])) {

            $url .= '&filter_order_status=' . $this->request->get['filter_order_status'];

        }


        if (isset($this->request->get['filter_date_added'])) {

            $url .= '&filter_date_added=' . $this->request->get['filter_date_added'];

        }


        if (isset($this->request->get['filter_date_modified'])) {

            $url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];

        }


        if ($order == 'ASC') {

            $url .= '&order=DESC';

        } else {

            $url .= '&order=ASC';

        }


        if (isset($this->request->get['page'])) {

            $url .= '&page=' . $this->request->get['page'];

        }


        $data['sort_order'] = $this->url->link('sale/prepared_orders', 'token=' . $this->session->data['token'] . '&sort=o.order_id' . $url, true);
        $data['sort_customer'] = $this->url->link('sale/prepared_orders', 'token=' . $this->session->data['token'] . '&sort=customer' . $url, true);
        $data['sort_status'] = $this->url->link('sale/prepared_orders', 'token=' . $this->session->data['token'] . '&sort=order_status' . $url, true);
        $data['sort_p_model'] = $this->url->link('sale/prepared_orders', 'token=' . $this->session->data['token'] . '&sort=o.p_model' . $url, true);
        $data['sort_date_added'] = $this->url->link('sale/prepared_orders', 'token=' . $this->session->data['token'] . '&sort=o.date_added' . $url, true);
        $data['sort_date_modified'] = $this->url->link('sale/prepared_orders', 'token=' . $this->session->data['token'] . '&sort=o.date_modified' . $url, true);

        $url = '';


        if (isset($this->request->get['filter_order_id'])) {
            $url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
        }


        if (isset($this->request->get['filter_customer'])) {
            $url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
        }


        if (isset($this->request->get['filter_order_status'])) {
            $url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
        }


        if (isset($this->request->get['filter_date_added'])) {
            $url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
        }


        if (isset($this->request->get['filter_date_modified'])) {
            $url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
        }


        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }


        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }


        $pagination = new Pagination();
        $pagination->total = $order_total;
        $pagination->page = $page;
        $pagination->limit = $config_limit_admin;
        $pagination->url = $this->url->link('sale/prepared_orders', 'token=' . $this->session->data['token'] . $url . '&page={page}', true);


        $data['pagination'] = $pagination->render();


        $data['results'] = sprintf($this->language->get('text_pagination'), ($order_total) ? (($page - 1) * $config_limit_admin) + 1 : 0, ((($page - 1) * $config_limit_admin) > ($order_total - $config_limit_admin)) ? $order_total : ((($page - 1) * $config_limit_admin) + $config_limit_admin), $order_total, ceil($order_total / $config_limit_admin));


        $data['filter_order_id'] = $filter_order_id;

        $data['filter_customer'] = $filter_customer;

        $data['filter_order_status'] = $filter_order_status;

        $data['filter_date_added'] = $filter_date_added;

        $data['filter_date_modified'] = $filter_date_modified;


        $data['sort'] = $sort;

        $data['order'] = $order;


        $this->load->model('localisation/order_status');


        $data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();


        // The URL we send API requests to

        $data['catalog'] = $this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG;


        $data['order_status_id'] = $this->config->get('yurticikargo_order_status_id');


        // API login

        $this->load->model('user/api');


        $api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));


        if ($api_info) {

            $data['api_id'] = $api_info['api_id'];

            $data['api_key'] = $api_info['key'];

            $data['api_ip'] = $this->request->server['REMOTE_ADDR'];

        } else {

            $data['api_id'] = '';

            $data['api_key'] = '';

            $data['api_ip'] = '';

        }


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

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

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


        if (file_exists(DIR_LOCAL_TEMPLATE . 'sale/prepared_orders.tpl')) {

            $this->response->setOutput($this->load->view(DIR_LOCAL_TEMPLATE . 'sale/prepared_orders', $data));

        } else {

            $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'sale/prepared_orders', $data));

        }

    }



    public function delete()
    {

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


        $this->document->setTitle($this->language->get('heading_title'));


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


        if (isset($this->request->post['selected_order_ids']) && $this->validate()) {

            foreach ($this->request->post['selected_order_ids'] as $order_id) {

                $sql = 'SELECT order_status_id from ps_order where order_id=' . $order_id;

                $status = $this->db->query($sql)->row;

                if ($status['order_status_id'] == '7') {

                    $this->model_sale_order->deleteOrder($order_id);

                    $this->session->data['success'] = $this->language->get('text_success');

                }

            }


            $url = '';


            if (isset($this->request->get['filter_order_id'])) {

                $url .= '&filter_order_id=' . $this->request->get['filter_order_id'];

            }


            if (isset($this->request->get['filter_customer'])) {

                $url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));

            }


            if (isset($this->request->get['filter_order_status'])) {

                $url .= '&filter_order_status=' . $this->request->get['filter_order_status'];

            }


            if (isset($this->request->get['filter_total'])) {

                $url .= '&filter_total=' . $this->request->get['filter_total'];

            }


            if (isset($this->request->get['filter_date_added'])) {

                $url .= '&filter_date_added=' . $this->request->get['filter_date_added'];

            }


            if (isset($this->request->get['filter_date_modified'])) {

                $url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];

            }


            $this->response->redirect($this->url->link('sale/prepared_orders', 'token=' . $this->session->data['token'] . $url, true));

        }


        $this->getList();

    }

    protected function validate()
    {

        if (!$this->user->hasPermission('modify', 'sale/prepared_orders')) {

            $this->error['warning'] = $this->language->get('error_permission');

        }


        return !$this->error;

    }

    public function invoice()
    {


        $order_id = $this->request->get['order_id'];

        $this->db->query("UPDATE ps_order_yurticikargo SET barcode_print_count = barcode_print_count+1 WHERE order_id = '" . $order_id . "' ");


        $yurtici_kargo_info = array();

        if ($this->config->get('yurticikargo_status')) {

            $this->load->model('extension/module/yurticikargo');

            $yurtici_kargo_info = $this->model_extension_module_yurticikargo->getShippingData($order_id);

        }

        require_once(DIR_SYSTEM . 'picqer/php-barcode-generator/generate-verified-files.php');

        $generatorJPG = new Picqer\Barcode\BarcodeGeneratorJPG();
        $barkod_cargokey = $generatorJPG->getBarcode($yurtici_kargo_info['kargo_barcode'], $generatorJPG::TYPE_CODE_128_A);
        $barkod_cargokey = '<img src="data:image/jpeg;base64,' . base64_encode($barkod_cargokey) . '" style="transform: rotate(90deg); width: 200px; margin-right:70px; height: auto;">';
        $barkod_talepno = $generatorJPG->getBarcode($yurtici_kargo_info['kargo_talepno'], $generatorJPG::TYPE_CODE_128_A);
        $barkod_talepno = '<img src="data:image/jpeg;base64,' . base64_encode($barkod_talepno) . '" style="width: 200px;">';


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

        $order_info = $this->model_sale_order->getOrder($order_id);
        $total = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value']);

        $product_names = array();


        //Return Status -- veritabanındaki kayıt
        // 0 Geçerli sipariş
        // 1 İade
        // 2 İptal
        // 3 Değişim

        $products = $this->model_sale_order->getOrderProducts($order_id);


        $return_info = '';

        foreach ($products as $product) {

            $name = explode(' ', $product['name']);

            if($product['return_status'] == 1){
                $return_info .= $product['name'] . ' <b>İADE</b> <br>';
            }else if($product['return_status'] == 2){
                $return_info .= $product['name'] . ' <b>İPTAL</b> <br>';
            }else if($product['return_status'] == 3){
                $return_info .= $product['name'] . ' <b>DEĞİŞİM</b> <br>';
            }else{
                $product_names[] = $product['model'] . ' - ' . str_replace('Tutacaklı','<b style="color: red; font-size: 18px;">Tutacaklı</b>', $product['name']);
            }

        }


        $product_names = implode('<br>', $product_names);

        $shipping_title = '';

        if ($order_info['payment_code'] == 'cod') {
            $shipping_title = 'Kapıda Nakit Ödemeli Normal Gönderi';
        } else {
            $shipping_title = 'Gönderici Ödemeli Normal Gönderi';
        }


        $html = '<html>
        <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">

          <style>
            html { margin: 0; padding: 5px; }
            body { font-family: DejaVu Sans, sans-serif; margin: 0; padding: 5px;}

            .outer{
              width: 100%;
              padding: 0;
            }

            .title{
              width: 100%;
              font-size: 14px;
              border-bottom: 1px solid black;
              margin-bottom: 4px;
            }

            .inner{
              width: 80%;
              float: left;
            }

            .alt{
              width: 100%;
            }

            .altBilgi{
              width: 50%;
              float:left;
            }

            .altBarkod{
              width: 50%;
              float: right;
              padding-top: 10px;
            }

            .border-bottom{ border-bottom: 1px solid gray; }

            .barcode{
              position: absolute;
              right: 275px;
              top: 175px;
            }

            .alt-title{
              font-weight: bold;
              font-size: 11px;
            }

            .alt div{
              font-size: 10px;
            }

            .tarih{
              float: right;
              margin: 0;
              font-size: 8px;
              margin-top: 3px;
            }
          </style>

        </head>
        <body>

          <div class="outer">

            <div class="inner">
             ';

        if($return_info){

            $html .= '<div class="alt border-bottom" >
                <div class="alt-title">İptal/İade/Değişim Sipariş Notu  Sipariş No: '. $order_id .'</div>
                <div style="height: 80%">' . $return_info . '</div>
                    
              </div>';

        }

        if($order_info['comment']){

            $html .= '<div class="alt border-bottom" >
                <div class="alt-title">Sipariş Notu</div>
                <div style="height: 80%; font-size:20px;">' . $order_info['comment'] . '</div>
                    
              </div>';

        }

        if($product_names) {

            $html .= '
                <div class="title">
                <b>Deercase - Web Servis</b> <span class="tarih">' . @date('d:m:y h:i') . '</span> <br>
                <small>' . $shipping_title . '</small>
              </div>

            <div class="alt border-bottom">
                <div class="alt-title">Alıcı Bilgileri</div>
                <div><b>Sipariş No: ' . $order_info['order_id'] . '</b></div>
                <div>İsim Soyisim: ' . $order_info['shipping_firstname'] . ' ' . $order_info['shipping_lastname'] . '</div>
                <div>Adres: ' . $order_info['shipping_city'] . ' ' . $order_info['shipping_address_1'] . '/' . $order_info['shipping_zone'] . ' </div>
                <div>Telefon: ' . $order_info['telephone'] . '</div>
              </div>
              

              <div class="alt border-bottom">
                <div class="alt-title">Tahsilat Bilgileri</div>
                <div>' . $product_names . '</div>
               <!-- <div>Dosya Poşet No: </div>
                <div>Fatura No: 1</div>
                <div>İrsaliye No: 1</div> -->
                <div>Toplam: ' . $total . '</div>
                <div>Tahsilat Türü: </div>
              </div>
              <div class="alt">
                <div class="altBilgi">
                  <div>Sipariş Numarası: ' . $yurtici_kargo_info['kargo_barcode'] . '</div>
                  
                  <div>Talep Numarası: ' . $yurtici_kargo_info['kargo_talepno'] . '</div><br>
                  
                  <div><h1 style="color: red;">  ' . $yurtici_kargo_info['kargo_barcode'] . '</h1></div>
                </div>
                <div class="altBarkod">
                ' . $barkod_talepno . '
                </div>
              </div>
            </div><div class="barcode">' . $barkod_cargokey . '</div>';
        }

        $html .= '
          </div>
        </body>
      </html>
        ';



        require_once(DIR_SYSTEM . 'dompdf/autoload.inc.php');

        $dompdf = new Dompdf\Dompdf(array('enable_remote' => true));
        $dompdf->loadHtml($html);

        //$customPaper = array(0, 0, 375, 280);
        $customPaper = array(0, 0, 378, 330);
        $dompdf->set_paper($customPaper);

        $dompdf->render();
        // Output the generated PDF to Browser

        $dompdf->stream("dompdf_out.pdf", array("Attachment" => false));

    }

    public function downloadGeneratedImages()
    {

        $model = $this->request->post ['model'];


        $Zip = new ZipArchive ();

        $Zip->open("ZIP/CollectionZip.$model.zip", ZipArchive::CREATE);


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


        $sql = "SELECT o.order_id, CONCAT(o.firstname, ' ', o.lastname) AS customer, o.row_color_code,

        (SELECT os.name FROM ps_order_status os WHERE os.order_status_id = o.order_status_id AND os.language_id = '" . (int)$this->config->get('config_language_id') . "') AS order_status,

		o.shipping_code, o.total, o.currency_code, o.currency_value, o.date_added, o.date_modified, o.status FROM ps_order o WHERE o.status = 0 AND o.row_color_code = '#ABFF72' ORDER BY o.date_added ASC ";


        $results = $this->db->query($sql)->rows;


        foreach ($results as $result) {


            $order_products = $this->model_sale_order->getOrderProducts($result['order_id']);


            $this->load->model('tool/image');

            foreach ($order_products as $order_product)

                if (strpos($order_product ['model'], $model) !== false)

                    $Zip->addFromString($order_product['admin_pattern_image'], file_get_contents($order_product['admin_pattern_image'] != '' ? ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $order_product['admin_pattern_image'] : ''));

        }


        $Zip->close();


        $this->response->addHeader('Content-Type: application/json');

        $this->response->setOutput(json_encode(array("link" => "https://www.deercase.com/ps-panel/ZIP/CollectionZip.$model.zip")));

    }

    public function toggleStatus()
    {

        $OrderProductID = $this->request->post ['order_product_id'];

        if (isset($OrderProductID))

            $this->db->query("UPDATE ps_order_product SET status = !(status) WHERE order_product_id='" . $OrderProductID . "'");

    }

    public function hideCompleted()
    {
        $Results = $this->db->query("SELECT order_id FROM ps_order_product GROUP BY order_id HAVING SUM(status) = COUNT(*)");
        foreach ($Results->rows as $Result)
            $this->db->query("UPDATE ps_order SET status = 1 WHERE order_id = '" . $Result ['order_id'] . "'");
    }

    public function hideSelected()
    {
        $OrderIDs = $_GET ["OrderIDs"];
        foreach ($OrderIDs as $OrderID)
            $this->db->query("UPDATE ps_order SET status = 1 WHERE order_id = '" . $OrderID . "'");
    }
    public function bulkDownload() {

        $OrderIDs = $this->request->post["selected_order_ids"];
      if(!$OrderIDs){
          die;
      }
                $zipname = 'DeerCase-'.@date("Y-m-d-His").'BulkImages.zip';
               
                $zip = new ZipArchive();
                $zip_file_tmp = tempnam('.','');
               $zip->open($zip_file_tmp, ZipArchive::CREATE);
          

        foreach ($OrderIDs as $OrderID){
            $query=$this->db->query("SELECT admin_pattern_image,admin_gradient_pattern_image,customcase_image FROM ps_order_product  WHERE order_id = '" . $OrderID . "'");
            foreach($query->rows as $row){
                if($row['customcase_image']!=''){
                    $str = explode('***', $row['customcase_image']);
                    $filename=str_replace('cropped','',$str[1]);
                    $customcase_image = ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $filename;
                   // $name=str_replace('upload/cropped','',$str[1]);
                   
                    $download_file = file_get_contents($customcase_image);
                    $zip->addFromString(basename($customcase_image), $download_file);
                }else{
                    if($row['admin_pattern_image']!=''){
                       $admin_pattern_image= ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $row['admin_pattern_image'];
                        
                       // $name=str_replace('admin_pattern_images/','',$row['admin_pattern_image']);
                        //$filepath = DIR_IMAGE.$row['admin_pattern_image'];
                       
                         $download_file = file_get_contents($admin_pattern_image);
                         $zip->addFromString(basename($admin_pattern_image), $download_file);   
                    }
                    if($row['admin_gradient_pattern_image']!=NULL){
                       $admin_gradient_pattern_image= ($this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG) . 'image/' . $row['admin_gradient_pattern_image'];
                        //$name=str_replace('admin_gradient_images/','',$row['admin_pattern_image']);
                         
                          $download_file = file_get_contents($admin_gradient_pattern_image);
                         $zip->addFromString(basename($admin_gradient_pattern_image), $download_file);
                    }
                    
                }
            }
            
        }
                $zip->close();
      
                header('Content-disposition: attachment; filename='.$zipname);
                header('Content-type: application/zip');
                readfile($zip_file_tmp);
                exit;
       
            
    }

    // 18 Ağustos 2020 - @toturkmen - Tolga
    public function toggleReprint()
    {
        $OrderProductID = $this->request->post ['order_product_id'];
        if (isset($OrderProductID))
            $this->db->query("UPDATE ps_order_product SET reprint = !(reprint) WHERE order_product_id='" . $OrderProductID . "'");
    }

}

