<?php

include "system/library/logo.php";

/**

 * Logo Tiger Programına Siteden Aktarım için Controller Dosyası

 * 

 * @author Can Yiğit KAV

 */

class ControllerModuleLogo extends Controller {

    /**

     * İşleyiş:

     * 1- Siparişin müşterisi Logo'da yoksa Logo'ya eklenir.

     * 2 -(sonradan ekleme) ürüne ait materyal yoksa materyal oluşturulur.

     * 2- Siparişin ürünlerinin ait olduğu materyaller Logo'da yoksa Logo'ya eklenir.

     * 3- Siparişin içine müşteri eklenir ve ürünler materyalle değiştirilerek eklenir.

     * 4- Sipariş Logo'ya gönderilir.

     * 

     * Bu işlemler sırasında hata oluşması durumunda siparişin logo_message sütununa hata mesajı eklenir.

     * Bir siparişin (order tablosunda) logo_reference sütunu boş olmasına rağmen logo_message sütunu doluysa sipariş eklenememiştir. Sitede uyarı bildirimleri gösterilebilir.

     * 

     * @param string  $route     Sipariş sonrası bu dosyayı tetikleyen route linkidir.

     * @param array   $output    Sipariş Numarası ve Sipariş Durumunu bir dizi içerisinde sağlar.

     * @param boolean $manually  Fonksiyonun event ile değil manuel olarak gönderme talebi yapıldığını bildirir.

     */

    public function send($route, $output, $manually = false) {

exit;

        $order_id = $output[0];

        $order_status_id = $output[1];



        # 17: Kargoya teslim edildi.

        if( ($order_status_id==17 && !empty($order_id)) || $manually == true) {

            $this->load->model('account/customer');

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

            $logo = new Logo;

            $order_info = $this->model_module_logo->getOrder($order_id);



            if($manually==true) { # Sipariş manuel eklenmeye çalışılıyorsa daha önce eklenmiş bir (hata) mesajı(nı) dikkate alma.

                $order_info['logo_message'] = null;

            }



            if(empty($order_info['logo_message']) && empty($order_info['logo_reference'])) {

                $customer_info = $this->model_account_customer->getCustomer($order_info['customer_id']);

                

                $order_products = $this->model_module_logo->getOrderProductsIds($order_id); 

                # Sipariş ürünlerinin materyaliyle eşleştirilmesi, yoksa materyalin oluşturulması

                for ($i=0; $i < count($order_products); $i++) { 

                    $order_product_info = $this->model_module_logo->getOrderProduct($order_products[$i]['order_product_id']); 

                    if(empty($order_product_info['barcode'])) {

                        # materyalin barkodu dağıtılmamış olabilir

                        # barkod kodu üret ve böyle bir materyal var mı sorgula

                        # varsa materyali kullan. 

                        # yoksa üret 



                        $categories = $this->db->query("SELECT c.category_id, c.infinityeditid, cd.name FROM ps_product_to_category p2c

                            LEFT JOIN ps_category c ON (p2c.category_id = c.category_id)

                            LEFT JOIN ps_category_description cd ON (c.category_id = cd.category_id)

                            WHERE p2c.product_id = '" . $order_product_info['product_id'] . "' GROUP BY c.category_id 

                        ")->rows;



                        if(count($categories)>1) { # kategori varsa barkod üret. 

                            $category = $categories[count($categories)-1];



                            if(count($categories)>2) {

                                $category = $categories[count($categories)-2];

                            }                            

                            $color = $this->db->query("SELECT ad.`name`, a.infinityeditid, a.attribute_id 

                                FROM ps_product AS p 

                                INNER JOIN ps_product_attribute AS pa ON p.product_id = pa.product_id

                                INNER JOIN ps_attribute AS a ON pa.attribute_id = a.attribute_id

                                INNER JOIN ps_attribute_description AS ad ON a.attribute_id = ad.attribute_id

                                INNER JOIN ps_attribute_group AS ag ON a.attribute_group_id = ag.attribute_group_id 

                                WHERE a.attribute_group_id = 13

                                AND p.product_id = '" . $order_product_info['product_id'] ."'

                                ")->row;



                            $collection = $this->db->query("SELECT ad.`name`, a.infinityeditid, a.attribute_id 

                                FROM ps_product AS p 

                                INNER JOIN ps_product_attribute AS pa ON p.product_id = pa.product_id

                                INNER JOIN ps_attribute AS a ON pa.attribute_id = a.attribute_id

                                INNER JOIN ps_attribute_description AS ad ON a.attribute_id = ad.attribute_id

                                INNER JOIN ps_attribute_group AS ag ON a.attribute_group_id = ag.attribute_group_id 

                                WHERE a.attribute_group_id = 11

                                AND p.product_id = '" . $order_product_info['product_id'] ."'

                            ")->row;



                            $barcode_category = !empty($category['infinityeditid']) ? $category['infinityeditid'] : $category['category_id'];

                            $barcode_collection = !empty($collection['infinityeditid']) ? $collection['infinityeditid'] : $collection['attribute_id'];

                            $barcode_color = !empty($color['infinityeditid']) ? $color['infinityeditid'] : $color['attribute_id'];

                            $barcode = $barcode_category . $barcode_collection . $barcode_color;



                            $barcode_query = $this->db->query("SELECT * FROM ps_product_stock WHERE barcode ='" . $barcode . "'")->row;



                            $true_product_stock_id = null;

                            if(empty($barcode_query)) {

                                $category_name = str_replace("Telefon Kılıfı", "", $category['name']);

                                $short_color_name = preg_replace('/('. $collection['name'] .'(?!.*'.$collection['name'].'))/', "", $color['name']); #renk adı koleksiyon adını içeriyorsa kısaltır.

                                $material_name = $category_name . ' ' . $collection['name'] . ' ' . $short_color_name;

                                $material_name = str_replace("  "," ", $material_name); # iki boşluk karakteri yan yanaysa birini temizler.

                                $this->db->query("INSERT INTO " . DB_PREFIX . "product_stock  

                                    SET product_stock_id = '" . (int)$barcode . "', 

                                        barcode = '" . (int)$barcode . "', 

                                        name = '" . $material_name . "', 

                                        category_id = '" . $category['category_id'] . "', 

                                        category_name = '" . $category['name'] . "', 

                                        collection_id = '" . $collection['attribute_id'] . "', 

                                        collection_name = '" . $collection['name'] . "',

                                        color_id = '" . $color['attribute_id'] . "', 

                                        color_name = '" . $color['name'] . "',    

                                        quantity = 0,

                                        kquantity = 0,

                                        price = 0,

                                        price_cost = 0

                                ");

                                # oluşturulan materyal ürüne kaydedilir.

                                $this->model_module_logo->saveMaterialToProduct($order_product_info['product_id'], $barcode, $barcode);

                                $true_product_stock_id = $barcode;

                                # Dizi içinde aynı üründen daha varsa o ürünlere de barkod ver.

                            } else {

                                # materyal bulunduğu için yeni materyal üretimeden materyal ürüne kaydedilir.

                                $this->model_module_logo->saveMaterialToProduct($order_product_info['product_id'], $barcode_query['product_stock_id'], $barcode_query['barcode']);

                                $true_product_stock_id = $barcode_query['product_stock_id'];

                            }

                        }

                    }

                }



                for ($i=0; $i < count($order_products); $i++) { 

                    $order_product_info = $this->model_module_logo->getOrderProduct($order_products[$i]['order_product_id']); 



                    if(!empty($order_product_info['product_stock_id'])) {

                        $material = $this->model_module_logo->getMaterial($order_product_info['product_stock_id']);



                        $name_part1 = substr($material['name'], 0, 50);

                        $name_part2 =  substr($material['name'], 50);

                        

                        # üretilen veya bulunan materyal logo'da yok ise logo'ya kaydet.

                        if($material['logo_reference']==null) {

                            $material_data = [

                                "INTERNAL_REFERENCE" => "0",

                                "CARD_TYPE" => "1",

                                "CODE" => $material['barcode'],

                                "NAME" => $name_part1,

                                "NAME3" => $name_part2,

                                "USEF_PURCHASING" => 1,

                                "USEF_MM" => 1,

                                "VAT" => "20.0",

                                "AUTOINCSL" => "1",

                                "LOTS_DIVISIBLE" => "1",

                                "UNITSET_CODE" => "05",

                                "SELVAT" => "20.0",

                                "RETURNVAT" => "20.0",

                                "SELPRVAT" => "20.0",

                                "RETURNPRVAT" => "20.0"

                            ];

                            

                            $post_material = $logo->postLogo('/api/v1/items', json_encode($material_data)); 

    

                            if(!empty($post_material['INTERNAL_REFERENCE']) && !empty($post_material['CODE'])) {

                                $material_ref = $post_material['INTERNAL_REFERENCE'];

                                $material_barcode = $post_material['CODE'];

                                $material_data = [

                                    'INTERNAL_REFERENCE' => $material_ref,

                                    'CODE' => $material_barcode

                                ];

                                $this->model_module_logo->saveMaterial($order_product_info['product_stock_id'], $material_data);

                            } else {

                                $error_keys = ['DBError', 'ServerError','ValError0','OtherError'];

                                foreach($error_keys as $key) {

                                    if(!empty($post_material['ModelState'][$key])) {

                                        $error = $post_material['ModelState'][$key];

                

                                        $log = new Log("logo/failed_materials.log");

                                        $log->write("Order #". $order_id .": " . json_encode($error));

                    

                                        $message = "Sipariş aktarılamadı. Materyal eklenirken hata oluştu." ;

                                        $this->model_module_logo->updateOrderLogoMessage($order_id, $message);

                                        if($manually = true) {

                                            return $message;

                                        } else {

                                            exit;

                                        }

                                    }

                                }

                            }

                        }  

                    }

                }



                # Eksik materyal ve barkodlar tamamlandığı için ürünler yeni verileriyle tekrar çekilir.

                $order_products = $this->model_module_logo->getOrderProducts($order_id); 



                if($customer_info==false) {

                    $customer_info = [

                        'firstname' => $order_info['firstname'],

                        'lastname' => $order_info['lastname'],

                        'tc' => $order_info['tc'], 

                        'email' => $order_info['email'],

                        'logo_code' => null,

                        'logo_reference' => null

                    ];

                }

                $address = $city = $zone = $country = "";

                if(!empty($order_info)) {

                    $address = $order_info['payment_address_1'];

                    $city = $order_info['payment_city'];

                    $zone = $order_info['payment_zone'];

                    $country = $order_info['payment_country'];

                }



                $customer_code =  !empty($customer_info['logo_code']) ? $customer_info['logo_code'] : null;

                # Müşteri logo'da ekli değilse müşteri ekle. 

                if($customer_info['logo_code']==null) {

                    $customer_logo_data = [

                        "INTERNAL_REFERENCE" => "0",

                        "ACCOUNT_TYPE" => "3",

                        "CODE" => isset($customer_info['customer_id']) ? $customer_info['customer_id'] : "MSFR".$order_id.rand(0,9), # Üyeliksiz siparişlerde müşteri hangi sipariş için üretildiyse sipariş id + rastgele rakam ile eşsiz kimlik almış olur.

                        "TITLE" => $customer_info['firstname'].' '.$customer_info['lastname'],

                        "ADDRESS1" => $address,

                        "TOWN" => $city,

                        "CITY" => $zone,

                        "COUNTRY" => $country,

                        "ISFOREIGN" => "0",

                        "PERSCOMPANY" => "1",

                        "TCKNO" => isset($customer_info['tc']) && !empty($customer_info['tc']) ? $customer_info['tc'] : "11111111111",

                        "TAX_ID" => "",

                        "TAX_OFFICE" => "",

                        "TAX_OFFICE_CODE" => "",

                        "PURCHBRWS" => "1",

                        "SALESBRWS" => "1",

                        "IMPBRWS" => "1",

                        "EXPBRWS" => "1",

                        "FINBRWS" => "1",

                        "ACCEPT_EINV" => "0",

                        "EARCHIVE_IS_RETAIL_AR_AP" => "1",

                        "NAME" => $customer_info['firstname'],

                        "SURNAME" => $customer_info['lastname'],

                        "CREATE_WH_FICHE" => 1

                    ];



                    /*

                    if(!empty($order_info['payment_company'])) {

                        $customer_logo_data['TITLE'] = $order_info['payment_company'];

                        unset($customer_logo_data['TCKNO']);

                        unset($customer_logo_data['PERSCOMPANY']);

                        $customer_logo_data['TAX_ID'] = $order_info['payment_company_tax_no'] ? $order_info['payment_company_tax_no'] : "";

                        $customer_logo_data['TAX_OFFICE'] = $order_info['payment_company_taxadmin'] ? $order_info['payment_company_taxadmin'] : "";

                    }

                */

                    $logo_customer = $logo->postLogo('/api/v1/ARPs', json_encode($customer_logo_data));



                    # Müşteri eklenirken hata oluşmuşsa log yaz. Sipariş aktarılamadı mesajı oluştur. İşlemi durdur.

                    if(!empty($logo_customer['ModelState']['LoginError']) || !empty($logo_customer['ModelState']['DBError']) || !empty($logo_customer['ModelState']['ServerError'])) {

                        $error = !empty($logo_customer['ModelState']['DBError']) ? $logo_customer['ModelState']['DBError'] : $logo_customer['ModelState']['ServerError'];

                        $log = new Log("logo/failed_orders.log");

                        $log->write("Order #". $order_id .": " . json_encode($error));

    

                        $message = "Sipariş aktarılamadı. Müşteri eklenirken hata oluştu.";

                        $this->model_module_logo->updateOrderLogoMessage($order_id, $message);

                        if($manually = true) {

                            return $message;

                        } else {

                            exit;

                        }

                    }

    

                    $customer_code = $logo_customer['CODE'];

                    $customer_logo_data = [

                        'INTERNAL_REFERENCE' => $logo_customer['INTERNAL_REFERENCE'],

                        'CODE' => $customer_code

                    ];

                    # müşteri varsa müşterinin logo referansını müşteri satırına ekle.

                    if(!empty($customer_info['customer_id'])) {

                        $this->model_module_logo->updateCustomerLogoData($customer_info['customer_id'], $customer_logo_data);

                    }

                    

                }

                

                $order_totals = $this->model_module_logo->getOrderTotals($order_id); 

        

                $logo_order_products = [];

    

                # Ürünlerin faturaya eklendiği döngü

                foreach($order_products as $product) {

                    $material_barcode = !empty($product['logo_code']) ? $product['logo_code'] : '0000000001';

                    

                    $product_total_tax = $product['tax']*$product['quantity'];

                    $product_tax_rate = round(1/($product['price']/$product['tax']),2)*100;

                    array_push($logo_order_products,

                        [

                            "INTERNAL_REFERENCE" => 0,

                            "TYPE" => "0",

                            "MASTER_CODE" => $material_barcode,

                            "QUANTITY" => $product['quantity'],

                            "PRICE" => $product['price'] + $product['tax'], 

                            "TOTAL" => $product['total'] + $product_total_tax, 

                            "UNIT_CODE" => "ADET", 

                            "VAT_INCLUDED" => "1", # kdv dahil mi bilgisi

                            "VAT_RATE" => $product_tax_rate,

                            "VAT_AMOUNT" => $product_total_tax,

                            "VAT_BASE" => $product['total'], #matrah

                        ]

                    );

    

                    # Hediye ürünün tutarının indirim olarak yansıtılması

                    $is_name_contains_gift = strpos($product['name'], '(Hediye)');

                    if($is_name_contains_gift!==false) {

                        array_push($logo_order_products,

                            [

                                "INTERNAL_REFERENCE" => "0",

                                "TYPE" => "2",

                                "DISCOUNT_RATE" => 100,

                                "UNIT_CONV1" => 0,

                                "UNIT_CONV2" => 0,

                                "BILLED" => 1,

                                "NET_DSC_FLAG" => 1,

                                "NET_DSC_RATE" => 100,

                                "NET_DSC_AMOUNT" => 99.9,

                                "DIST_ORD_REFERENCE" => 0,

                                "MULTI_ADD_TAX" => 0,

                            ]

                        );

                    }

                }



                # Kapıda Ödemeli Sipariş ise 

                if($order_info['payment_code'] == 'cod') {

                    $cod_cost = $this->config->get('codtotal_fee');

                    array_push($logo_order_products,

                    [

                        "INTERNAL_REFERENCE" => 0,

                        "TYPE" => "4",

                        "MASTER_CODE" => "000000000000000000000001",

                        "QUANTITY" => "1",

                        "PRICE" => $cod_cost*1.20, 

                        "TOTAL" => $cod_cost*1.20,

                        "UNIT_CODE" => "ADET", 

                        "VAT_INCLUDED" => "1", # kdv dahil mi bilgisi

                        "VAT_RATE" => "20",

                        "VAT_AMOUNT" => $cod_cost*1.20-$cod_cost,

                        "VAT_BASE" => $cod_cost, #matrah

                    ]);

                }



                # İyzico taksit ücreti varsa eklenmesi

                if($order_totals['iyzico_checkout_form_fee']>0) {

                    $iyzico_amount = $order_totals['iyzico_checkout_form_fee'];

                    array_push($logo_order_products,

                    [

                        "INTERNAL_REFERENCE" => 0,

                        "TYPE" => "4",

                        "MASTER_CODE" => "000000000000000000000002",

                        "QUANTITY" => "1",

                        "PRICE" => $iyzico_amount,

                        "TOTAL" => $iyzico_amount,

                        "UNIT_CODE" => "ADET", 

                        "VAT_INCLUDED" => "1", # kdv dahil mi bilgisi

                        "VAT_RATE" => "20",

                        "VAT_AMOUNT" => $iyzico_amount - ($iyzico_amount/1.20), 

                        "VAT_BASE" => $iyzico_amount/1.20, #matrah                            

                    ]);

                }



                # Kupon kullanımı varsa eklenmesi

                if($order_totals['coupon']>0) {

                    array_push($logo_order_products,

                    [

                        "INTERNAL_REFERENCE" => 0,

                        "TYPE" => "2",

                        "MASTER_CODE" => "KUPON",

                        "QUANTITY" => "1",

                        "DETAIL_LEVEL" => "1",

                        "DISCEXP_CALC" => "1",

                        "QUANTITY" => "0",

                        "TOTAL" => $order_totals['coupon'],

                    ]);

                }



                # Puan kullanımı varsa eklenmesi

                if($order_totals['reward']>0) {

                    array_push($logo_order_products,

                    [

                        "INTERNAL_REFERENCE" => 0,

                        "TYPE" => "2",

                        "MASTER_CODE" => "PUAN",

                        "QUANTITY" => "1",

                        "DETAIL_LEVEL" => "1",

                        "DISCEXP_CALC" => "1",

                        "QUANTITY" => "0",

                        "TOTAL" => ($order_totals['reward']/1.20),

                    ]);

                }



                # Ekstra İndirim varsa eklenmesi

                if($order_totals['extra_discount']>0) {

                    array_push($logo_order_products,

                    [

                        "INTERNAL_REFERENCE" => 0,

                        "TYPE" => "2",

                        "MASTER_CODE" => "EKİNDİRİM",

                        "QUANTITY" => "0",

                        "TOTAL" => $order_totals['extra_discount'],

                        "BASE_AMOUNT" => ($order_totals["sub_total_amount"]/9)*10, # TODO: tam değeri çek

                        "DISCOUNT_RATE" => 10, # TODO: tam değeri çek

                        "MULTI_ADD_TAX" => 0,

                        "DETAIL_LEVEL" => 1

                    ]);

                }



                # Ödeme yöntemine kod verilmesi

                switch ($order_info['payment_code']) {

                    case 'cod':

                        $special_code = "KO";

                        break;                    

                    case 'iyzico_checkout_form':

                        $special_code = "KK";

                        break;                                       

                    case 'bank_transfer':

                        $special_code = "HAVALE";

                        break;

                    default:

                        $special_code = "";

                        break;

                }



                $shipment_date = !empty($this->model_module_logo->getOrderShipmentDate($order_id)) ? $this->model_module_logo->getOrderShipmentDate($order_id) : date('Y-m-d', strtotime($order_info['date_modified']));



                # Fatura genel bilgileri

                $sale_invoice_data = [

                    "INTERNAL_REFERENCE" => "0",

                    "GRPCODE" => "2",

                    "TYPE" => "7",

                    "NUMBER" => "~",

                    "CANCELLED" => 0,

                    "DATE" => $shipment_date,

                    //"TIME" => time() - strtotime(date('Y-m-d')), #mysql time logo'da hatalı oluyor

                    "DOC_DATE" => date('Y-m-d', strtotime($order_info['date_added'])),

                    "DOC_TRACK_NR" => $order_id,

                    "AUXIL_CODE" => $special_code,

                    "ARP_CODE" => $customer_code,

                    "TRANSACTIONS" => [

                        "items" =>  $logo_order_products                    

                    ]                      

                ];

                # Ekstra İndirim varsa GENELE eklenmesi

                if($order_totals['extra_discount']>0) {

                    $sale_invoice_data['ADD_DISCOUNTS'] = $order_totals['extra_discount'];

                }



                $logo_sale_invoice = $logo->postLogo('/api/v1/salesInvoices', json_encode($sale_invoice_data));



                $error_keys = ['DBError', 'ServerError','ValError0','OtherError'];

                foreach($error_keys as $key) {

                    if(!empty($logo_sale_invoice['ModelState'][$key])) {

                        $error = $logo_sale_invoice['ModelState'][$key];



                        $log = new Log("logo/failed_orders.log");

                        $log->write("Order #". $order_id .": " . json_encode($error, JSON_UNESCAPED_UNICODE));

    

                        $message = "Sipariş aktarılamadı. " . json_encode($error, JSON_UNESCAPED_UNICODE);

                        $this->model_module_logo->updateOrderLogoMessage($order_id, $message);

                        if($manually = true) {

                            return $message;

                        } else {

                            exit;

                        }

                    }

                }



                $order_logo_data = [

                    'INTERNAL_REFERENCE' => $logo_sale_invoice['INTERNAL_REFERENCE'],

                    'ARP_CODE' => $customer_code

                ];

                      

                !empty($logo_sale_invoice['INTERNAL_REFERENCE']) and $this->model_module_logo->updateOrderLogoReference($order_id, $order_logo_data);

            }

        } # Sipariş iptalinin Logo'ya aktarılması

        else if($order_status_id==7 && !empty($order_id)) {

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

            $order_info = $this->model_module_logo->getOrder($order_id);

            if(!empty($order_info['logo_reference'])) {

                $logo = new Logo;

                $data = $logo->getLogo('/api/v1/salesInvoices/'.$order_info['logo_reference'].'?expandLevel=full');

                $data['CANCELLED'] = 1;

                $put = $logo->putLogo('/api/v1/salesInvoices/'.$order_info['logo_reference'], $data);

                $this->model_module_logo->updateOrderLogoCancelStatus($order_id,1);

            }

        } # Sipariş iptalinin geriye alınması

        else if($order_status_id==9 && !empty($order_id)) {

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

            $order_info = $this->model_module_logo->getOrder($order_id);

            if(!empty($order_info['logo_reference'])) {

                $logo = new Logo;

                $data = $logo->getLogo('/api/v1/salesInvoices/'.$order_info['logo_reference'].'?expandLevel=full');

                $data['CANCELLED'] = 0;

                $put = $logo->putLogo('/api/v1/salesInvoices/'.$order_info['logo_reference'], $data);

                $this->model_module_logo->updateOrderLogoCancelStatus($order_id, NULL);

            }

        }

    }



    public function send_manually() {
exit;

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

        $output = [ $this->request->post['order_id'], NULL ];

        $send = $this->send(NULL, $output, true);

        $order_info = $this->model_module_logo->getOrder($this->request->post['order_id']);

        

        $msg = empty($send) ? 'Sipariş aktarıldı.' : $send;

        $status = empty($send) ? 'success' : 'failed';



        $json = array(

            'status' => $status,

            'message' => $msg

        );

    

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

        $this->response->setOutput(json_encode($json));

    }



    public function get_unreferenced_materials() {

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

        $materials = $this->model_module_logo->getUnReferencedMaterials();

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

        $this->response->setOutput(json_encode($materials));

    }

    /**

     * Materyali Logo'ya göndermek için kullanılır

     */

        public function send_materials() {

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

            $logo = new Logo;



            $materials = $this->model_module_logo->getUnReferencedMaterials();



            $success_materials=[];

            $failed_materials=[];

            foreach($materials as $material) {



                $name_part1 = substr($material['name'], 0, 50);

                $name_part2 =  substr($material['name'], 50);



                $material_data = [

                    "INTERNAL_REFERENCE" => "0",

                    "CARD_TYPE" => "1",

                    "CODE" => $material['barcode'],

                    "NAME" => $name_part1,

                    "NAME3" => $name_part2,

                    "USEF_PURCHASING" => 1,

                    "USEF_MM" => 1,

                    "VAT" => "20.0",

                    "AUTOINCSL" => "1",

                    "LOTS_DIVISIBLE" => "1",

                    "UNITSET_CODE" => "05",

                    "SELVAT" => "20.0",

                    "RETURNVAT" => "20.0",

                    "SELPRVAT" => "20.0",

                    "RETURNPRVAT" => "20.0",

                    "DIST_LOT_UNITS" => 1,

                    "COMB_LOT_UNITS" => 1

                ];

                $post_material = $logo->postLogo('/api/v1/items', json_encode($material_data)); 



                if(!empty($post_material['INTERNAL_REFERENCE']) && !empty($post_material['CODE'])) {

                    $success_materials[] = $material['name'];



                    $post_material_data = [

                        "INTERNAL_REFERENCE" => $post_material['INTERNAL_REFERENCE'],

                        "CODE" => $post_material['CODE']

                    ];

                    $this->model_module_logo->saveMaterial($material['product_stock_id'], $post_material_data);

                } else {

                    $failed_materials[] = $material['name'];

                    if(!empty($post_material['ModelState']['DBError']) || !empty($post_material['ModelState']['ServerError'])) {

                        $error = !empty($post_material['ModelState']['DBError']) ? $post_material['ModelState']['DBError'] : $post_material['ModelState']['ServerError'];

                        $log = new Log("logo/failed_materials.log");

                        $log->write("Material (product_stock_id) #". $material['product_stock_id'] .": " . json_encode($error));

                    }

                }

            }

            $json = array(

                'success_materials' => $success_materials,

                'failed_materials' => $failed_materials,

                'message' => 'Aktarım tamamlandı.'

            );

        

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

            $this->response->setOutput(json_encode($json));

        }

    public function getMaterials() {

        $logo = new Logo;

        $data = $logo->getLogo('/api/v1/items/1863');

        echo '<pre>';

        print_r($data);

    }



    # Materyal isimleri tek satıra sığmıyordu artan kısım 2.satıra eklendi

    public function setMaterialNames() {



        # oluşturulan dosyanın içine 0 yazılır. timeout'a düşmeden sistem materyalleri gezer.

        $count = DIR_SYSTEM . '/storage/logo_count.txt';

        $number = (int)file_get_contents($count);



        $materials = $this->db->query("

            SELECT name,

            logo_reference,

            CHAR_LENGTH(name)

            FROM ps_product_stock 

            WHERE CHAR_LENGTH(name)>50

            LIMIT " . $number . ", 10"

        )->rows;



        if($materials) {

            foreach($materials as $material) {

                $logo = new Logo;

                $data = $logo->getLogo('/api/v1/items/'.$material['logo_reference']);



                $data = [];



                $data['NAME'] = substr($material['name'], 0, 50);

                $data['NAME3'] = substr($material['name'], 50);



                $put_material = $logo->patchLogo('/api/v1/items/'.$material['logo_reference'], $data); 

            }

            file_put_contents($count, $number+10);



            header("Refresh:0");           

        }



    }

}

?>