<?php

class ControllerTooljsonResponse extends Controller{    
    
    public function getProductJson()
    {
        if(!isset($this->request->get['secret_key'])){
            die();
        }else {
            if($this->request->get['secret_key'] != '723bc10a6576351257dea2e18ece21311a3182b0'){
                die();
            }
        }

        //https://www.deercase.com/index.php?route=tool/jsonResponse/getProductJson&&secret_key=723bc10a6576351257dea2e18ece21311a3182b0

        $json = '[';

        $products = $this->db->query("SELECT * FROM ps_product LIMIT 4051,1 ")->rows;

        foreach($products as $product){ 

        //echo "<pre>";  var_dump($product); echo "</pre>"; die();

        $productDescription = $this->db->query("SELECT * FROM ps_product_description WHERE product_id = ". $product['product_id'] ." ")->row;
        $productImages = $this->db->query("SELECT * FROM ps_product_image WHERE product_id = ". $product['product_id'] ." ")->rows;
        $productSpecials = $this->db->query("SELECT * FROM ps_product_special WHERE product_id = ". $product['product_id'] ." ")->rows;
        $productToCategories = $this->db->query("SELECT * FROM ps_product_to_category WHERE product_id = ". $product['product_id'] ." ")->rows;
        $productAttributes = $this->db->query("SELECT * FROM ps_product_attribute WHERE product_id = ". $product['product_id'] ." ")->rows;
        $productFilters = $this->db->query("SELECT * FROM ps_product_filter WHERE product_id = ". $product['product_id'] ." ")->rows;
        
       // echo "<pre>";  var_dump($productDescription); echo "</pre>"; die();
       // echo "<pre>";  var_dump($productImages); echo "</pre>"; die();
        //echo "<pre>";  var_dump($productSpecials); echo "</pre>"; die();
        //echo "<pre>";  var_dump($productToCategories); echo "</pre>"; die();

        $productDescriptionJson = '{
            "productId": '. $productDescription['product_id'] .',
            "languageId": '. $productDescription['language_id'] .',
            "name": "'. $productDescription['name'] .'",
            "description": '. json_encode($productDescription['description']) .',
            "tag": "'. $productDescription['tag'] .'",
            "metaTitle": "'. $productDescription['meta_title'] .'",
            "metaDescription": "'. $productDescription['meta_description'] .'",
            "metaKeyword": "'. $productDescription['meta_keyword'] .'"
        }';

        $productImageJson = '';
        foreach($productImages as $image){
            $productImageJson .= '{
                "productId": '. $product['product_id'] .',
                "image": "'. $image['image'] .'",
                "sortOrder": '. $image['sort_order'] .'
            },';
        }
        $productImageJson = rtrim($productImageJson, ',');

        $productToCategoryJson = '';
        foreach($productToCategories as $category){
            $productToCategoryJson .= '{
                "productId": '. $category['product_id'] .',
                "categoryId": '. $category['category_id'] .'
            },';
        }
        $productToCategoryJson = rtrim($productToCategoryJson, ',');

        //ProductOptions
        $productOptionJson = '';
        $productOptions = $this->db->query("SELECT * FROM ps_product_option WHERE product_id = ". $product['product_id'] ." ")->rows;
        foreach($productOptions as $option){
            
            $productOptionValuesJson = '';
            $productOptionValues = $this->db->query("SELECT * FROM ps_product_option_value WHERE product_id = ". $product['product_id'] ." ")->rows;
            foreach($productOptionValues as $value){
                $productOptionValuesJson .= '{
                    "quantity": '. $value['quantity'] .',
                    "subtract": '. $value['subtract'] .',
                    "price": '. $value['price'] .',
                    "pricePrefix": "'. $value['price_prefix'] .'",
                    "points": '. $value['points'] .',
                    "pointsPrefix": "'. $value['points_prefix'] .'",
                    "weight": '. $value['weight'] .',
                    "weightPrefix": "'. $value['weight_prefix'] .'",
                    "customerGroupId": '. $value['customer_group_id'] .',
                    "optionValueBarcode": "'. $value['option_value_barcode'] .'"
                },';
            }
            $productOptionValuesJson = rtrim($productOptionValuesJson, ',');

            $productOptionJson = '{
                "productId": '. $product['product_id'] .',
                "optionId": '. $option['option_id'] .',
                "value": "'. $option['value'] .'",
                "required": '. $option['required'] .',
                "values": ['. $productOptionValuesJson .']
            },';
        }
        $productOptionJson = rtrim($productOptionJson, ',');
        //ProductOptions

        $productAttributeJson = '';
        foreach($productAttributes as $attibute){
            $productAttributeJson .= '{
                "productId": '. $product['product_id'] .',
                "attributeId": '. $attibute['attribute_id'] .',
                "languageId": '. $attibute['language_id'] .',
                "text": "'. $attibute['text'] .'"
            },';
        }
        $productAttributeJson = rtrim($productAttributeJson, ',');

        $productFilterJson = '';
        foreach($productFilters as $filter){
            $productFilterJson .= '{
                "productId": '. $product['product_id'] .',
                "filterId": '. $filter['filter_id'] .'
            },';
        }
        $productFilterJson = rtrim($productFilterJson, ',');


        $json .= '{
            "productId": '. $product['product_id'] .',
            "productStockId": '. $product['product_stock_id'] .',
            "model": "'.$product['model'].'",
            "model2": "'.$product['model2'].'",
            "slug": "'. $productDescription['href'] .'",
            "barcode": "'.$product['barcode'].'",
            "productType": "'.$product['product_type'].'",
            "productShowCase": "'.$product['product_showcase'].'",
            "productShipping": "'.$product['product_shipping'].'",
            "productPayment": "'.$product['product_payment'].'",
            "quantity": "'.$product['quantity'].'",
            "stockStatusId": "'.$product['stock_status_id'].'",
            "image": "'.$product['image'].'",
            "imageVitrin": "'.$product['image_vitrin'].'",
            "media": "'.$product['media'].'",
            "pattern": "'.$product['pattern'].'",
            "patternNames": "'.$product['pattern_names'].'",
            "coverNames": "'.$product['cover_names'].'",
            "mask": "'.$product['mask'].'",
            "manufacturerId": "'.$product['manufacturer_id'].'",
            "shipping": "'.$product['shipping'].'",
            "price": "'.$product['price'].'",
            "costPrice": "'.$product['cost_price'].'",
            "currencyId": "'.$product['currency_id'].'",
            "points": "'.$product['points'].'",
            "dateAvailable": "'.$product['date_available'].'",
            "weight": "'.$product['weight'].'",
            "length": "'.$product['length'].'",
            "width": "'.$product['width'].'",
            "height": "'.$product['height'].'",
            "subtract": "'.$product['subtract'].'",
            "minimum": "'.$product['minimum'].'",
            "sortOrder": "'.$product['sort_order'].'",
            "lidyana": "'.$product['lidyana'].'",
            "dr": "'.$product['dr'].'",
            "status": '. ($product['status'] ? 'true' : 'false') .',
            "viewed": "'.$product['viewed'].'",
            "facebookFeedStatus": '. ($product['fb_feed_status'] ? 'true' : 'false' ) .',
            "idleStock": '. ($product['idle_stock'] ? 'true' : 'false' ) .',
            "productDescription": ['. $productDescriptionJson .'],
            "productImage": ['. $productImageJson .'],
            "productSpecial": [],
            "productToCategory": ['. $productToCategoryJson .'],
            "productOption": ['. $productOptionJson .'],
            "productAttribute": ['. $productAttributeJson .'],
            "productFilter": ['. $productFilterJson .']
        },';
        }
        $json = rtrim($json, ',');
        $json .= ']';
        

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

       


    }

    public function getCustomerJson()
    {

        if(!isset($this->request->get['secret_key'])){
            die();
        }else {
            if($this->request->get['secret_key'] != '723bc10a6576351257dea2e18ece21311a3182b0'){
                die();
            }
        }

       //https://www.deercase.com/index.php?route=tool/jsonResponse/getCustomerJson&secret_key=723bc10a6576351257dea2e18ece21311a3182b0

       $customers = $this->db->query("SELECT * FROM ps_customer LIMIT 1 ")->rows;

       $json = '[';



       foreach($customers as $customer){ 

        $addresses = $this->db->query("SELECT * FROM ps_address WHERE customer_id = ". $customer['customer_id'] ." ")->rows;
        $customerAddressJson = '';
        foreach($addresses as $address){
            $customerAddressJson .= '{
                "addressId": '. $address['address_id'] .',
                "customerId": '. $customer['customer_id'] .',
                "firstname": "'. $address['firstname'] .'",
                "lastname": "'. $address['lastname'] .'",
                "companyInfo": {
                    "company": "'. str_replace('"','',$address['company']) .'",
                    "taxNo": "'. str_replace('"','',$address['company_taxno']) .'",
                    "taxAdmin": "'. str_replace('"','',$address['company_taxadmin']) .'"
                },
                "address1": "'. $address['address_1'] .'",
                "address2": "'. $address['address_2'] .'",
                "city": "'. $address['city'] .'",
                "postCode": "'. $address['postcode'] .'",
                "countryId": '. $address['country_id'] .',
                "zoneId": '. $address['zone_id'] .'
            },';
        }

        $customerAddressJson = rtrim($customerAddressJson, ',');

        $json .= '{
            "customerId": '. $customer['customer_id'] .',
            "customerGroupId": '. $customer['customer_group_id'] .',
            "firstname": "'. $customer['firstname'] .'",
            "lastname": "'. $customer['lastname'] .'",
            "email": "'. $customer['email'] .'",
            "telephone": "'. $customer['telephone'] .'",
            "profilePicture": "'. $customer['profile_picture'] .'",
            "password": "'. $customer['password'] .'",
            "tc": "'. $customer['tc'] .'",
            "cart": "'. $customer['cart'] .'",
            "wishList": "'. $customer['wishlist'] .'",
            "newsletter": '. ($customer['newsletter'] ? 'true' : 'false' ) .',
            "addresses": ['. $customerAddressJson .'],
            "status": '. ($customer['status'] ? 'true' : 'false' ) .',
            "approved": '. ($customer['approved'] ? 'true' : 'false' ) .',
            "safe": '. ($customer['safe'] ? 'true' : 'false' ) .',
            "code": "'. $customer['code'] .'",
            "token": "'. $customer['token'] .'",
            "logoReference": "'. $customer['logo_reference'] .'",
            "logoCode": "'. $customer['logo_code'] .'"
        },';

       }

        $json = rtrim($json, ',');
        $json .= ']';
        

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



    }

    public function catCacheControl()
    {
        //https://www.deercase.com/index.php?route=tool/jsonResponse/catCacheControl

       // die();

        $this->createCache();

    }

    public function getSubCategory($parent_id = 0, $language_id){

        flush();

        echo "bitti <br>";
        
        return $this->db->query("SELECT * FROM ps_category c 
            LEFT JOIN ps_category_description cd ON (c.category_id = cd.category_id) 
            WHERE c.parent_id = '" . (int)$parent_id . "' AND 
            cd.language_id = 1
            AND c.status = 1 ORDER BY c.sort_order, c.date_added DESC ")->rows;

    }


    private function createCache(){

        $this->load->model('tool/image');
        $this->load->model('catalog/product');
        $this->load->model('localisation/language');

        $categories = array();

        if ($this->request->server['HTTPS']) {
			$config_url = $this->config->get('config_ssl') . 'image/';
		} else {
			$config_url = $this->config->get('config_url') . 'image/';
		}

        $languages = $this->model_localisation_language->getLanguages();

        foreach ($languages as $l_key => $language){
            $categories = array();
            if($language['status']) {
                foreach ($this->getSubCategory(0, $language['language_id']) as $key1 => $c_data) {
                    if ($c_data['top']) {
                        $category2 = array();
                        $categories2_data = $this->getSubCategory($c_data['category_id'], $language['language_id']);
                        foreach ($categories2_data as $key2 => $c2_data) {
                            if ($c2_data['top']) {
                                // $category3 = array();
                                // $categories3_data = $this->getSubCategory($c2_data['category_id'], $language['language_id']);
                                // foreach ($categories3_data as $key3 => $c3_data) {
                                //     if ($c3_data['top']) {
                                        
                                //         $category3[] = array(
                                //             'name' => $c3_data['name'],
                                //             'href' => $c3_data['href'],
                                //             'category_id' => $c3_data['category_id'],
                                //             'image' => '',
                                //             'children' => [],
                                //             'top' => 1,
                                //             'column' => $c3_data['column'] ? $c3_data['column'] : 1,
                                //             'count' => '',
                                //         );
                                //     }
                                // }
                                $category2[] = array(
                                    'name' => $c2_data['name'],
                                    'href' => $c2_data['href'],
                                    'category_id' => $c2_data['category_id'],
                                    'image' => '',
                                    'top' => 1,
                                    'children' => [],
                                    'column' => $c2_data['column'] ? $c2_data['column'] : 1,
                                );
                            }
                        }
                        $categories[] = array(
                            'name' => $c_data['name'],
                            'href' => $c_data['href'],
                            'category_id' => $c_data['category_id'],
                            'image' => '',
                            'no_cache_image' => $c_data['image'] ? $config_url . $c_data['image'] : '',
                            'children' => $category2,
                            'top' => 1,
                            'column' => $c_data['column'] ? $c_data['column'] : 1,
                        );
                        $this->cache->cache_set($l_key . '-test', $categories, 'category/');
                    }
                }
            }
        }


        return $this->cache->cache_get($this->session->data['language']. '-test', 'category/');

        // BİLAL 26/02/2019


    }

    public function getOrderJson()
    {

        if(!isset($this->request->get['secret_key'])){
            die();
        }else {
            if($this->request->get['secret_key'] != '723bc10a6576351257dea2e18ece21311a3182b0'){
                die();
            }
        }

       
        //https://www.deercase.com/index.php?route=tool/jsonResponse/getOrderJson&secret_key=723bc10a6576351257dea2e18ece21311a3182b0
 
        $orders = $this->db->query("SELECT * FROM ps_order LIMIT 500, 1 ")->rows;
        //$orders = $this->db->query("SELECT * FROM ps_order WHERE order_id = 541")->rows;
 
        $json = '[';

        foreach($orders as $order) {

            $order_histories = $this->db->query("SELECT * FROM ps_order_history WHERE order_id = '". $order['order_id'] ."' ")->rows;
            $orderHistoryJson = '';
            foreach($order_histories as $history){
                $orderHistoryJson .= '{
                    "orderId": '. $order['order_id'] .',
                    "orderStatusId": '. $history['order_status_id'] .',
                    "notify": '. ($history['notify'] ? 'true' : 'false' ) .',
                    "comment": "'. trim($history['comment']) .'"
                },';
            }
            
            $orderHistoryJson = rtrim($orderHistoryJson, ',');

            $order_options = $this->db->query("SELECT * FROM ps_order_option WHERE order_id = '". $order['order_id'] ."' ")->rows;
            $orderOptionJson = '';
            foreach($order_options as $option){
                $orderOptionJson .= '{
                    "orderId": '. $order['order_id'] .',
                    "productOptionId": '. $option['product_option_id'] .',
                    "productOptionValueId": '. $option['product_pption_value_id'] .',
                    "name": "'. $option['name'] .'",
                    "value": "'. $option['value'] .'",
                    "type": '. $option['type'] .'
                },';
            }
            
            $orderOptionJson = rtrim($orderOptionJson, ',');

            $order_products = $this->db->query("SELECT * FROM ps_order_product WHERE order_id = '". $order['order_id'] ."' ")->rows;
            $orderProductJson = '';
            foreach($order_products as $product){

                $orderProductJson .= '{
                    "orderId": '. $order['order_id'] .',
                    "productId": '. $product['product_id'] .',
                    "name": "'. $product['name'] .'",
                    "model": "'. $product['model'] .'",
                    "quantity": '. $product['quantity'] .',
                    "caseOrderImage": "'. $product['case_order_image'] .'",
                    "customerPatternData": '. ($product['customer_pattern_data'] ? $product['customer_pattern_data'] : '""') .',
                    "p11PatternImage": "'. $product['p_11_pattern_img'] .'",
                    "adminPatternImage": "'. $product['admin_pattern_image'] .'",
                    "adminGradientPatternImage": "'. $product['admin_gradient_pattern_image'] .'",
                    "customCaseImage": "'. $product['customcase_image'] .'",
                    "price": '. $product['price'] .',
                    "costPrice": '. $product['cost_price'] .',
                    "total": '. $product['total'] .',
                    "tax": '. $product['tax'] .',
                    "reward": '. $product['reward'] .',
                    "status": '. ($product['status'] ? 'true' : 'false') .',
                    "roomNo": '. $product['room_no'] .',
                    "reprint": '. $product['reprint'] .',
                    "reprintDownloadCount": '. $product['reprint_download_count'] .',
                    "productGeneratedStatus": '. $product['product_generated_status'] .',
                    "returnStatus": '. $product['return_status'] .',
                    "reprintReasonId": '. $product['reprint_reason_id'] .',
                    "showIdleStock": '. ($product['show_idle_stock'] ? 'true' : 'false') .',
                    "logoReturnInfo": "'. $product['logo_return_info'] .'",
                    "baskiStatus": '. $product['baski_status'] .'
                },';
            }
            $orderProductJson = rtrim($orderProductJson, ',');

            $order_totals = $this->db->query("SELECT * FROM ps_order_total WHERE order_id = '". $order['order_id'] ."' ")->rows;
            $orderTotalJson = '';
            foreach($order_totals as $total){
                $orderTotalJson .= '{
                    "orderId": '. $order['order_id'] .',
                    "code": "'. $total['code'] .'",
                    "title": "'. $total['title'] .'",
                    "value": '. $total['value'] .',
                    "sortOrder": '. $total['sort_order'] .'
                },';
            }
            
            $orderTotalJson = rtrim($orderTotalJson, ',');
        
            $order['payment_address_1'] = str_replace('\\', '/', $order['payment_address_1']);
            $order['shipping_address_1'] = str_replace('\\', '/', $order['shipping_address_1']);

            $json .= '{
                "orderId": '. $order['order_id'] .',
                "invoiceNo": '. $order['invoice_no'] .',
                "invoicePrefix": "'. $order['invoice_prefix'] .'",
                "customerId": '. $order['customer_id'] .',
                "firstname": "'. $order['firstname'] .'",
                "lastname": "'. $order['lastname'] .'",
                "email": "'. $order['email'] .'",
                "tc": "'. $order['tc'] .'",
                "telephone": "'. $order['telephone'] .'",
                "paymentFirstname": "'. $order['payment_firstname'] .'",
                "paymentLastname": "'. $order['payment_lastname'] .'",
                "paymentCompany": "'. $order['payment_company'] .'",
                "paymentCompanyTaxno": "'. $order['payment_company_taxno'] .'",
                "paymentCompanyTaxadmin": "'. $order['payment_company_taxadmin'] .'",
                "paymentAddress1": "'. $order['payment_address_1'] .'",
                "paymentAddress2": "'. $order['payment_address_2'] .'",
                "paymentCity": "'. $order['payment_city'] .'",
                "paymentPostcode": "'. $order['payment_postcode'] .'",
                "paymentCountry": "'. $order['payment_country'] .'",
                "paymentCountryId": '. $order['payment_country_id'] .',
                "paymentZone": "'. $order['payment_zone'] .'",
                "paymentZoneId": '. $order['payment_zone_id'] .',
                "paymentMethod": "'. $order['payment_method'] .'",
                "paymentCode": "'. $order['payment_code'] .'",
                "shippingFirstname": "'. $order['shipping_firstname'] .'",
                "shippingLastname": "'. $order['shipping_lastname'] .'",
                "shippingAddress1": "'. $order['shipping_address_1'] .'",
                "shippingAddress2": "'. $order['shipping_address_2'] .'",
                "shippingCity": "'. $order['shipping_city'] .'",
                "shippingPostcode": "'. $order['shipping_postcode'] .'",
                "shippingCountry": "'. $order['shipping_country'] .'",
                "shippingCountryId": '. $order['shipping_country_id'] .',
                "shippingZone": "'. $order['shipping_zone'] .'",
                "shippingZoneId": '. $order['shipping_zone_id'] .',
                "shippingMethod": "'. $order['shipping_method'] .'",
                "shippingCode": "'. $order['shipping_code'] .'",
                "comment": "'. str_replace('\\n', '', $this->db->escape($order['comment'])) .'",
                "total": '. $order['total'] .',
                "orderStatusId": '. $order['order_status_id'] .',
                "affiliateId": '. $order['affiliate_id'] .',
                "commission": '. $order['commission'] .',
                "marketingId": '. $order['marketing_id'] .',
                "tracking": "'. $order['tracking'] .'",
                "currencyId": '. $order['currency_id'] .',
                "currencyCode": "'. $order['currency_code'] .'",
                "currencyValue": "'. $order['currency_value'] .'",
                "ip": "'. $order['ip'] .'",
                "forwardedIp": "'. $order['forwarded_ip'] .'",
                "userAgent": "'. $order['user_agent'] .'",
                "acceptLanguage": "'. $order['accept_language'] .'",
                "status": '. ($order['status'] ? 'true' : 'false') .',
                "rowColorCode": "'. $order['row_color_code'] .'",
                "preparedOrderStatus": '. ($order['prepared_order_status'] ? 'true' : 'false') .',
                "userId": "'. $order['user_id'] .'",
                "campaign": "'. $order['campaign'] .'",
                "logoReference": "'. $order['logo_reference'] .'",
                "logoMessage": "'. $order['logo_message'] .'",
                "logoIsCancelled": "'. $order['logo_is_cancelled'] .'",
                "logoCustomerCode": "'. $order['logo_customer_code'] .'",
                "orderHistory": ['. $orderHistoryJson .'],
                "orderOption": ['. $orderOptionJson .'],
                "orderProduct": ['. $orderProductJson .'],
                "orderTotal": ['. $orderTotalJson .']
            },';
        }


        $json = rtrim($json, ',');
        $json .= ']';
        

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



    }


}