<?php
    require 'load.php';

    $res = json_decode(file_get_contents("urls.json"), true);


    foreach($res as $u) {
        $options = array(
            'http' => array(
                'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\r\n" . // Normal bir tarayıcı User-Agent'ı
                            "Referer: https://www.google.com/\r\n" . // Dosyanın bulunduğu domaini veya ana sayfayı referer olarak gönderin
                            "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\r\n" .
                            "Accept-Language: en-US,en;q=0.9,tr;q=0.8\r\n",
                'method' => 'GET',
                // 'timeout' => 10, // İsteğin zaman aşımı süresi (saniye)
                // 'ignore_errors' => true, // 4xx/5xx hatalarında bile içeriği almaya çalış
            ),
            'ssl' => array(
                'verify_peer' => false, // SSL sertifikası doğrulamayı kapat (güvenli değil, sadece test amaçlı)
                'verify_peer_name' => false,
            )
        );

        $context = stream_context_create($options);

        // file_get_contents() ile dosyaya erişin
        $file_content = @file_get_contents($u.".js", false, $context);

        if ($file_content === false) {
            echo "Dosyaya erişilemedi veya dosya bulunamadı. ".$u."\n";
        } else {
            // Dosya içeriğini işleyin
            $row = json_decode($file_content, true);
            if (json_last_error() === JSON_ERROR_NONE) {

                foreach($row['variants'] as $variant) {
                    $status             = 1;
                    $title              = count($row['variants']) == 1 ? $row['title'] : $variant['name'];
                    $sku                = $variant['sku'];
                    $ean                = $variant['barcode'];
                    $brand_id           = 1;
                    $supplier_id        = 0;
                    $category           = null;
                    $delivery_areas     = null;
                    $shipping_agencies  = null;
                    $featured           = 0;
                    $checkout_offer     = 0;
                    $free_shipping      = 1;
                    $new                = 0;

                    $price               = $variant['price']/100;
                    $discount_rate       = 50;
                    $discounted_price    = $price/2;
                    $buying_price        = 0;
                    $vat                 = 20;
                    $cart_discount_rate  = 0;
                    $cart_discounted_price = 0;

                    if($cart_discount_rate != 0) {
                        $selling_price = $cart_discounted_price;
                    }else if($discount_rate != 0) {
                        $selling_price = $discounted_price;
                    }else{
                        $selling_price = $price;
                    }

                    $description         = $row['description'];
                    $short_description   = "";
                    $info_1              = "";
                    $info_2              = "";
                    $info_3              = "";
                    $return_policy       = "";

                    $stock_tracking      = 1;
                    $stock_unit          = 1;
                    $stock_level         = -1;
                    $stock_critical_level = 0;
                    
                    $min_order_quantity  = (int)1;
                    $max_order_quantity  = (int)1000;
                    $search_keywords     = "";
                    $delivery_time       = 1;
                    $delivery_description = "";
                    $meta_title          = $title;
                    $meta_description    = $title . " fiyatını ve ürün özellikleri incelemek  için hemen tıklayın, en yeni fırsatları kaçırmayın!";

                    
                    if($max_order_quantity < 1) {
                        $max_order_quantity = 9999;
                    }

                    $seo_url	         = $utils->generateUrl($title);

                    if(!isset($_FILES['image']) || !file_exists($_FILES['image']['tmp_name']) || !is_uploaded_file($_FILES['image']['tmp_name'])){
                        $image               = "default.jpg";
                    } else {
                        $content = @file_get_contents($row["featured_image"], false, $context);
                        
                        $ext = pathinfo(parse_url($row["featured_image"], PHP_URL_PATH), PATHINFO_EXTENSION);
            
                        $image  = $seo_url."-".uniqid().".".$ext;
            
                        $fp = fopen("../public/assets/images/products/large/".$image, "w");
                        fwrite($fp, $content);
                        fclose($fp);

                        $image_parts         = pathinfo($_FILES['image']["name"]);
                        $image               = $seo_url."-".uniqid().".".$image_parts['extension'];
                        $utils->resizeCropImage(400, 500, $_FILES['image']['tmp_name'], "../public/assets/images/products/medium/".$image);
                        $utils->resizeCropImage(170, 170, $_FILES['image']['tmp_name'], "../public/assets/images/products/thumb/".$image);
                        //move_uploaded_file($_FILES['image']['tmp_name'], "../public/assets/images/products/large/".$image);
                    }

                    $stmt = $db->query("INSERT INTO {$db->prefix}products (`status`, `title`, `short_description`, `description`, info_1, info_2, info_3, `return_policy`, `sku`, `ean`, `free_shipping`, `featured`, `checkout_offer`, `new`, `supplier_id`, `brand_id`, `price`, `discounted_price`, `discount_rate`, `cart_discounted_price`, `cart_discount_rate`, `selling_price`, `buying_price`, `vat`, `stock_unit`, `stock_tracking`, `stock_level`, `stock_critical_level`, `delivery_time`, `delivery_description`, `min_order_quantity`, `max_order_quantity`, `image`, `search_keywords`, `date_added`, `date_modified`) VALUES (:status, :title, :short_description, :description, :info_1, :info_2, :info_3, :return_policy, :sku, :ean, :free_shipping, :featured, :checkout_offer, :new, :supplier_id, :brand_id, :price, :discounted_price, :discount_rate, :cart_discounted_price, :cart_discount_rate, :selling_price, :buying_price, :vat, :stock_unit, :stock_tracking, :stock_level, :stock_critical_level, :delivery_time, :delivery_description, :min_order_quantity, :max_order_quantity, :image, :search_keywords, NOW(), NOW())", 
                    array(':status'=>$status, ':title'=>$title, ':short_description'=>$short_description, ':description'=>$description, ':info_1'=>$info_1, ':info_2'=>$info_2, ':info_3'=>$info_3, ':return_policy'=>$return_policy, ':sku'=>$sku, ':ean'=>$ean, ':free_shipping'=>$free_shipping, ':price'=>$price, ':discount_rate'=>$discount_rate, ':discounted_price'=>$discounted_price, ':cart_discount_rate'=>$cart_discount_rate, ':cart_discounted_price'=>$cart_discounted_price, ':vat'=>$vat, ':selling_price'=>$selling_price, ':buying_price'=>$buying_price, ':featured'=>$featured, ':checkout_offer'=>$checkout_offer, ':new'=>$new, ':image'=>$image, ':supplier_id'=>$supplier_id, ':brand_id'=>$brand_id, ':stock_unit'=>$stock_unit, ':stock_tracking'=>$stock_tracking, ':stock_level'=>$stock_level, ':stock_critical_level'=>$stock_critical_level, ':delivery_time'=>$delivery_time, ':delivery_description'=>$delivery_description, ':min_order_quantity'=>$min_order_quantity, ':max_order_quantity'=>$max_order_quantity, ':search_keywords'=>$search_keywords));
                    if($stmt->error){
                        echo "error: ".$stmt->error."\n";
                    }else{
                        $inserted_id = $db->getLastId();
                        $utils->addUrl($seo_url, "product", $inserted_id, "", $meta_title, strip_tags($meta_description));

                        $db->query("INSERT INTO {$db->prefix}product_shipping (product_id, shipping_agency) VALUES (:product_id, 1)", array(':product_id'=>$inserted_id));
                    }
                }



                
            } else {
                echo "JSON verisi işlenemedi: " . json_last_error_msg() . " ".$u."\n";
            }
        }
    }