<?php

include "system/library/logo.php";



class ControllerToolLogoTransfer extends Controller {



    public function index() {

        if($_SERVER["REMOTE_ADDR"]!==$_SERVER['SERVER_ADDR']) { 
            echo 'Bu URL adresine erişim izniniz yoktur.';
            die();
        }

	

        @ini_set("max_execution_time", "0"); 

        set_time_limit(0);



        $orders = $this->db->query("SELECT DISTINCT o.*, oh.order_status_id 

            FROM ps_order o

            LEFT JOIN ps_order_history oh ON o.order_id = oh.order_id 

            WHERE

            o.logo_reference IS NULL 

            AND o.logo_message IS NULL 

            AND oh.order_status_id IN (5,17)

            AND oh.date_added BETWEEN NOW() - INTERVAL 2 WEEK 

            AND NOW() - INTERVAL 5 MINUTE 

            ORDER BY oh.date_added 

            LIMIT 3")->rows;



echo '<pre>';
print_r($orders);
        $minutes = intval(date('i'));



        if($minutes % 30 == 0) {

            $failed_orders = $this->db->query("SELECT DISTINCT o.*, oh.order_status_id 

                FROM ps_order o

                LEFT JOIN ps_order_history oh ON o.order_id = oh.order_id 

                WHERE o.logo_message IS NOT NULL 

                    AND oh.order_status_id IN (5,17) 

                    AND oh.date_added BETWEEN NOW() - INTERVAL 2 WEEK 

                    AND NOW() - INTERVAL 5 MINUTE 

                ORDER BY RAND() 

                LIMIT 1")->rows;



            $orders = array_merge($orders, $failed_orders);            

        }



        if(count($orders)>0) {

            foreach($orders as $key => $order) {

                $data = [$order['order_id'],'17'];

                print_r($order['order_id'] . PHP_EOL);

                //echo $order['order_id'] . '<br/>';

                $this->sendOrder(NULL, $data, true);

            }

        }

    }



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

        $order_id = $output[0];

        $order_status_id = $output[1];



        # 17: Kargoya teslim edildi.

        //if( (!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']); 



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

                        SELECT op.*, ovd.`name` AS option_value_name, ovd.option_value_id 

                        FROM ps_order_product AS op

                        LEFT JOIN ps_order_option AS opt ON op.order_product_id = opt.order_product_id

                        LEFT JOIN ps_product_option_value AS pov ON opt.product_option_value_id = pov.product_option_value_id

                        LEFT JOIN ps_option_value_description AS ovd ON pov.option_value_id = ovd.option_value_id 

                        WHERE op.order_product_id = ". $order_products[$i]['order_product_id']

                    )->row;



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

                    $true_product_stock_id = $this->createProductMaterialIfNotExists($order_product_info['product_id'], $order_product_info['option_value_id'], $order_product_info['option_value_name']);



                    if(isset($true_product_stock_id['status']) && $true_product_stock_id['status'] == false) {

                        $message =  $true_product_stock_id['message'] . ' Ürün:' . $order_product_info['product_id'] . '<br/>';



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

                        if($manually = true) {

                            echo $message . "<br>";

                            return $message;

                        } else {

                            return;

                        }

                    }

                    $order_products[$i] += $order_product_info;

                    $order_products[$i]['product_stock_id'] = $true_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_products[$i]['product_stock_id'])) {

                        //$material = $this->model_module_logo->getMaterial($order_products[$i]['product_stock_id']);



                        $material = $this->db->query("SELECT ps_product_stock.* 

                            FROM ps_product_stock

                            WHERE barcode = '"  . $order_products[$i]['product_stock_id'] . "'"

                        )->row;

                        if(empty($material['logo_code'])) {

      

                            if(empty($material)) {

                                return;

                            }

                            $post_material = $this->sendMaterialToLogo($material);



                            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_products[$i]['product_stock_id'], $material_data);



                            } else {



                                $error_keys = ['LoginError', '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.";

                                        echo $message . "<br>";



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

                                        if($manually = true) {

                                            return $message;

                                        } else {

                                            break;

                                        }



                                    }



                                }

                            }

                        }  

                    }

                }



                # 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) {

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

                        $logo_customer = $this->createCustomer($customer_info, $order_info, $address, $city, $zone, $country);

                    } else {

                        $logo_customer = $this->createCustomerAsCommercial($customer_info, $order_info, $address, $city, $zone, $country);

                    }

                    

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

                    if(empty($logo_customer['CODE']) || !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 = $product['product_stock_id'];

                    

                    $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",

                        "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",

                        "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,

                    "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));

                print_r($logo_sale_invoice);

                $error_keys = ['LoginError', '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);

            }

        //}

    }



    /**

     * Logo'da Kurumsal müşteri oluşturur

     */

    private function createCustomerAsCommercial($customer_info, $order_info, $address, $city, $zone, $country) {

        $logo = new Logo;



        $customer_logo_data = [

            "INTERNAL_REFERENCE" => "0",

            "ACCOUNT_TYPE" => "3",

            "CODE" => isset($customer_info['customer_id']) ? $customer_info['customer_id'] : "MSFR".$order_info['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" => $order_info['payment_company'],

            "ADDRESS1" => $address,

            "TOWN" => $city,

            "CITY" => $zone,

            "COUNTRY" => $country,

            'E_MAIL' => $customer_info['email'],

            "TAX_ID" => !empty($order_info['payment_company_taxno']) ? $order_info['payment_company_taxno'] : "",

            "TAX_OFFICE" => !empty($order_info['payment_company_taxadmin']) ? $order_info['payment_company_taxadmin'] : "",

            "PURCHBRWS" => "1",

            "SALESBRWS" => "1",

            "IMPBRWS" => "1",

            "EXPBRWS" => "1",

            "FINBRWS" => "1",

        ];

    

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

    }



    /**

     * Logo'da müşteri oluşturur

     */

    private function createCustomer($customer_info, $order_info, $address, $city, $zone, $country) {

        $logo = new Logo;



        $customer_logo_data = [

            "INTERNAL_REFERENCE" => "0",

            "ACCOUNT_TYPE" => "3",

            "CODE" => isset($customer_info['customer_id']) ? $customer_info['customer_id'] : "MSFR".$order_info['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

        ]; 



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

    }



    public function createProductMaterialIfNotExists($product_id, $option_value_id = '', $option_value_name = '') {

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

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

        # varsa materyali kullan. 

        # yoksa üret 



        $category = $this->db->query("SELECT

            c.category_id,

            cd.`name`, 

            c.infinityeditid

        FROM

            ps_product_to_category AS ptc

            INNER JOIN ps_category AS c ON ptc.category_id = c.category_id

            INNER JOIN ps_category_description AS cd ON c.category_id = cd.category_id 

        WHERE

            ptc.product_id = {$product_id}   

            AND c.is_logo_material = 1

        ")->rows;



        foreach($category as $item) {

            if($item['category_id'] == '8541') {

                return '0000000001';

            }

        }



        if(count($category)!==1) {

            return [

                "status"=> false,

                "message" => "Logo için kategori sayısı uygun değil."

            ];

        }



        $category = $category[0];



        $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 = '" . $product_id ."'

        ")->row;



        if(empty($color)) {

            return [

                "status"=> false,

                "message" => "Renk bilgisi yok."

            ];

        }



        $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 = '" . $product_id ."'

        ")->row;



        if(empty($collection)) {

            return [

                "status"=> false,

                "message" => "Koleksiyon bilgisi yok."

            ];

        }



        # Saat kordonlarında barkoda bedeni de ekler

        if($category['category_id'] == 4762 || $category['category_id'] == 4894) {

            $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 . $option_value_id;

        } else {

            $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;

        }

        $logo = new Logo;

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



        //$barcode_query = $logo->getLogo("/api/v1/queries?tsql=SELECT%20TOP%201%20LOGICALREF,CODE,NAME%20FROM%20LG_".FIRMNO."_ITEMS%20WHERE%20CODE='".$barcode."'");

        if(empty($barcode_query)) {

            if($category['category_id'] == 4762 || $category['category_id'] == 4894) {

                $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.



                if($category_name == $collection['name']) {

                    $material_name = $category_name . ' ' . $short_color_name . ' ' . $option_value_name;

                } else {

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

                }

                $material_name = preg_replace('/\s+/', ' ', $material_name); 

            } else {

                $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.

            

                if($category_name == $collection['name']) {

                    $material_name = $category_name . ' ' . $short_color_name;

                } else {

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

                }

                $material_name = str_replace("  "," ", $material_name); 

            }



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

                SET product_stock_id = '" . $barcode . "', 

                    barcode = '" . $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($product_id, $barcode, $barcode);

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

        }



        return $barcode;

    }



    public function sendMaterialToLogo($material) {

        $logo = new Logo;

        $name_part1 = $material['name'];

        $name_part2 = "";

        if(strlen($material['name'])>50) {

            $name_part1 = mb_substr($material['name'], 0, 49, 'UTF-8');

            $name_part2 = mb_substr($material['name'], 49, null, 'UTF-8');            

        }

        if(empty($name_part1)) {

            $name_part1 = $material['name'];

        }



        $material_data = [

            "INTERNAL_REFERENCE" => "0",

            "CARD_TYPE" => "1",

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

            "GROUP_CODE" => $material['collection_name'],

            "NAME" => $name_part1,

            "NAME3" => $name_part2,

            "USEF_PURCHASING" => 1,

            "USEF_MM" => 1,

            "USEF_SALES" => 1,

            "VAT" => "20.0",

            "AUTOINCSL" => "1",

            "LOTS_DIVISIBLE" => "1",

            "UNITSET_CODE" => "05",

            "SELVAT" => "20.0",

            "RETURNVAT" => "20.0",

            "SELPRVAT" => "20.0",

            "RETURNPRVAT" => "20.0"

        ];

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

    }



    public function send_material() {

        if(isset($this->request->post['product_stock_id'])) {

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



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

            $logo = new Logo;



            $material = $this->db->query("SELECT ps_product_stock.* 

                FROM ps_product_stock

                WHERE barcode = '"  . $product_stock_id . "'"

            )->row;

            if(empty($material['logo_code'])) {      

                $material = $this->model_module_logo->getMaterial($product_stock_id);



                $post_material = $this->sendMaterialToLogo($material);



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

                    $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 {

                    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(

                    'status' => 'success',

                );

            } else {

                $json = array(

                    'status' => 'success',

                );

            }

        } else {

            $json = array(

                'status' => 'failed',

            );

        }



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

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

    }



}



?>