<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Etsy;

class EtsyExport extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'etsy:export {store} {--type=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Export store item of Etsy EC site.';
    private $_path;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->_path = public_path("jsondata") . "/";
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $shopName = str_replace(" ", "", trim($this->argument('store')));
        if ($shopName == null || $shopName == "") {
            $this->error("Shop name is invalid.");
            exit();
        }

        $type = $this->option('type');
        $skuKey = trim(preg_replace('/([A-Z])/', ' $1', $shopName));
        $skuKey = str_replace(" ", "-", $skuKey);

        if (isset($type) && $type == "wordpress") {
            $this->wordpressExport($shopName, $skuKey);
        } elseif (isset($type) && $type == "gxomens") {
            $this->gxomensExport($shopName);
        } else {
            $this->wordpressExport($shopName, $skuKey);
            $this->gxomensExport($shopName);
        }
    }

    private function wordpressExport($shopName, $skuKey = '') {
        $products = Etsy::with('category', 'highlight', 'image')
            ->where('shop_name', $shopName)
            ->get();

        $published = 0;
        $inStock = 1;
        $shippingClass = "ウルグアイ";
        $currencyRate = 206;
        $csvHeader = '"ID","Type","SKU","Name","Published","Is featured?","Visibility in catalog","Short description","Description","Date sale price starts","Date sale price ends","Tax status","Tax class","In stock?","Stock","Low stock amount","Backorders allowed?","Sold individually?","Weight (kg)","Length (cm)","Width (cm)","Height (cm)","Allow customer reviews?","Purchase note","Sale price","Regular price","Categories","Tags","Shipping class","Images","Download limit","Download expiry days","Parent","Grouped products","Upsells","Cross-sells","External URL","Button text","Position","Attribute 1 name","Attribute 1 value(s)","Attribute 1 visible","Attribute 1 global","Attribute 2 name","Attribute 2 value(s)","Attribute 2 visible","Attribute 2 global","Attribute 3 name","Attribute 3 value(s)","Attribute 3 visible","Attribute 3 global","Attribute 2 default"';
        $csvContent = "";
        $count = 0;

        foreach ($products as $item) {
            $regularPrice = trim(str_replace(",", "", $item->price));
            $regularPrice = (float) $regularPrice;
            if (trim($item->currency) == "VND") $regularPrice = ceil($regularPrice/$currencyRate);
            $desc = str_replace("\r\n", "<br/>", $item->description);
            $shortDesc = $this->getShortDesc($item->description);
            $categories = $this->categoryParent($item->category);
            $images = $this->imageStr($item->image);
            $itemName = $this->decodeStr($item->name);
            $desc = $this->decodeStr($desc);
            $shortDesc = $this->decodeStr($shortDesc);
            if ($skuKey == "" || $skuKey == null) $skuKey = $item->slug;
            $csvContent .= '"","simple","' . $skuKey . '-' . $item->product_id . '","' . $itemName . '","' . $published . '","0","visible","' . $shortDesc . '","' . $desc . '","","","taxable","","' . $inStock . '","","","0","0","","","","","1","","","' . $regularPrice . '","' . $categories . '","","' . $shippingClass . '","' . $images . '","","","","","","","","","0","","","","","","","","","","","","",""' . "\r\n";
            $count++;
        }

        $csvData = $csvHeader . "\r\n" . $csvContent;
        $csvFile = $this->_path . "wc-import-" . strtolower($shopName) . "-" . date('YmdHis') . ".csv";
        file_put_contents($csvFile, $csvData);
        print "[Etsy] Exported: {$csvFile}\r\n";
    }

    private function gxomensExport($shopName) {
        $products = Etsy::with('category', 'highlight', 'image')
            ->where('shop_name', $shopName)
            ->get();

        $currencyRate = 206;
        $csvHeader = '"Sku","Name","Brand","Description","Regular_price","Sale_price","Images","Category","Tag","Size","Site","Url","Slug","Shop","Rate","Thumbnail","Video","Reviews","ReviewItem","Availability","Note","ShortDescription"';
        $csvContent = "";
        $count = 0;

        foreach ($products as $item) {
            $regularPrice = trim(str_replace(",", "", $item->price));
            $regularPrice = (float) $regularPrice;
            if (trim($item->currency) == "VND") $regularPrice = ceil($regularPrice/$currencyRate);
            $desc = str_replace("\r\n", "<br/>", $item->description);
            $shortDesc = $this->getShortDesc($item->description);
            $categories = $this->categoryParent($item->category);
            $images = $this->imageStr2($item->image);
            $itemName = $this->decodeStr($item->name);
            $desc = $this->decodeStr($desc);
            $shortDesc = $this->decodeStr($shortDesc);
            $csvContent .= '"' . $item->product_id . '","'. $itemName .'","' . $item->shop_name . '","<p>' . trim($desc) . '</p>","' . $regularPrice . '","' . $item->sales . '","' . $images . '","' . $categories . '","' . $categories . '","","esty","' . $item->url . '","' . $item->slug . '","' . $item->shop_name . '","' . $item->rating . '","' . $item->thumbnail . '","' . $item->videos . '","' . $item->reviews_shop . '","' . $item->reviews_item . '","' . $item->availability . '","' . $item->note . '","' . $shortDesc . '"' . "\r\n";
            $count++;
        }

        $csvData = $csvHeader . "\r\n" . $csvContent;
        $csvFile = $this->_path . "gxomens-import-" . strtolower($shopName) . "-" . date('YmdHis') . ".csv";
        file_put_contents($csvFile, $csvData);
        print "[Etsy] Exported: {$csvFile}\r\n";
    }

    private function decodeStr($str = '') {
        $str = htmlspecialchars_decode($str);
        $str = html_entity_decode($str);
        $str = str_replace("'", '’', $str);
        $str = str_replace("&#39;", '’', $str);
        $str = str_replace("'", "’", $str);
        $str = str_replace('"', '“', $str);
        return trim($str);
    }

    private function categoryParent($category) {
        $cate = null;
        if (isset($category) && $category != null) {
            $cate = $category->name;
            if ($category->parent != null) {
                $parent = $this->categoryParent($category->parent);
                if ($parent != "") $cate = $parent . " > " . $cate;
            }
        }
        return $cate;
    }

    private function imageStr($images) {
        $img = "";
        foreach ($images as $item) {
            $itImg = "";
            if ($item->src_zoom != "") {
                $itImg = $item->src_zoom;
            } else if ($item->data_src != "") {
                $itImg = $item->data_src;
            } else {
                $itImg = $item->src;
            }
            $img .= ($img == "") ? $itImg : ", " . $itImg;
        }
        return $img;
    }

    private function imageStr2($images) {
        $img = "";
        foreach ($images as $item) {
            $itImg = "";
            if ($item->src_zoom != "") {
                $itImg = $item->src_zoom;
            } else if ($item->data_src != "") {
                $itImg = $item->data_src;
            } else {
                $itImg = $item->src;
            }
            $img .= ($img == "") ? $itImg : "|" . $itImg;
        }
        return $img;
    }

    private function getShortDesc($desc) {
        $descStr = "";
        $list = explode("\r\n", $desc);
        $count = 0;
        foreach ($list as $key => $item) {
            if (trim($item) != "") {
                $descStr .= trim($item) . "<br/>";
                $count++;
                if ($count > 3) break;
            }
        }
        return $descStr;
    }
}
