<?php

use Illuminate\Database\Seeder;
use App\Area;
use App\Road;
use App\Brand;
use App\Station;
use App\CountryOld;
use App\BrandOld;
use App\StoreOld;
use App\LocationOld;
use App\Store;
use App\Seo;
use App\Media;
use App\BrandDetail;
use Intervention\Image\Exception\NotReadableException;
use App\Helpers\Helper;

class CloneOldData extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    protected $state = false;
    protected $_filePath;

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

    public function run()
    {
        //Clear Data
        Brand::truncate();
        Area::truncate();
        Station::truncate();
        Store::truncate();

        //Brand
        $all = BrandOld::all();
        foreach ($all as $item) {
            $checkBrand = Brand::where('is_deleted', false)->where('name', $item->name)->count();
            if ($checkBrand > 0) continue;
            Brand::create([
                'name'         => $item->name,
                'slug'         => $item->slug,
                'description'  => $item->description,
                'is_activated' => 1,
                'created_at'   => $item->created_at,
                'updated_at'   => $item->updated_at,
            ]);
        }

        //Area
        for ($i = 0; $i < 2; $i++) {
            $locations = LocationOld::where('parent_id', 0)->get();
            foreach ($locations as $location) {
                print "Location: " . $location->title . " ---- " . $location->slug . "\r\n";
                $area = $this->insertArea($location, 0);
                $childs1 = $this->getChildArea($location->id);
                foreach ($childs1 as $c1) {
                    if ($c1->type == 'station') {
                        $this->insertStation($c1, $area->id);
                    } else {
                        $a1 = $this->insertArea($c1, $area->id);
                        $childs2 = $this->getChildArea($c1->id);
                        foreach ($childs2 as $c2) {
                            if ($c2->type == 'station') {
                                $this->insertStation($c2, $a1->id);
                            } else {
                                $a2 = $this->insertArea($c2, $a1->id);
                                $childs3 = $this->getChildArea($c2->id);
                                foreach ($childs3 as $c3) {
                                    if ($c3->type == 'station') {
                                        $this->insertStation($c3, $a2->id);
                                    } else {
                                        $a3 = $this->insertArea($c3, $a2->id);
                                        $childs4 = $this->getChildArea($c3->id);
                                        foreach ($childs4 as $c4) {
                                            if ($c4->type == 'station') {
                                                $this->insertStation($c4, $a3->id);
                                            } else {
                                                $a4 = $this->insertArea($c4, $a3->id);
                                                $childs5 = $this->getChildArea($c4->id);
                                                foreach ($childs5 as $c5) {
                                                    if ($c5->type == 'station') {
                                                        $this->insertStation($c5, $a4->id);
                                                    } else {
                                                        $a5 = $this->insertArea($c5, $a4->id);
                                                        $childs6 = $this->getChildArea($c5->id);
                                                        foreach ($childs6 as $c6) {
                                                            if ($c6->type == 'station') {
                                                                $this->insertStation($c6, $a5->id);
                                                            } else {
                                                                $this->insertArea($c6, $a5->id);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            $this->state = true;
        }

        $areas = Area::all();
        foreach ($areas as $item) {
            $duplicate = Area::where('id', '!=', $item->id)->where('name', $item->name)->where('slug', $item->slug)->count();
            if ($duplicate > 0) {
                print "Duplicate Area: " . $duplicate . "\r\n";
            }
        }

        //Store Brand
        $oldStores = StoreOld::with('brand_detail')->get();
        foreach ($oldStores as $item) {
            if (isset($item->brand_detail) && $item->brand_detail != null) {
                $fStore = Store::where('name', $item->name)
                    ->where('slug', $item->slug)
                    ->where('phone_number', $item->phone_number)
                    ->where('original_link', $item->original_link)
                    ->first();
                if (isset($fStore)) {
                    foreach ($item->brand_detail as $bIt) {
                        $fBrand = Brand::where('name', $bIt->brand->name)->where('slug', $bIt->brand->slug)->first();
                        if (isset($fBrand)) {
                            BrandDetail::create(['store_id' => $fStore->id, 'brand_id' => $fBrand->id]);
                        }
                    }
                }
            }
        }

        //Thumb
        Media::truncate();
        $allStores = Store::all();
        $media = Media::where('name', 'Stores')
            ->where('slug', 'stores')
            ->where('file', md5('Stores'))
            ->where('type', 0)
            ->where('parent_id', 0)
            ->where('is_deleted', false)
            ->first();
        if (!isset($media) || $media->id == null) {
            $media = Media::create([
                'name'       => 'Stores',
                'slug'       => 'stores',
                'file'       => md5('Stores'),
                'type'       => 0,
                'parent_id'  => 0,
                'is_deleted' => 0,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        }

        foreach ($allStores as $item) {
            if ($item->origin_thumb != null && $item->origin_thumb != "") {
                $fileName = $item->thumbnail;
                if ($fileName == null || $fileName == "") $fileName = md5(date('YmdHis') . rand(100, 1000000)) . ".jpg";
                if (!file_exists($this->_filePath . $fileName)) {
                    try {
                        $imageCross = ImageCross::make($item->origin_thumb)->orientate()->save($this->_filePath . $fileName);
                        $imgWidth = $imageCross->width();
                        $imgHeight = $imageCross->height();
                        $imgSize = $imageCross->filesize();

                        $baseName = basename($item->origin_thumb);
                        if (strlen($baseName) > 14) {
                            $baseName = substr($baseName, 0, 10);
                            $baseName = str_replace(".", "", $baseName);
                            $baseName .= ".jpg";
                        }

                        $slug = Helper::slug($baseName);
                        $slug = str_replace(".", "-", $slug);
                        $slug = str_replace("_", "-", $slug);
                        $slug = str_replace("--", "-", $slug);

                        Media::create([
                            'name'       => $baseName,
                            'slug'       => $slug,
                            'file'       => $fileName,
                            'file_type'  => 'image/jpeg',
                            'extension'  => '.jpg',
                            'size'       => $this->formatBytes($imgSize),
                            'width'      => $imgWidth,
                            'height'     => $imgHeight,
                            'type'       => 1,
                            'parent_id'  => $media->id,
                            'is_deleted' => 0,
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);
                        print "Generate Thumb: " . $item->id . " --- " . $fileName . "\r\n";
                    } catch (NotReadableException $exception) {
                        logger("[Error] Image Cross: " . $exception->getMessage());
                    } catch (\Exception $exception) {
                        logger("[Error] Image Cross: " . $exception->getMessage());
                    }
                }
                $item->thumbnail = $fileName;
                $item->save();
            }
        }
    }

    private function getChildArea($parentId)
    {
        return LocationOld::where('parent_id', $parentId)->get();
    }

    private function insertArea(LocationOld $item, $parentId = 0)
    {
        $area = Area::where('name', $item->title)->where('slug', $item->slug)->where('parent_id', $parentId)->where('is_activated', $item->is_activated)->first();
        if (!isset($area)) {
            $area = Area::create([
                'name'         => $item->title,
                'slug'         => $item->slug,
                'description'  => $item->description,
                'parent_id'    => $parentId,
                'order'        => $item->sort,
                'is_activated' => $item->is_activated,
                'is_deleted'   => $item->is_deleted,
                'created_at'   => date('Y-m-d H:i:s'),
                'updated_at'   => date('Y-m-d H:i:s')
            ]);
        }

        if ($this->state && isset($item->store) && $item->store !== null && $item->store->count() > 0) {
            foreach ($item->store as $store) {
                $stationId = null;
                if (isset($store->station) && $store->station != null) {
                    $station = Station::where('name', $store->station->title)
                        ->where('slug', $store->station->slug)
                        ->where('is_activated', $store->station->is_activated)
                        ->first();
                    $stationId = $station->id;
                }
                $insertData = [
                    'package_id'      => $store->package_id,
                    'area_id'         => $area->id,
                    'name'            => $store->name,
                    'slug'            => $store->slug,
                    'address'         => $store->address,
                    'phone_number'    => $store->phone_number,
                    'email'           => $store->email,
                    'title'           => $store->title,
                    'description'     => $store->description,
                    'other_request'   => $store->other_request,
                    'open_time'       => $store->open_time,
                    'working_time'    => $store->working_time,
                    'latitude'        => $store->latitude,
                    'longitude'       => $store->longitude,
                    'near'            => $store->near,
                    'rating'          => $store->rating,
                    'thumbnail'       => $store->thumbnail,
                    'origin_thumb'    => $store->origin_thumb,
                    'website'         => $store->website,
                    'original_link'   => $store->original_link,
                    'refer_id'        => $store->refer_id,
                    'seo_title'       => $store->seo_title,
                    'seo_robots'      => $store->seo_robots,
                    'seo_keywords'    => $store->seo_keywords,
                    'seo_description' => $store->seo_description,
                    'is_amp'          => $store->is_amp,
                    'is_activated'    => $store->is_activated,
                    'is_deleted'      => $store->is_deleted,
                    'created_at'      => date('Y-m-d H:i:s'),
                    'updated_at'      => date('Y-m-d H:i:s')
                ];
                if ($stationId != null) $insertData['station_id'] = $stationId;
                $storeNew = Store::create($insertData);
                $checkSeo = Seo::where('uri', '/store/' . $storeNew->id . '/' . $storeNew->slug)->where('post_id', $storeNew->id)->where('type', 'store')->count();
                if ($checkSeo <= 0) {
                    Seo::create([
                        'uri'         => '/store/' . $storeNew->id . '/' . $storeNew->slug,
                        'title'       => $store->seo_title,
                        'robots'      => $store->seo_robots,
                        'keywords'    => $store->seo_keywords,
                        'description' => $store->seo_description,
                        'type'        => 'store',
                        'post_id'     => $storeNew->id,
                        'created_at'  => date('Y-m-d H:i:s'),
                        'updated_at'  => date('Y-m-d H:i:s')
                    ]);
                }
            }
        }

        return $area;
    }

    private function insertStation(LocationOld $item, $parentId = 0)
    {
        $station = Station::where('name', $item->title)->where('slug', $item->slug)->where('area_id', $parentId)->where('is_activated', $item->is_activated)->first();
        if (!isset($station)) {
            Station::create([
                'area_id'      => $parentId,
                'name'         => $item->title,
                'slug'         => $item->slug,
                'description'  => $item->description,
                'is_activated' => $item->is_activated,
                'is_deleted'   => $item->is_deleted,
                'created_at'   => date('Y-m-d H:i:s'),
                'updated_at'   => date('Y-m-d H:i:s')
            ]);
        }
    }

    private function formatBytes($bytes, $precision = 2)
    {
        $units = array('B', 'Kb', 'MB', 'GB', 'TB');
        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= pow(1024, $pow); //$bytes /= (1 << (10 * $pow));

        return round($bytes, $precision) . '' . $units[$pow];
    }
}
