<?php
class ControllerToolProductBot extends Controller{

    public function index()
    {

        imagecopyresampled();
        set_time_limit(0);

        $phone_models = array(
            //'iphone-x',
            'iphone-8',
            //'iphone-8-plus',
            //'iphone-5',
            //'iphone-6',
            //'iphone-6-plus',
            //'iphone-7',
            //'iphone-7-plus',
            //'iphone-xr',
            //'iphone-xs',
            //'iphone-xs-max'
        );

        $phone_materials = array(
            'seffaf' => array(
                'seffaf-kilif'
            ),
            'aquarium' => array(
                'aquarium-red-kilif',
                'aquarium-black-kilif',
                'aquarium-silver-kilif'
            ),
            'silicon' => array(
                'silicon-red-kilif',
                'silicon-black-kilif',
                'silicon-yellow-kilif',
                'silicon-pink-kilif'
            ),
            'neon' => array(
                'neon-green-kilif',
                'neon-orange-kilif',
                'neon-violet-kilif'
            ),
        );

        $brand = 'apple';

        $product_models = array('aq', 'neon');

        foreach ($product_models as $p_model){
            for ($i = 1; $i <= 55; $i++){
                foreach ($phone_models as $model){
                    $metarials = 'https://deercase.ir/api/v1/materials/mobile/' . $model;
                    $icerik = file_get_contents($metarials);
                    $metarials = json_decode($icerik, true);
                    $metarials = $metarials['data'];
                    foreach ($metarials as $metarial){
                        foreach ($phone_materials[$metarial['slug']] as $slug){
                            $sub_link = 'https://deercase.ir/api/v1/gp/'.$brand.'-'.$model.'-' . $slug;
                            $sub_icerik = file_get_contents($sub_link);
                            $sub_icerik = json_decode($sub_icerik, true);
                            if($sub_icerik['jpg'] != ''){
                                // jpg değeri boş değilse metaryalin renk varyantı var demektir.
                                $product_images_link = 'https://deercase.ir/api/v1/sticker-case/gallery/'.$brand.'-'.$model.'-'.$slug.'/'.$p_model . ( $i<10 ? '0'.$i : $i );
                                $pattern_link = 'https://deercase.ir/api/v1/sticker-case/png-500/'.$brand.'-'.$model.'-'.$slug.'/'.$p_model.( $i<10 ? '0'.$i : $i ).'/6/1/1/';
                                //echo $product_images_link . '<br>';
                                $product_data = array();
                                $product_data = array(
                                    'model' => $p_model.( $i<10 ? '0'.$i : $i ),
                                    'model2' => $p_model.( $i<10 ? '0'.$i : $i ) . '-' . $slug,
                                    'name' => $metarial['name'],
                                    'image' => $sub_icerik['jpg'],
                                    'mp4' => $sub_icerik['mp4'],
                                    'webm' => $sub_icerik['webm'],
                                    'pattern_link' => $pattern_link,
                                    'product_images_link' => $product_images_link,
                                    'brand' => $brand,
                                    'category' => $model,
                                    'slug' => $slug
                                );
                                $this->addProduct($product_data);
                            }
                        }
                    }
                }
            }
        }


    }

    private function addProduct($data)
    {
        $ask = $this->db->query("SELECT * FROM ps_product WHERE model = '". $this->db->escape($data['model']) ."' AND model2 = '". $data['model2'] ."' ")->row;
        if(!$ask){

        //echo $data['category'] . ' - ' . $slug[0] .' - ' .$data['model']. '<br>';

        $upload_path = DIR_IMAGE . 'catalog/products/';
        $upload_path_l = 'catalog/products/';
        $upload_path_p = 'catalog/products/';
        $path = $upload_path . $data['model'];
        $upload_path_l .= $data['model'];
        $upload_path_p .= $data['model'];
        if(!is_dir($path)){
            if (!mkdir($path, 0777, true)) {
                var_dump("Hata");
            }
        }

        $path .= '/' . $data['brand'];
        $upload_path_l .= '/' . $data['brand'];
        $upload_path_p .= '/' . $data['brand'];
        if(!is_dir($path)){
            if (!mkdir($path, 0777, true)) {
                var_dump("Hata");
            }
        }

        $path .= '/' . $data['category'];
        $upload_path_l .= '/' . $data['category'];
        $upload_path_p .= '/' . $data['category'];
        if(!is_dir($path)){
            if (!mkdir($path, 0777, true)) {
                var_dump("Hata");
            }
        }


        $slug = explode('-', $data['slug']);

        $path .= '/' . $slug[0];
        $upload_path_l .= '/' . $slug[0];
        $upload_path_p .= '/' . $slug[0];
        if(!is_dir($path)){
            if (!mkdir($path, 0777, true)) {
                var_dump("Hata");
            }
        }


        $phone_models = array(
            'iphone-5' => 'iPhone5',
            'iphone-6' => 'iPhone6',
            'iphone-6-plus' => 'iPhone6Plus',
            'iphone-7' => 'iPhone7',
            'iphone-7-plus' => 'iPhone7Plus',
            'iphone-8' => 'iPhone8',
            'iphone-8-plus' => 'iPhone8Plus',
            'iphone-x' => 'iPhoneX',
            'iphone-xr' => 'iPhoneXr',
            'iphone-xs' => 'iPhoneXs',
            'iphone-xs-max' => 'iPhoneXsMax'
        );

        $phone_models_name = array(
            'iphone-5' => 'iPhone 5',
            'iphone-6' => 'iPhone 6',
            'iphone-6-plus' => 'iPhone 6 Plus',
            'iphone-7' => 'iPhone 7',
            'iphone-7-plus' => 'iPhone 7 Plus',
            'iphone-8' => 'iPhone8',
            'iphone-8-plus' => 'iPhone 8 Plus',
            'iphone-x' => 'iPhone X',
            'iphone-xr' => 'iPhone Xr',
            'iphone-xs' => 'iPhone Xs',
            'iphone-xs-max' => 'iPhone Xs Max'
        );

        $product_categories_ids = array(
            'iphone-5' => 1,
            'iphone-6' => 1,
            'iphone-6-plus' => 1,
            'iphone-7' => 1,
            'iphone-7-plus' => 1,
            'iphone-8' => 129,
            'iphone-8-plus' => 1,
            'iphone-x' => 127,
            'iphone-xr' => 1,
            'iphone-xs' => 1,
            'iphone-xs-max' => 1
        );

        $r_attribute_id = 0;
        $attribute_id = 0;
        $name_prefix = '';
        if($slug[0] == 'silicon'){
            $attribute_id = 48;
            if($slug[1] == 'red'){
                $r_attribute_id = 55;
                $name_prefix = 'Kırmızı Silikon Telefon Kılıfı';
            }
            elseif ($slug[1] == 'black'){
                $r_attribute_id = 59;
                $name_prefix = 'Siyah Silikon Telefon Kılıfı';
            }
            elseif ($slug[1] == 'yellow'){
                $r_attribute_id = 56;
                $name_prefix = 'Sarı Silikon Telefon Kılıfı';
            }
            elseif ($slug[1] == 'pink'){
                $r_attribute_id = 65;
                $name_prefix = 'Pembe Silikon Telefon Kılıfı';
            }

        }elseif ($slug[0] == 'neon'){
            $attribute_id = 46;
            if($slug[1] == 'green'){
                $r_attribute_id = 52;
                $name_prefix = 'Mavi / Sarı Neon Telefon Kılıfı';
            }
            elseif ($slug[1] == 'orange'){
                $r_attribute_id = 54;
                $name_prefix = 'Kırmızı / Turuncu Neon Telefon Kılıfı';
            }
            elseif ($slug[1] == 'violet'){
                $r_attribute_id = 50;
                $name_prefix = 'Kırmızı / Mor Neon Telefon Kılıfı';
            }
        }elseif ($slug[0] == 'aquarium'){
            $attribute_id = 47;
            if($slug[1] == 'silver'){
                $r_attribute_id = 63;
                $name_prefix = 'Gri / Simli Sulu Telefon Kılıfı';
            }
            elseif ($slug[1] == 'black'){
                $r_attribute_id = 62;
                $name_prefix = 'Siyah / Simli Sulu Telefon Kılıfı';
            }
            elseif ($slug[1] == 'red'){
                $r_attribute_id = 55;
                $name_prefix = 'Kırmızı / Simli Sulu Telefon Kılıfı';
            }
        }elseif ($slug[0] == 'seffaf'){
            $attribute_id = 49;
            if($slug[0] == 'seffaf'){
                $r_attribute_id = 64;
                $name_prefix = 'Şeffaf Telefon Kılıfı';
            }
        }



        $product_name = $phone_models_name[$data['category']] . ' ' . $data['model'] . ' ' . $name_prefix;

        echo $product_name . '<br>';

            $media_path = DIR_IMAGE . 'catalog/media/' . $phone_models[$data['category']];
            if(!is_dir($media_path)){
                if (!mkdir($media_path, 0777, true)) {
                    var_dump("Hata");
                }
            }

            $slug = explode('-', $data['slug']);

            $media_path = DIR_IMAGE . 'catalog/media/' . $phone_models[$data['category']] . '/' . $slug[0];
            $media_path_l = 'catalog/media/' . $phone_models[$data['category']] . '/' . $slug[0];
            if(!is_dir($media_path)){
                if (!mkdir($media_path, 0777, true)) {
                    var_dump("Hata");
                }
            }

            if($data['image']){
                if($slug[0] == 'seffaf'){
                    $new_path = $media_path .'/' . $slug[0] . '.jpg';
                    if(!is_file($new_path)){
                        copy($data['image'],   $new_path);
                    }
                    $image = $media_path_l .'/' . $slug[0] . '.jpg';
                }else{
                    $new_path = $media_path .'/' . $slug[1] . '.jpg';
                    if(!is_file($new_path)){
                        copy($data['image'],   $new_path);
                    }
                    $image = $media_path_l .'/' . $slug[1] . '.jpg';
                }

            }else{
                $image = '';
            }

            if($data['mp4']){
                $new_path = $media_path .'/' . $slug[1] . '.mp4';
                if(!is_file($new_path)){
                    copy($data['mp4'],   $new_path);
                }
                $media = $media_path_l .'/' . $slug[1] . '.mp4';

                $new_path = $media_path .'/' . $slug[1] . '.webm';
                if(!is_file($new_path)){
                    copy($data['webm'],   $new_path);
                }
            }else{
                $media = '';
            }

            $product_images_link = file_get_contents($data['product_images_link']);
            $product_images_link = json_decode($product_images_link, true);

            $product_images = array();
            if(isset($product_images_link[1])){
                unset($product_images_link[0]);
                foreach ($product_images_link as $p_image){
                    if($slug[0] == 'seffaf'){
                        $file_image = $path . '/' . $slug[0] . '-'. $p_image['id'] . '.jpg';
                        $file_image_l = $upload_path_l .'/' . $slug[0] . '-'. $p_image['id'] . '.jpg';
                        if(!is_file($file_image)){
                            copy($p_image['url'], $file_image);
                        }
                    }else{
                        $file_image = $path . '/' . $slug[1] . '-'. $p_image['id'] . '.jpg';
                        $file_image_l = $upload_path_l . '/' . $slug[1] . '-'. $p_image['id'] . '.jpg';
                        if(!is_file($file_image)){
                            copy($p_image['url'], $file_image);
                        }
                    }
                    $product_images[] = array(
                        'image' => $file_image_l
                    );
                }
            }

            $pattern_path = '';
            if($data['pattern_link']){
                if($slug[0] == 'seffaf'){
                    $pattern_path = $path . '/' . $slug[0] . '-'. $data['model'] . '.png';
                    $upload_path_p .= '/' . $slug[0] . '-'. $data['model'] . '.png';
                    if(!is_file($pattern_path)){
                        copy($data['pattern_link'], $pattern_path);
                    }
                }else{
                    $pattern_path = $path . '/' . $slug[1] . '-'. $data['model'] . '.png';
                    $upload_path_p .= '/' . $slug[1] . '-'. $data['model'] . '.png';
                    if(!is_file($pattern_path)){
                        copy($data['pattern_link'], $pattern_path);
                    }
                }
            }


            $this->db->query("INSERT INTO ps_product SET
            model = '". $this->db->escape($data['model']) ."',
            model2 = '". $this->db->escape($data['model2']) ."',
            image = '". $this->db->escape($image) ."',
            media = '". $this->db->escape($media) ."',
            pattern = '". $this->db->escape($upload_path_p) ."',
            quantity = '10',
            subtract = '1',
            manufacturer_id = '13',
            minimum = '1',
            stock_status_id = '1',
            product_type = '1',
            status = 1
            ");

            $product_id =  $this->db->getLastId();

            $this->db->query("INSERT INTO ps_product_description SET
            product_id = '". (int)$product_id ."',
            language_id = '1',
            name = '". $this->db->escape($product_name) ."',
            meta_title = '". $this->db->escape($product_name) ."'
             ");

            $this->db->query("INSERT INTO ps_product_to_store SET product_id = '" . (int)$product_id . "', store_id = '0'");

            $this->db->query("INSERT INTO ps_product_attribute SET product_id = '" . (int)$product_id . "', attribute_id = '" . (int)$attribute_id. "', language_id = '1' ");
            $this->db->query("INSERT INTO ps_product_attribute SET product_id = '" . (int)$product_id . "', attribute_id = '" . (int)$r_attribute_id. "', language_id = '1' ");

            foreach ($product_images as $product_image) {
                $this->db->query("INSERT INTO ps_product_image SET 
                product_id = '" . (int)$product_id . "', 
                image = '" . $this->db->escape($product_image['image']) . "' ");
            }

            $category_id = $product_categories_ids[$data['category']];

            $check_cat_to_product = $this->db->query("SELECT * FROM ps_product_to_category WHERE product_id = '" . (int)$product_id . "'AND category_id = '" . (int)$category_id . "'");
            if ($check_cat_to_product->num_rows == 0) {
                $parent_row = $this->db->query("SELECT parent_id FROM ps_category WHERE category_id = '" . (int)$category_id . "'");
                if ($parent_row->num_rows > 0) {
                    if ((int)$parent_row->row['parent_id'] > 0) {
                        $check_cat_to_product = $this->db->query("SELECT * FROM ps_product_to_category WHERE product_id = '" . (int)$product_id . "'AND category_id = '" . (int)$parent_row->row['parent_id'] . "'");
                        if ($check_cat_to_product->num_rows == 0) {

                            $this->db->query("INSERT INTO ps_product_to_category SET 
                                product_id ='" . (int)$product_id . "',
                                category_id ='" . (int)$parent_row->row['parent_id'] . "' ");
                        }
                        $parent_sec_row = $this->db->query("SELECT parent_id From ps_category WHERE category_id = '" . (int)$parent_row->row['parent_id'] . "'");
                        if ($parent_sec_row->num_rows > 0) {
                            if ((int)$parent_sec_row->row['parent_id'] > 0) {
                                $check_cat_to_product = $this->db->query("SELECT * FROM ps_product_to_category WHERE product_id = '" . (int)$product_id . "'AND category_id = '" . (int)$parent_sec_row->row['parent_id'] . "'");
                                if ($check_cat_to_product->num_rows == 0) {
                                    $this->db->query("INSERT INTO ps_product_to_category SET 
                                        product_id ='" . (int)$product_id . "',
                                        category_id ='" . (int)$parent_sec_row->row['parent_id'] . "' ");
                                }
                            }
                        }
                    }
                }
                $this->db->query("INSERT INTO ps_product_to_category SET 
                    product_id = '" . (int)$product_id . "', 
                    category_id = '" . (int)$category_id . "' ");
            }



        }



    }

    private function permalinkimage($deger)
    {
        $turkce = array("ş", "Ş", "ı", "(", ") ", "‘", "ü", "Ü", "ö", "Ö", "ç", "Ç", " ",  " /",  " *",  " ?", "ş", "Ş", "ı", "ğ", "Ğ", "İ", "ö", "Ö", "Ç", "ç", "ü", "Ü");
        $duzgun =array("s", "S", "i", "", "", "", "u", "U", "o", "O", "c", "C",  " -",  " -",  " -", "", "s", "S", "i", "g", "G", "I", "o", "O", "C", "c", "u", "U");
        $deger =str_replace($turkce ,$duzgun ,$deger);
        $deger = preg_replace( "@[ ^ A -Z a -z 0 - 9 -_ ] +@i" ,"" ,$deger);
        return $deger;
    }

    private function getCurl($link, $p_model)
    {



        $url = $link; //Login.php $_SERVER['HTTP_USER_AGENT'] yazarsanız gelen browser değerlerini görebilirsiniz.

        $_curl = curl_init();//cURL oturmu başlatıldı.
        curl_setopt($_curl,CURLOPT_URL,$url);//URL tanımlanıyor.
        curl_setopt($_curl,CURLOPT_VERBOSE,1);// Hata ayıklama çalıştı.
        curl_setopt($_curl,CURLOPT_RETURNTRANSFER,1);// Çıktı işlevini curl_exec() olacak
        $gelendeger = curl_exec($_curl) or die(curl_error());
        $curl_status = curl_getinfo($_curl);
        curl_close($_curl);

        if($curl_status['http_code'] == 200){
            $data = json_decode($gelendeger, true);
            //var_dump( $data);
            var_dump('https://deercase.ir' . $data[0]['url']);
            var_dump($link);
            var_dump($p_model); die();
        }




    }
}