<?php
class ControllerToolN11 extends Controller{

    private $error = array();

    public function test()
    {
        $conn = [
            'appKey' => $this->config->get('n11_api_key'),
            'appSecret' => $this->config->get('n11_api_password'),
        ];
        //GetCategoryAttributes

        $data = array(
            'auth' => $conn,
            'categoryId' => '1001796',
            'pagingData' => array(
                'currentPage' => 0,
                'pageSize' => 500,
                'totalCount' => 500,
                'pageCount' => 500
            )
        );

        $productWsdl = 'https://api.n11.com/ws/CategoryService.wsdl';


        $client = new SoapClient($productWsdl);
        $response = $client->GetCategoryAttributes($data);
        foreach ($response->category->attributeList->attribute[0]->valueList->value as $marka){ //var_dump($marka); die();
            echo $marka->name . " <br>";
        }die();
        var_dump($response->category->attributeList->attribute[0] ); die();
            //$result = $response->result->status;

    }

    public function index() {

        //$this->test();

        if($this->config->get('n11_status')){
            $data['install'] = false;
        }else{
            $data['install'] = $this->url->link('tool/n11/install', 'token=' . $this->session->data['token'], true);;
        }

       

        $this->load->model('setting/setting');
        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
            $this->model_setting_setting->editSetting('n11', $this->request->post);

            $data['success'] = 'Ayarlar kayıt edildi';
            $this->response->redirect($this->url->link('tool/n11', 'token=' . $this->session->data['token'], true));
        }


        $this->document->setTitle("N11 Bağlantı Ayarları");

        $data['heading_title'] = "N11 Modül";


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

        if (isset($data['success'])) {
            $data['success'] = "N11 Modül";
        } else {
            $data['success'] = '';
        }


        $url = '';




        $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' => 'N11 Entegrasyon Modülü',
            'href' => $this->url->link('tool/n11', 'token=' . $this->session->data['token'] . $url, true)
        );

        $data['action'] = $this->url->link('tool/n11', 'token=' . $this->session->data['token'], true);


        $data['cancel'] = $this->url->link('common/dashboard', 'token=' . $this->session->data['token'] , true);

        $data['product_transfer_link'] = $this->url->link('tool/n11/n11ProductTransfer', 'token=' . $this->session->data['token'] , true);


        if (isset($this->request->post['n11_api_key'])) {
            $data['n11_api_key'] = trim( $this->request->post['n11_api_key'] );
        } else {
            $data['n11_api_key'] = $this->config->get('n11_api_key');
        }

        if (isset($this->request->post['n11_api_password'])) {
            $data['n11_api_password'] = trim( $this->request->post['n11_api_password'] );
        } else {
            $data['n11_api_password'] = $this->config->get('n11_api_password');
        }

        if (isset($this->request->post['n11_status'])) {
            $data['n11_status'] = $this->request->post['n11_status'];
        } else if($this->config->get('n11_status')){
            $data['n11_status'] = $this->config->get('n11_status');
        }else{
            $data['n11_status'] = 0;
        }



        $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 .'tool/n11/index.tpl')){
            $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'tool/n11/index', $data));
        }else{ 
            $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'tool/n11/index', $data));
        }
    }

    private function setting(){

        $url = '';

        $this->document->setTitle("N11 Bağlantı Ayarları");



        $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' => 'N11 Entegrasyon Modülü',
            'href' => $this->url->link('n11/', 'token=' . $this->session->data['token'] . $url, true)
        );



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

        $this->response->setOutput($this->load->view('n11/setting', $data));

        if(file_exists(DIR_LOCAL_TEMPLATE .'n11/setting.tpl')){
            $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'n11/setting', $data));
        }else{ 
            $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'n11/setting', $data));
        }

    }

    public function n11ProductTransfer(){

        $this->document->setTitle("N11 Ürün Aktarımı");

        $data['heading_title'] = "N11 Ürün Aktarımı";

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

        if (isset($data['success'])) {
            $data['success'] = "N11 Modül";
        } else {
            $data['success'] = '';
        }

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

        $url = '';
        $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' => 'N11 Entegrasyon Modülü',
            'href' => $this->url->link('tool/n11', 'token=' . $this->session->data['token'] . $url, true)
        );

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

        $data['create_new_transfer_link'] = $this->url->link('tool/n11/n11AddProductTransfer', 'token=' . $this->session->data['token'] , true);

        $this->load->model('tool/n11');
        $this->load->model('catalog/category');
        $this->load->model('catalog/product');

        $product_transfer_total = $this->model_tool_n11->getN11ProductTransferTotal();
        $product_transfers = $this->model_tool_n11->getN11ProductTransfers();
       
        $data['product_transfers'] = array();

        foreach ($product_transfers as $item){

            $local_category = $this->model_catalog_category->getCategory($item['local_category_id']);
            $count_product = $this->model_catalog_product->getProductsByCategoryId($item['local_category_id']);
  
            $data['product_transfers'][] = array(
                'product_transfer_id' => $item['id'],
                'transfer_name'       => $item['transfer_name'],
                'local_category_id'   => $item['local_category_id'],
                'local_category_name' => $local_category['name'],
                'category_count'      => count($count_product),
                'status'              => $item['status'],
                'sort_order'          => $item['sort_order'],
                'commission_rate'     => $item['commission_rate'],
                'teslimat_sablonu'    => $item['teslimat_sablonu'],
                'edit'                => $this->url->link('tool/n11/n11EditProductTransfer', 'token=' . $this->session->data['token'] .'&product_transfer_id='. $item['id'] , true),
                'delete'              => $this->url->link('tool/n11/n11DeleteProductTransfer', 'token=' . $this->session->data['token'] .'&product_transfer_id='. $item['id'] , true),
                'log_href'            => $this->url->link('tool/n11/transferlogs', 'token=' . $this->session->data['token'] .'&product_transfer_id='. $item['id'] , true),
                'log_count'           => count($this->model_tool_n11->getLogs($item['id'])),
            );
        }

        $pagination = new Pagination();
        $pagination->total = $product_transfer_total;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_limit_admin');
        $pagination->url = $this->url->link('tool/n11/n11ProductTransfer', 'token=' . $this->session->data['token'] . $url . '&page={page}', true);

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

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


        $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 .'tool/n11/product_transfer.tpl')){
            $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'tool/n11/product_transfer', $data));
        }else{ 
            $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'tool/n11/product_transfer', $data));
        }


    }

    public function n11DeleteProductTransfer(){

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

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

            $this->model_tool_n11->n11DeleteProductTransfer($this->request->get['product_transfer_id']);

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

            $url = '';

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

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

        }

    }

    public function n11EditProductTransfer(){

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

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateProductsTransferForm()) {

            $this->model_tool_n11->n11ProductsTrasnferEdit($this->request->post, $this->request->get['product_transfer_id'] );

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

            $this->response->redirect($this->url->link('tool/n11/n11ProductTransfer', 'token=' . $this->session->data['token'] , true));
        }

        $this->n11ProductTransferForm();
    }

    public function n11AddProductTransfer(){

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

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateProductsTransferForm()) {

            $this->model_tool_n11->n11ProductsTrasnferAdd($this->request->post);

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

            $this->response->redirect($this->url->link('tool/n11/n11ProductTransfer', 'token=' . $this->session->data['token'] , true));
        }

        $this->n11ProductTransferForm();


    }

    public function n11ProductTransferForm(){

        $this->document->setTitle("N11 Ürün Aktarımı");

        $data['heading_title'] = "N11 Ürün Aktarımı";

        $url = '';
        $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' => 'N11 Entegrasyon Modülü',
            'href' => $this->url->link('tool/n11', 'token=' . $this->session->data['token'] . $url, true)
        );


        $data['cancel'] = $this->url->link('tool/n11/n11ProductTransfer', 'token=' . $this->session->data['token'] , true);

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


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

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

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

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

        $data['edit_status'] = 0;

        $this->load->model('tool/n11');
        if (isset($this->request->get['product_transfer_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
            $product_transfer_info = $this->model_tool_n11->getN11ProductTransfer($this->request->get['product_transfer_id']);
            $data['action'] = $this->url->link('tool/n11/n11EditProductTransfer', 'token=' . $this->session->data['token'].'&product_transfer_id='.$this->request->get['product_transfer_id'], true);
            $data['edit_status'] = 1;
        }else{
            $data['action'] = $this->url->link('tool/n11/n11AddProductTransfer', 'token=' . $this->session->data['token'], true);
        }

        if(isset($this->request->post['transfer_name'])){
            $data['transfer_name'] = $this->request->post['transfer_name'];
        }elseif (!empty($product_transfer_info)){
            $data['transfer_name'] = $product_transfer_info['transfer_name'];
        }else{
            $data['transfer_name'] = '';
        }

        
        $categories = $this->model_tool_n11->getCategories();

        $data['categories'] = array();
        foreach ($categories as $category){
            $data['categories'][] = array(
                'name'        => $category['name'],
                'category_id' => $category['category_id'],
            );
        }

        //N11 KATEGORİLERİ
        $data['n11_categories'] =  $this->getN11Categories();
        //sort($data['n11_categories']);
        //N11 KATEGORİLERİ



        if (isset($this->request->post['local_category'])) {
            $data['local_category'] = $this->request->post['local_category'];
        } elseif (!empty($product_transfer_info)) {
            $data['local_category'] = $product_transfer_info['local_category_id'];
        } else {
            $data['local_category'] = '';
        }

        if (isset($this->request->post['n11_top_category'])) {
            $data['n11_top_category'] = $this->request->post['n11_top_category'];
        } elseif (!empty($product_transfer_info)) {
            $data['n11_top_category'] = $product_transfer_info['n11_top_category'];
        } else {
            $data['n11_top_category'] = '';
        }

        if (isset($this->request->post['commission_rate'])) {
            $data['commission_rate'] = $this->request->post['commission_rate'];
        } elseif (!empty($product_transfer_info)) {
            $data['commission_rate'] = $product_transfer_info['commission_rate'];
        } else {
            $data['commission_rate'] = 0;
        }

        if (isset($this->request->post['teslimat_sablonu'])) {
            $data['teslimat_sablonu'] = $this->request->post['teslimat_sablonu'];
        } elseif (!empty($product_transfer_info)) {
            $data['teslimat_sablonu'] = $product_transfer_info['teslimat_sablonu'];
        } else {
            $data['teslimat_sablonu'] = '';
        }

        if (isset($this->request->post['sort_order'])) {
            $data['sort_order'] = $this->request->post['sort_order'];
        } elseif (!empty($product_transfer_info)) {
            $data['sort_order'] = $product_transfer_info['sort_order'];
        } else {
            $data['sort_order'] = 0;
        }

        if (isset($this->request->post['status'])) {
            $data['status'] = $this->request->post['status'];
        } elseif (!empty($product_transfer_info)) {
            $data['status'] = $product_transfer_info['status'];
        } else {
            $data['status'] = true;
        }

        if (isset($this->request->post['description_status'])) {
            $data['description_status'] = $this->request->post['description_status'];
        } elseif (!empty($product_transfer_info)) {
            $data['description_status'] = $product_transfer_info['description_status'];
        } else {
            $data['description_status'] = true;
        }


        $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 .'tool/n11/product_transfer_form.tpl')){
            $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'tool/n11/product_transfer_form', $data));
        }else{ 
            $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'tool/n11/product_transfer_form', $data));
        }

    }

    protected function validateProductsTransferForm(){
        if ( !$this->request->post['transfer_name'] ) {
            $this->error['transfer_name'] = "Transfer adı yazmalısınız!";
        }

        if ( !$this->request->post['local_category'] ) {
            $this->error['local_category'] = "Kategori seçmelisiniz!";
        }

        /*
        if ( !$this->request->post['n11_top_category'] ) {
            $this->error['n11_category'] = "N11 Kategorisi seçmelisiniz!";
        }*/

        if ( !$this->request->post['teslimat_sablonu'] ) {
            $this->error['teslimat_sablonu'] = "N11 Kategorisi seçmelisiniz!";
        }

        if ( !$this->error ) { return true; }
        else { return false; }


    }

    public function transferlogs(){

        $data['heading_title'] = "N11 Ürün Aktarımı Logları";
        $this->document->setTitle($data['heading_title']);

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

        $url = '';
        $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' => 'N11 Ürün Aktarımı Logları',
            'href' => $this->url->link('tool/n11', 'token=' . $this->session->data['token'] . $url, true)
        );

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

        $this->load->model('tool/n11');
       
        $total_logs = $this->model_tool_n11->getTotalLogs($this->request->get['product_transfer_id']);
        $logs = $this->model_tool_n11->getLogs($this->request->get['product_transfer_id']);

        $this->load->model('catalog/product');

        $data['logs'] = array();
        foreach($logs as $log){
            $product = $this->model_catalog_product->getProduct($log['product_id']);
            $data['logs'][] = array(
                'product_transfer_id' => $log['id'],
                'product_name' => $product['name'],
                'product_model' => $product['model'],
                'product_id' => $product['product_id'],
                'mesaj' => $log['mesaj'],
                'date' => $log['date'],
            );
        }

            
           
        

        $pagination = new Pagination();
        $pagination->total = $total_logs;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_limit_admin');
        $pagination->url = $this->url->link('tool/n11/n11ProductTransfer', 'token=' . $this->session->data['token'] . $url . '&page={page}', true);

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

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

        
        
        $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 .'tool/n11/product_transfer_log.tpl')){
            $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'tool/n11/product_transfer_log', $data));
        }else{ 
            $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'tool/n11/product_transfer_log', $data));
        }
    }

    protected function validate(){
        if ( !$this->user->hasPermission('modify', 'tool/n11') ) {
            $this->error['warning'] = 1;
        }

        if ( !$this->request->post['n11_api_key'] ) {
            $this->error['n11_api_key'] = "API Anahtarını girmelisiniz!";
        }

        if ( !$this->request->post['n11_api_password'] ) {
            $this->error['n11_api_password'] = "API Şifresini yazmalısınız!";
        }



        if ( !$this->error ) { return true; }
        else { return false; }
    }

    private function getN11Categories(){

       
        $categoryWsdl = 'https://api.n11.com/ws/CategoryService.wsdl';

        $conn['auth'] = array(
            'appKey' => $this->config->get('n11_api_key'),
            'appSecret' => $this->config->get('n11_api_password'),
        );

        $client = new \SoapClient($categoryWsdl);
        $response = $client->GetTopLevelCategories($conn);
        $response = $response->categoryList->category;
        $response = json_decode( json_encode($response) , 1);

        $categories = array();
        foreach ($response as $res){ 
            $categories[] = array(
                'id' => $res['id'],
                'name' => $res['name']
            );
        }
        return  $categories;
    }

    public function getN11SubCategory(){

        $json = array();
       
        $categoryWsdl = 'https://api.n11.com/ws/CategoryService.wsdl';

        $conn['auth'] = array(
            'appKey' => $this->config->get('n11_api_key'),
            'appSecret' => $this->config->get('n11_api_password'),
        );

        $conn['categoryId'] = $this->request->get['sub_category_id'];

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

        if(isset($this->request->get['sub_category_id']) AND $this->request->get['sub_category_id'] != 0 ){

            $client = new SoapClient($categoryWsdl);
            $response = $client->GetSubCategories($conn);
            $result = $response->result->status;
            //var_dump($result);
            if(isset($response->category->subCategoryList->subCategory)){
                $response = $response->category->subCategoryList->subCategory;
                $response = json_decode( json_encode($response) , 1);

                foreach ($response as $res){
                    $json['sub_categories'][] = array(
                        'id'    => $res['id'],
                        'name'  => $res['name']
                    );

                    $con2 = array(
                        'auth' => array(
                            'appKey' => $this->config->get('n11_api_key'),
                            'appSecret' => $this->config->get('n11_api_password'),
                        ),
                        'categoryId' => $res['id'],
                    );

                }
                
            }else{
                $json['error'] = "Alt kategori sonu!";
            }

        }else{
            $json['error'] = "Kategori seçmelisiniz!!!";
        }

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

    public function getSubCategory(){

        $json = array();


       if(isset($this->request->get['sub_category_id'])){
            $category_id = $this->request->get['sub_category_id'];

            $this->load->model('tool/n11');
            $categories = $this->model_tool_n11->getCategories($category_id);

            if(count($categories) > 0){
                foreach ($categories as $key => $value) {
                    $json['sub_categories'][] = array(
                        'id'    => $value['category_id'],
                        'name'  => $value['name']
                    );
                }
            }else{
                $json['sub_categories'] = false;
            }
            

       }else{
            $json['error'] = "Kategori seçmelisiniz!!!";
       }


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

    public function startEntegrasyon(){

        $log = new Log("N11startEntegrasyonLog.txt");
        $json = array();

        $success_sends =0;
        $error_sends =0;
        $json['sonuc'] = '';

        $conn = [
            'appKey' => $this->config->get('n11_api_key'),
            'appSecret' => $this->config->get('n11_api_password'),
        ];

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

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

            $this->load->model('tool/n11');
            $get_record = $this->model_tool_n11->getN11ProductTransfer($product_transfer_id);
            $this->model_tool_n11->logDelete($product_transfer_id);
            $local_category_id = $get_record['local_category_id'];
            $this->load->model('catalog/product');
            $products = $this->model_catalog_product->getProductsByCategoryId($local_category_id);
            
            $info = array();

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

            foreach ($products as $item){ 

                $price = $this->calcPrice(array(
                    'price' => $item['price'],
                    'special' => $item['special'], 
                    'tax_class_id' => $item['tax_class_id'],
                    'commission_rate' => $get_record['commission_rate'])
                );

                $get_product_options = $this->model_catalog_product->getProductOptions($item['product_id']);
                $product_options = array();
                $stock_items = array();
                if(count($get_product_options) > 0){
                    foreach ($get_product_options as $get_product_option){
                        foreach ($get_product_option['product_option_value'] as $key => $product_option_value){

                            $option_info = $this->model_catalog_product->getProductOptionValue($item['product_id'],$product_option_value['product_option_value_id'] );

                            $stock_items['stockItem'][] = [
                                'gtin'            => date('Ymdhi').$product_option_value['option_value_id'],
                                'sellerStockCode' => $product_option_value['option_value_id'].'-'.$item['product_id'],
                                'quantity'        => (int)$option_info['quantity'],
                                'attributes'      => [
                                    'attribute' => [
                                        'name'  => $get_product_option['name'],
                                        'value' => $option_info['name']
                                    ],
                                ],
                                'optionPrice'     => $price,
                                'bundle'          => '',
                                'mpn'             => '',
                            ];
                        }

                    }
                }else{ 
                    $stock_items = [
                        'stockItem' => [
                            'sellerStockCode' => $item['model'].'-'.$item['product_id'],
                            'quantity'        => (int)$item['quantity'],
                            'attributes'      => '',
                            'optionPrice'     => '',
                            'bundle'          => '',
                            'mpn'             => '',
                            'gtin'            => '',
                        ]
                    ];
                }

                $images['image'] = array();
                $images['image'][] = [
                    'url'   => 'https://'. $_SERVER['SERVER_NAME'] .'/image/'.$item['image'],
                    'order' => 0
                ];
                $this->load->model('catalog/product');
                $product_images = $this->model_catalog_product->getProductImages($item['product_id']);
                foreach($product_images as $ikey => $image){
                    $images['image'][] = [
                        'url'   => 'https://'. $_SERVER['SERVER_NAME'] .'/image/'.$image['image'],
                        'order' => $ikey++
                    ];
                }

                $n11_attributes = $this->model_tool_n11->getN11CategoryAttributes($get_record['n11_sub_category_3']);
                $attributes = array();
                $attributes['attribute'][] = [
                    'name'  => 'Marka',
                    'value' => 'Derinet',
                ];
                /*foreach ($n11_attributes as $attr){
                    $attributes['attribute'][] = [
                        'name'  => $attr['name'],
                        'value' => 'Diğer',
                    ];
                }
                unset($attributes[1]);*/
                $n11_send_category = $get_record['n11_sub_category_3'];
                if($n11_send_category == 0){
                    $n11_send_category = $get_record['n11_sub_category_second'];
                }


                $name = html_entity_decode(substr($item['name'],0,55), ENT_QUOTES, 'UTF-8');
                if($get_record['description_status']){
                    $description = html_entity_decode($item['description'] . "<br> <b>Piyer Soft</b> tarafından yayınlanmıştır!", ENT_QUOTES, 'UTF-8');
                }else{
                    $description = html_entity_decode("<b>Piyer Soft</b> tarafından yayınlanmıştır!", ENT_QUOTES, 'UTF-8');
                }
                
                $product = [
                    'productSellerCode' => $item['model'],
                    'title'             => $name,
                    'subtitle'          => $name,
                    'description'       => $description,
                    'attributes'        => $attributes,
                    'category'          => array( 'id' => $n11_send_category ),
                    'price'             => $price,
                    'currencyType'      => $item['currency_id'],
                    'images'            => $images,
                    'saleStartDate'     => '',
                    'saleEndDate'       => '',
                    'productionDate'    => '',
                    'expirationDate'    => '',
                    'discount'          => '',
                    'productCondition'  => 1,
                    'preparingDay'      => 3,
                    'shipmentTemplate'  => $get_record['teslimat_sablonu'],
                    'stockItems'        => $stock_items,
                    'domestic'          => true
                ];

                $info = [
                    'auth'    => $conn,
                    'product' => $product,
                ];

                $product_to_product = $this->model_tool_n11->getN11ProductToProduct($item['product_id']);
                $entegrasyon = 0;
                if(isset($product_to_product['local_product_id'])){
                    if(!$this->model_tool_n11->blockProducts($item['product_id'])){
                        $entegrasyon = $this->n11EntegrasyonProductSend($info, $item['product_id'] ,$product_transfer_id);
                    }
                }else{
                    if(!$this->model_tool_n11->blockProducts($item['product_id'])){
                        $entegrasyon = $this->n11EntegrasyonProductSend($info, $item['product_id'], $product_transfer_id);
                    }
                }

               if($entegrasyon){
                    $log->write($item['model'] .' - '. $price . ' Success');
                   $success_sends++;
               }else{
                    $log->write($item['model'] .' - '. $price . ' Failure');
                   $error_sends++;
               }
            }

            if($success_sends == 0){ 
                $json['sonuc'] = "Bu kategorideki hiçbir ürün N11 e gönderilemedi!";
            }else if($error_sends > 0){
                $json['sonuc'] = "Tüm ürünler başarılı birşekilde N11 e aktarıldı";
            }else{
                $json['sonuc'] = 'N11 e gönderilen ürün adeti: '.$success_sends. ' Gönderilemeyen: '.$error_sends;
            }

        }

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


    }

    private function n11EntegrasyonProductSend($data= array(), $product_id, $product_transfer_id){

        $json = array();
        $this->load->model('tool/n11');

        $productWsdl = 'https://api.n11.com/ws/ProductService.wsdl';

        try{
            $client = new SoapClient($productWsdl);
            $response = $client->SaveProduct($data);
            $result = $response->result->status;
        }catch (Exception $e){
           echo $e;
        }

        $save_info = array();

        if($result == "success"){
            $save_info = array(
                'product_transfer_id'   => $product_transfer_id,
                'local_product_id'      => $product_id,
                'n11_product_id'        => $response->product->id,
                'productSellerCode'     => $response->product->productSellerCode,
                'saleStatus'            => $response->product->saleStatus,
                'approvalStatus'        => $response->product->approvalStatus,
            );
            $this->model_tool_n11->addN11ProductToProduct($save_info);
            $json = 1;
        }else if ($result == "failure"){
            $save_info = array(
                'local_product_id'      => $product_id,
                'product_transfer_id'   => $product_transfer_id,
                'n11_product_id'        => '',
                'mesaj'                 => $response->result->errorMessage,
            );
            $this->model_tool_n11->addN11EntegrasyonHataLog($save_info);
            $json = 0;
        }

        return $json;

        

    }

    public function startPriceUpdate(){
        $json = array();

        $success_sends =0;
        $error_sends =0;
        $json['sonuc'] = '';

        //startStockUpdate

        $conn = array(
            'appKey' => $this->config->get('n11_api_key'),
            'appSecret' => $this->config->get('n11_api_password'),
        );

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

            $this->load->model('tool/n11');
            $get_record = $this->model_tool_n11->getN11ProductTransfer($this->request->get['product_transfer_id']);
            $local_category_id = $get_record['local_category_id'];

            $this->load->model('catalog/product');
            $products = $this->model_catalog_product->getProductsByCategoryId($local_category_id);

            $info = array();

            $data = new stdClass;

             foreach ($products as $product){

                 $n11_product_info = $this->model_tool_n11->getN11ProductToProduct($product['product_id']);

                // $price = number_format((float)$product['price'], 2, '.', '');

                 $price = $this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax'));

                 $data->auth = new stdClass;
                 $data->auth->appKey = $this->config->get('n11_api_key');
                 $data->auth->appSecret = $this->config->get('n11_api_password');
                 $data->productId = $n11_product_info['n11_product_id'];
                 $data->price = $price;
                 $data->currencyType = 3;
                 $data->product = new stdClass;
                 $data->product->stockItems = new stdClass;
                 $data->product->stockItems->stockItem = new stdClass;
                 $data->product->stockItems->stockItem->sellerStockCode = '';
                 $data->product->stockItems->stockItem->optionPrice = '';


                 $update = $this->n11EntegrasyonPriceUpdate($data, $product['product_id'],$n11_product_info['n11_product_id']);

                 if($update['success'] == 1){
                     $success_sends++;
                 }else{
                     $error_sends++;
                 }

             }



            if($success_sends == 0){
                $json['sonuc'] = "Bu kategorideki hiçbir ürün N11 e gönderilemedi!";
            }else if($error_sends == 0){
                $json['sonuc'] = "Tüm ürünler başarılı birşekilde N11 e aktarıldı";
            }else{
                $json['sonuc'] = 'N11 e gönderilen ürün adeti: '.$json['success_sends']. ' Gönderilemeyen: '.$json['error_sends'];
            }

        }

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

    }

    private function n11EntegrasyonPriceUpdate($data = array(), $product_id, $n11_product_id){
        $json = array();
        $this->load->model('tool/n11');
        $productWsdl = 'https://api.n11.com/ws/ProductService.wsdl';



        try{
            $client = new SoapClient($productWsdl);
            $response = $client->UpdateProductPriceById($data);
            $result = $response->result->status;
        }catch (Exception $e){
            echo $e;
        }

        $save_info = array();

        if($result == "success"){

            $json['success'] = 1;
        }elseif ($result == "failure"){
            $save_info = array(
                'local_product_id'  => $product_id,
                'n11_product_id'    => $n11_product_id,
                'mesaj'             => $response->result->errorMessage,
            );
            $this->model_tool_n11->addN11EntegrasyonHataLog($save_info);
            $json['success'] = 0;
        }

        return $json;
    }

    public function startStockUpdate(){ 

        $json = array();

        $success_sends =0;
        $error_sends =0;
        $json['sonuc'] = '';

        //startStockUpdate

        $conn = array(
            'appKey'    => $this->config->get('n11_api_key'),
            'appSecret' => $this->config->get('n11_api_password'),
        );

        

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


            $this->load->model('tool/n11');
            $get_record = $this->model_tool_n11->getN11ProductTransfer($this->request->get['product_transfer_id']);
            $local_category_id = $get_record['local_category_id'];

            $this->load->model('catalog/product');
            $products = $this->model_catalog_product->getProductsByCategoryId($local_category_id);

            $info = array();
            /*
            foreach ($products as $product){ 

            }

            */

        }

    }

    public function calcPrice($data = array()){

        if($data['special']){
            $price = $data['special'];
        }else{
            $price = $data['price'];
        }

        if($data['tax_class_id'] == 1){
            $price *= 1.18;
        }elseif($data['tax_class_id'] == 2){
            $price *= 1.08;
        }
        if($data['commission_rate']){
            $price += ($price / 100) * $data['commission_rate'];
        }
        return $price;
    }

    public function install(){
        $this->load->model('tool/n11');

        $this->model_tool_n11->install();

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


}
?>