<?php

use Illuminate\Database\Seeder;
use App\Keyword;
use App\KeywordDetail;
use App\Seo;
use App\ShopCsvLog;
use App\ShopInfo;
use App\ShopReview;
use App\ShopSlider;
use App\Shop;
use App\Area;
use App\ShopMeta;
use App\Header;
use App\Helpers\Helper;
use Illuminate\Support\Facades\Log;

class ImportStoreCsv extends Seeder
{
	private $_imagePath;
    private $_csvPath;

    public function __construct()
    {
        $this->_imagePath = public_path('uploads/image/shop/');
        $this->_csvPath = storage_path('app/public/uploads/temp/csv/');
    }

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        print "Start Importing:\r\n";
        $thumbPath = public_path('uploads/image/shop/');

        /*$log = ShopCsvLog::where('status', 2)->orderBy('id', 'DESC')->first();
        if (!isset($log)) exit();
        $csvPath = $this->_csvPath . $log->file_name;*/
        //if (isset($log) && $log->file_name != '' && $log->file_name != null && file_exists($csvPath)) {
        /*$log->update(['status' => 3]);*/

        $hasNewStore = false;
        $countSuccess = 0;
        $fileListCSV = glob($this->_csvPath . '*.csv');
        foreach($fileListCSV as $csvPath){
            print "File Importing: " . $csvPath . "\r\n";
            $fileHandle = fopen($csvPath, "r");
            $count = 0;
            $listRow = [];
            $newRow = [];
            $listName = [];

            while (!feof($fileHandle)) {
                $row = fgetcsv($fileHandle);
                $count++;
                if ($count == 1) continue;    
                if (isset($row) && is_array($row) && count($row) >= 23) {
                    if (trim($row[2]) != "" && trim($row[2]) != null) {
                        if (isset($newRow['name']) && $newRow['name'] != "") {
                            $listRow[] = $newRow;
                            if (!in_array($newRow['name'], $listName)) $listName[] = $newRow['name'];
                        }

                        $newRow = [];
                        $newRow['id'] = $row[0];
                        $newRow['area'] = $row[1];
                        $newRow['name'] = $row[2];
                        $newRow['fee'] = $row[3];
                        $newRow['average'] = $row[4];
                        $newRow['benefit'] = $row[5];
                        $newRow['numberOfTeller'] = $row[6];
                        $newRow['operation'] = $row[7];
                        $newRow['review'] = $row[8];
                        $newRow['evaluation'] = 0; //$row[9];
                        $newRow['description'] = $row[10];
                        $newRow['logo'] = $row[11];
                        $newRow['defaultSearch'] = $row[16];
                        $newRow['active'] = 1; //$row[17];

                        $newRow['seoTitle'] = $row[18];
                        $newRow['seoKeywords'] = $row[19];
                        $newRow['seoDescription'] = $row[20];
                        $newRow['seoImage'] = $row[21];
                        $newRow['appraisalMethod'] = ''; //$row[22];

                        $newRow['images'] = (trim($row[12]) != "") ? explode("|", trim($row[12])) : [];
                        $newRow['info'] = [];

                        $methodOrg = trim($row[13]);
                        $methodOrg = str_replace(" ", "", $methodOrg);
                        $methodOrg = str_replace("❘", "|", $methodOrg);
                        $newRow['method'] = explode("|", $methodOrg);
                    }
                    if ($row[14] != null && trim($row[14]) != "") $newRow['info'][] = ['title' => $row[14], 'content' => $row[15]];
                }
            }
            fclose($fileHandle);
            if (isset($newRow) && $newRow != null && count($newRow) > 0) {
                $listRow[] = $newRow;
            }

            if(count($listRow) > 0) {
                foreach ($listRow as $store) {
                    $areaNameItem = trim($store['area']);
                    if ($areaNameItem == "神奈川県" || $areaNameItem == "神奈川県" || $areaNameItem == "神奈川") $areaNameItem = "神奈川";
                    $area = Area::where('is_deleted', false)->where('name', $areaNameItem)->first();
                    if (!isset($area)) {
                        $area = Area::create([
                            'name'         => $areaNameItem,
                            'order'        => 999,
                            'parent_id'    => 0,
                            'show_top'     => 0,
                            'show_search'  => 0,
                            'is_activated' => 1,
                            'created_at'   => date('Y-m-d H:i:s'),
                            'updated_at'   => date('Y-m-d H:i:s')
                        ]);
                        $area->update(['slug' => $area->id]);
                    }

                    $shop = Shop::where('is_deleted', 0)->where('name', $store['name'])->where('area_id', $area->id)->first();
                    if ((trim($store['id']) == "" || trim($store['id']) == null) && (!isset($shop) || $shop == null || !isset($shop->id))) {
                        $logo = '';
                        if ($store['logo'] != null && $store['logo'] != "") $logo = Helper::getStoreImage($store['logo'], $thumbPath);
                        $shop = Shop::create([
                            'area_id'      => $area->id,
                            'name'         => $store['name'],
                            'slug'         => Helper::slug($store['name']),
                            'fee'          => $store['fee'],
                            'average'      => $store['average'],
                            'benefits'     => $store['benefit'],
                            'operation'    => $store['operation'],
                            'reviews'      => $store['review'],
                            'description'  => $store['description'],
                            'logo'         => $logo,
                            'show_search'  => ($store['defaultSearch'] == true || $store['defaultSearch'] == "1" || $store['defaultSearch'] == 1) ? 1 : 0,
                            'is_activated' => ($store['active'] == true || $store['active'] == "1" || $store['active'] == 1) ? 1 : 0,
                            'created_at'   => date('Y-m-d H:i:s'),
                            'updated_at'   => date('Y-m-d H:i:s')
                        ]);
                        $ignoreShops[] = $store['name'];

                        $storeUpdateStation = [];
                        if (isset($store['info']) && is_array($store['info'])) {
                            $metaInfoData = [];
                            foreach ($store['info'] as $key => $item) {
                                $metaInfoData[] = [
                                    'shop_id'    => $shop->id,
                                    'title'      => $item['title'],
                                    'content'    => $item['content'],
                                    'order'      => ($key + 1),
                                    'created_at' => date('Y-m-d H:i:s'),
                                    'updated_at' => date('Y-m-d H:i:s'),
                                ];
                                if(trim($item['title']) == "最寄り駅") $storeUpdateStation['station'] = $item['content'];
                                if(trim($item['title']) == "住所") $storeUpdateStation['address'] = $item['content'];   
                            }
                            if (count($metaInfoData) > 0) ShopMeta::insert($metaInfoData);
                        }
                        if (count($storeUpdateStation) > 0) $shop->update($storeUpdateStation);

                        if (isset($store['method']) && is_array($store['method'])) {
                            $metaMethodData = [];
                            foreach ($store['method'] as $item) {
                                $item = trim($item);
                                $item = str_replace(" ", "", $item);
                                $item = str_replace("対面占い", 1, $item);
                                $item = str_replace("電話占い", 2, $item);
                                $item = str_replace("チャット占い", 3, $item);
                                $item = str_replace("メール占い", 4, $item);
                                $item = str_replace("オンライン占い", 5, $item);
                                $item = trim($item);
                                $item = str_replace(" ", "", $item);
                                $item = (integer)$item;

                                if (strpos($item, "|") === false && ($item == 1 || $item == 2 || $item == 3 || $item == 4 || $item == 5)) {
                                    $metaMethodData[] = [
                                        'shop_id'    => $shop->id,
                                        'info_id'    => $item,
                                        'created_at' => date('Y-m-d H:i:s'),
                                        'updated_at' => date('Y-m-d H:i:s'),
                                    ];
                                }
                            }
                            if (count($metaMethodData) > 0) ShopInfo::insert($metaMethodData);
                        }

                        if (isset($store['images']) && is_array($store['images'])) {
                            $thumbPathSlider = public_path('uploads/image/shop/');
                            foreach ($store['images'] as $item) {
                                if ($item != null && $item != "") {
                                    $sName = basename($item);
                                    if(strlen($sName) > 50) $sName = md5(rand(100, 10000)) . ".jpg";
                                    $fileName = Helper::getStoreImage($item, $thumbPathSlider);
                                    ShopSlider::create([
                                        'shop_id'    => $shop->id,
                                        'name'       => $sName,
                                        'file_name'  => $fileName,
                                        'type'       => 'slider',
                                        'created_at' => date('Y-m-d H:i:s'),
                                        'updated_at' => date('Y-m-d H:i:s')
                                    ]);
                                }
                            }
                        }

                        $shopUri = '/shop/detail/' . $shop->id;
                        $metaSeo = Seo::where('uri', $shopUri)->where('post_id', $shop->id)->first();
                        $seoData = [
                            'uri'         => $shopUri,
                            'title'       => (isset($store['seoTitle']) && $store['seoTitle'] != null && $store['seoTitle'] != "") ? $store['seoTitle'] : $store['name'],
                            'keywords'    => isset($store['seoKeywords']) ? $store['seoKeywords'] : '',
                            'description' => isset($store['seoDescription']) ? $store['seoDescription'] : '',
                            'type'        => 'shop',
                            'post_id'     => $shop->id,
                            'updated_at'  => date('Y-m-d H:s:i'),
                        ];
                        if (isset($metaSeo)) {
                            $metaSeo->update($seoData);
                        } else {
                            $seoData['created_at'] = date('Y-m-d H:s:i');
                            Seo::create($seoData);
                        }

                        if ($store['seoImage'] != null && $store['seoImage'] != "") {
                            $seoImage = Helper::getImageFile($store['seoImage'], public_path('uploads/image/header/'));
                            Header::create([
                                'uri'          => $shopUri,
                                'title'        => $store['name'],
                                'image'        => $seoImage,
                                'color'        => '#F1F1F1',
                                'type'         => 1,
                                'is_activated' => 1,
                                'created_at'   => date('Y-m-d H:i:s'),
                                'updated_at'   => date('Y-m-d H:i:s')
                            ]);
                        }

                        $countSuccess++;
                        $hasNewStore = true;
                        Log::info("Imported Store: [" . $shop->id . "] " . $shop->name . "\r\n");
                        print "Imported Store: [" . $shop->id . "] " . $shop->name . "\r\n";
                    }
                }
            }

            unlink($csvPath);
            /*$this->call(UpdateShopSlider::class);
            $log->update(['status' => 4]);*/
        //}
        }

        if ($hasNewStore) $this->call(UpdateShopSlider::class);
        print "Ended Importing.\r\n";
    }
}
