<?php

namespace Database\Seeders;

use App\Keyword;
use App\KeywordDetail;
use Illuminate\Database\Seeder;
use App\Product;
use App\ProductBrand;
use App\ProductBrandDetail;
use App\ProductCategory;
use App\ProductCategoryDetail;
use App\ProductImage;
use App\Seo;
use ImageCross;

class ImportProductEtsy extends Seeder
{
    private $_path;

    public function __construct()
    {
        $this->_path = public_path('uploads/files/');
    }

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //------------delete------------------
        $limitOneFile = 5;
        $countOneFile = 0;
        Product::where('id', '>=', 4)->delete();
        //------------delete------------------

        $error = [];
        $csv_files = glob(public_path("uploads/csv") . "/*.csv");
        foreach ($csv_files as $csvFileName) {
            print "------------------------------ \r\n Start Reading Data of file: " . basename($csvFileName) . "\r\n";
            $count = 0;
            $csv = fopen($csvFileName, "r");
            while (!feof($csv)) {
                $row = fgetcsv($csv);
                if ($count > 0) {
                    if (!isset($row) || $row == null) continue;
                    try {
                        $previewCode = md5(date('Y-m-d H:i:s') . rand(1, 99999999));
                        $publishAt = date('Y-m-d H:i:s');

                        $productName = str_replace("®", "", $row[1]);
                        $sku = trim($row[0]);
                        $slug = $sku . "-" . trim($row[12]);

                        $skuKey = trim(preg_replace('/([A-Z])/', ' $1', trim($row[2])));
                        $skuKey = str_replace(" ", "-", $skuKey);
                        $sku = strtolower($skuKey . "-" . $sku);

                        $checkProduct = Product::where('name', $productName)->where('slug', $slug)->where('sku', $sku)->first();
                        if (isset($checkProduct) && $checkProduct->id != null) continue;

                        $ratingAvg = 0;
                        if (trim($row[14]) !== null && trim($row[14]) != "") {
                            $row[14] = (float)$row[14];
                            $ratingAvg = round($row[14], 2);
                        }

                        $thumbnail = null;
                        if (trim($row[15]) !== "" && trim($row[15]) !== null) {
                            $thumbnail = md5(date('YmdHis') . rand(1, 9999999999)) . ".jpg";
                            ImageCross::make(trim($row[15]))->orientate()->save($this->_path . $thumbnail);
                        }
                        $description = str_replace("<p></p>", "", trim($row[3]));

                        $product = Product::create([
                            'name'              => $productName,
                            'slug'              => $slug,
                            'sku'               => $sku,
                            'price'             => trim($row[4]),
                            'thumbnail'         => $thumbnail,
                            'in_stock'          => 1,
                            'rating_avg'        => $ratingAvg,
                            'information'       => trim($row[20]),
                            'short_description' => trim($row[21]),
                            'description'       => $description,
                            'preview'           => $previewCode,
                            'publish_at'        => $publishAt,
                            'is_activated'      => 1,
                            'created_at'        => date('Y-m-d H:i:s'),
                            'updated_at'        => date('Y-m-d H:i:s')
                        ]);

                        //Category
                        $categoryStr = trim($row[7]);
                        $categoryStr = explode(">", $categoryStr);
                        $lastCateId = null;
                        $lastParentId = 0;
                        $lastCateName = "";
                        foreach ($categoryStr as $cate) {
                            $cate = trim($cate);
                            $cItem = ProductCategory::notDeleted()->where('name', $cate)->where('parent_id', $lastParentId)->first();
                            if (!isset($cItem)) {
                                $cItem = ProductCategory::create([
                                    'name'       => $cate,
                                    'slug'       => $cate,
                                    'parent_id'  => $lastParentId,
                                    'created_at' => date('Y-m-d H:i:s'),
                                    'updated_at' => date('Y-m-d H:i:s')
                                ]);
                            }
                            $lastCateId = $cItem->id;
                            $lastParentId = $cItem->id;
                            $lastCateName = $cItem->name;
                        }
                        if ($lastCateId != null && $lastCateId != "") ProductCategoryDetail::create(['product_id' => $product->id, 'product_category_id' => $lastCateId, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]);

                        //Brand
                        $brandName = trim($row[2]);
                        if ($brandName !== "") {
                            $brand = ProductBrand::notDeleted()->where('name', $brandName)->first();
                            if (!isset($brand)) {
                                $brand = ProductBrand::create([
                                    'name'       => $brandName,
                                    'slug'       => $brandName,
                                    'created_at' => date('Y-m-d H:i:s'),
                                    'updated_at' => date('Y-m-d H:i:s')
                                ]);
                            }

                            ProductBrandDetail::create([
                                'product_id'       => $product->id,
                                'product_brand_id' => $brand->id,
                                'created_at'       => date('Y-m-d H:i:s'),
                                'updated_at'       => date('Y-m-d H:i:s')
                            ]);
                        }

                        //Slider
                        if (trim($row[6]) != null && trim($row[6]) != "") {
                            $images = trim($row[6]);
                            $images = explode("|", $images);
                            $sliderData = [];
                            foreach ($images as $iIt) {
                                $sName = md5(date('YmdHis') . rand(1, 9999999999)) . ".jpg";
                                ImageCross::make(trim($iIt))->orientate()->save($this->_path . $sName);
                                $sliderData[] = [
                                    'product_id' => $product->id,
                                    'file_name'  => $sName,
                                    'name'       => $sName,
                                    'created_at' => date('Y-m-d H:i:s'),
                                    'updated_at' => date('Y-m-d H:i:s')
                                ];
                            }
                            if (count($sliderData) > 0) ProductImage::insert($sliderData);
                        }

                        //Seo Meta
                        $seoTitle = $product->name;
                        Seo::create([
                            'uri'         => "/product/" . $product->slug,
                            'title'       => $seoTitle,
                            'keywords'    => '',
                            'description' => '',
                            'type'        => 'product',
                            'post_id'     => $product->id,
                            'created_at'  => date('Y-m-d H:i:s'),
                            'updated_at'  => date('Y-m-d H:i:s'),
                        ]);

                        //Tag
                        if ($lastCateName != "") {
                            $tag = trim($lastCateName);
                            $checkKeyword = Keyword::where('is_deleted', 0)
                                ->where(function ($query) use ($tag) {
                                    $query->where('name', $tag)
                                        ->orWhere('name', strtolower($tag))
                                        ->orWhere('name', strtoupper($tag))
                                        ->orWhere('name', ucfirst($tag));
                                })->first();
                            if (!isset($checkKeyword) || $checkKeyword->id == null) {
                                $checkKeyword = Keyword::create([
                                    'name'         => $tag,
                                    'is_activated' => true,
                                    'is_deleted'   => false,
                                    'created_at'   => date('Y-m-d H:i:s'),
                                    'updated_at'   => date('Y-m-d H:i:s'),
                                ]);
                            }
                            KeywordDetail::create([
                                'keyword_id' => $checkKeyword->id,
                                'ref_id'     => $product->id,
                                'type'       => 'product',
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                            ]);
                        }

                        print "Product Imported: [id] " . $product->id . " \t Name: " . $productName . "\r\n";



                        //------------delete------------------
                        $countOneFile++;
                        if ($countOneFile >= $limitOneFile) {
                            $countOneFile = 0;
                            break;
                        }
                        //------------delete------------------

                    } catch (Exception $exception) {
                        $error[] = $row[11];
                        print "Error load file from http: \r\n" . $exception->getMessage();
                    }
                }
                $count++;
            }
            fclose($csv);
            //unlink($csvFileName);
        }

        if (count($error) > 0) {
            foreach ($error as $err) {
                print "Error Product: " . $err . "\r\n";
            }
            $errorOld = [];
            if (file_exists(public_path("uploads/csv/errors.json"))) {
                $errorOld = json_decode(file_get_contents(public_path("uploads/csv/errors.json")), true);
            }
            $error = array_merge($errorOld, $error);
            file_put_contents(public_path("uploads/csv/errors.json"), json_encode($error));
        }
    }

    function getImageFromUrl($url)
    {
        $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/jpg, image/png';
        $headers[] = 'Connection: Keep-Alive';
        $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
        $user_agent = 'php';
        $process = curl_init($url);
        curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($process, CURLOPT_HEADER, 0);
        curl_setopt($process, CURLOPT_USERAGENT, $user_agent); //check here
        curl_setopt($process, CURLOPT_TIMEOUT, 30);
        curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
        $return = curl_exec($process);
        curl_close($process);

        return $return;
    }

}
