<?php

namespace App\Repositories\Shop;

use App\Models\Shop\Article;
use App\Models\Shop\Merchandise;
use App\Traits\Model\Basic;
use App\Repositories\Botanic\Species;
use App\Repositories\Botanic\Varieties;
use App\Repositories\Core\Comments;
use App\Repositories\Core\Tag;
use App\Traits\Repository\Imageable;
use Illuminate\Support\Str;

class Articles
{
    use Basic, Imageable;

    public static function autocomplete($str)
    {
        $data = Article::byAutocomplete($str)->orderBy('name')->limit(30)->pluck('name', 'id');
        $export = [];
        foreach ($data as $key => $name) {
            $export[] = ['value' => $key, 'text' => $name];
        }

        return $export;
    }

    public static function getOffersGroupedByNature($id, $saleChannelId = false)
    {
        $articleIds = self::getSiblingsIds($id);
        $articleIds[] = $id;
        $offers = Offers::getOffersByArticles($articleIds, $saleChannelId);
        foreach ($offers as $offer) {
            $data[strtolower($offer->article_nature->name)][] = [
                'id' => $offer->id,
                'name' => $offer->variation->name,
                'prices' => $offer->tariff->price_lists->first()->price_list_values->toArray(),
            ];
        }

        return $data ?? false;
    }

    public static function getSiblingsIDs($id)
    {
        return self::getSiblings($id)->pluck('id')->toArray();
    }

    public static function getSiblingsDescriptions($id)
    {
        $siblings = self::getSiblings($id);
        foreach ($siblings as $sibling) {
            if ($sibling->description && ($sibling->article_nature->name ?? false)) {
                $data[strtolower($sibling->article_nature->name)] = $sibling->description;
            }
        }

        return $data ?? false;
    }

    public static function getSiblings($id)
    {
        return Article::with([
            'siblings' => function ($query) use ($id) {
                $query->where('id', '!=', $id);
            },
        ])->find($id)->siblings;
    }

    public static function getOffersById($id)
    {
        return Offers::getOffersByArticle($id);
    }

    public static function getOptionsWithNature()
    {
        $articles = Article::with(['article_nature'])->get();
        foreach ($articles as $article) {
            $data[$article->id] = ($article->article_nature->name ?? null).' - '.$article->name;
        }
        asort($data, SORT_NATURAL);

        return $data;
    }

    public static function getAll()
    {
        return Article::orderBy('name', 'asc')->get();
    }

    public static function getArticleToSell($id, $saleChannelId = false)
    {
        $data = self::getArticle($id);
        $data['offers'] = self::getOffersGroupedByNature($id, $saleChannelId);

        return $data;
    }

    public static function getArticle($id)
    {
        $article = self::get($id);
        $data = $article->toArray();
        $data['description'] = self::getFullDescriptionByArticle($article);
        $images = self::getFullImagesByArticle($article);
        $data['image'] = self::getPreviewSrc($images[0] ?? false);
        $data['images'] = count($images) ? $images : false;
        $data['image_big'] = self::getImageSrc($images[0] ?? false);
        $data['inherited'] = self::getInherited($id);
        $data['categories'] = self::getCategoriesNameByArticle($article);
        $data['tags'] = self::getFullTagsSlugByArticle($article);
        $data['comments'] = Comments::getByModel($article);

        return $data;
    }

    public static function getFullDescriptionByArticle($article)
    {
        switch ($article->product_type) {
            case 'App\Models\Botanic\Variety':
                $data['variety'] = $article->product->description;
                $data['plus'] = $article->product->plus;
                if ($article->product->specie->description ?? false) {
                    $data['specie'] = $article->product->specie->description;
                }
                break;
            case 'App\Models\Botanic\Specie':
                $data['specie'] = $article->product->description;
                break;
            case 'App\Models\Shop\Merchandise':
                $data['merchandise'] = $article->product->description;
                $data['producer'] = $article->product->producer->description;
                break;
            default:
        }
        if ($article->description) {
            $data[strtolower($article->article_nature->name ?? '')] = $article->description;
        }
        $siblings = self::getSiblingsDescriptions($article->id);
        if ($siblings) {
            array_push($data, $siblings);
        }
        /*
        $data['resume'] = ($data['semences'] ?? null) .
            ($data['plants'] ?? null) .
            ($data['variety'] ?? null) .
            ($data['merchandise'] ?? null) .
            ($data['plus'] ?? null);
        */
        $data['description'] = $article->description;

        return $data;
    }

    public static function getArticlesByHomepage()
    {
        $shelves = Categories::getByHomepage();
        foreach ($shelves as $shelve) {
            $data[] = [
                'id' => $shelve->id,
                'name' => $shelve->name,
                'articles' => self::getArticlesToSell([
                    'category_id' => $shelve->id,
                    'homepage' => true,
                ]),
            ];
        }

        return $data ?? [];
    }

    public static function getArticlesToSell($options)
    {
        $articles = self::getArticlesWithOffers($options);
        foreach ($articles as $article) {
            $price_lists = $article->offers[0]->tariff->price_lists->toArray();
            if (! count($price_lists)) {
                continue;
            }
            if (! is_array($data[$article->name] ?? false)) {
                $data[$article->name] = self::getDataForSale($article);
            }
            $prices = $price_lists[0]['price_list_values'][0];
            $article_nature_name = strtolower($article->article_nature->name);
            $data[$article->name][$article_nature_name] = self::getDataPriceForSale($article, $prices);
        }
        if ($data ?? false) {
            ksort($data);
        }

        return $data ?? false;
    }

    public static function getDataForSale($article)
    {
        return [
            'id' => $article->id,
            'article_nature_id' => $article->article_nature_id,
            'description' => $article->description ? $article->description : $article->product->description,
            'image' => self::getFullImageByArticle($article),
            'product_type' => $article->product_type,
            'product_id' => $article->product_id,
            'product_name' => $article->product->name,
            'parent_name' => trim(str_replace($article->product->name, '', $article->name)),
            'offers' => $article->offers->toArray(),
        ];
    }

    public static function getDataPriceForSale($article, $prices)
    {
        return [
            'article_id' => $article->id,
            'offer_id' => $article->offers[0]->id,
            'quantity' => $prices['quantity'],
            'price' => $prices['price_taxed'],
            'variation' => $article->offers[0]->variation->name,
        ];
    }

    public static function getArticlesWithOffers($options = false)
    {
        $saleChannelId = $options['sale_channel_id'] ?? SaleChannels::getDefaultID();
        $model = self::getModelByOptions($options);
        $data = $model->withAvailableOffers($saleChannelId)->with([
            'image',
            'product',
            'article_nature',
            'offers' => function ($query) use ($saleChannelId) {
                $query->bySaleChannel($saleChannelId);
            },
            'offers.tariff' => function ($query) use ($saleChannelId) {
                $query->bySaleChannel($saleChannelId);
            },
            'offers.tariff.price_lists' => function ($query) use ($saleChannelId) {
                $query->where('sale_channel_id', $saleChannelId);
            },
            'offers.tariff.price_lists.price_list_values',
            'offers.variation.package',
        ])->get();

        return $data;
    }

    public static function getArticleNaturesOptionsWithOffers($options = false)
    {
        $ids = self::getArticleNaturesIdsWithOffers($options);
        
    }

    public static function getArticleNaturesWithOffers($options = false)
    {
        return ArticleNatures::getNamesByIds(self::getArticleNaturesIdsWithOffers($options));
    }

    public static function getArticleNaturesIdsWithOffers($options = false)
    {
        $saleChannelId = $options['sale_channel_id'] ?? SaleChannels::getDefaultID();
        $model = self::getModelByOptions($options);
        $data = $model->withAvailableOffers($saleChannelId)->get()->pluck('article_nature_id')->unique();

        return array_values($data->toArray());
    }

    public static function getProductTypesWithOffers($options = false)
    {
        $data = [];
        $classes = self::getProductTypesClassesWithOffers($options);
        foreach ($classes as $class) {
            $type = ArticleNatures::getProductTypeNameByClass($class);
            $data[$type] = true;
        }

        return array_keys($data);
    }

    public static function getProductTypesClassesWithOffers($options = false)
    {
        $saleChannelId = $options['sale_channel_id'] ?? SaleChannels::getDefaultID();
        $model = self::getModelByOptions($options);
        $data = $model->withAvailableOffers($saleChannelId)->get()->pluck('product_type')->unique();

        return $data->toArray();
    }

    public static function getModelByOptions($options = false)
    {
        $category_id = $options['category_id'] ?? false;
        $search = $options['search'] ?? false;
        $tags = $options['tags'] ?? false;
        $article_nature_id = $options['article_nature_id'] ?? false;
        $article_nature_ids = $options['article_nature_ids'] ?? false;
        $product_type = $options['product_type'] ?? false;

        $model = ($options['homepage'] ?? false) ? Article::homepage()->visible() : Article::visible();
        $model = $category_id ? $model->byCategoryParent($category_id) : $model;
        $model = $tags ? $model->byTagsSelected($tags) : $model;
        $model = $search ? $model->search($search) : $model;
        $model = $article_nature_id ? $model->byArticleNature($article_nature_id) : $model;
        $model = $article_nature_ids ? $model->byArticleNatures($article_nature_ids) : $model;
        switch ($product_type) {
            case 'botanic':
                $model = $model->botanic();
                break;
            case 'merchandise':
                $model = $model->merchandise();
                break;
        }

        return $model;
    }

    public static function getFull($id)
    {
        $data['article'] = self::getArticleEdit($id);
        self::getMeta($data);

        return $data;
    }

    public static function getArticleEdit($id)
    {
        $article = self::get($id);
        $data = $article->toArray();
        $data['inherited'] = self::getInherited($id);
        $data['categories'] = self::getCategoriesByArticle($article);
        $data['tags'] = self::getTagsByArticle($article);
        $data['comments'] = Comments::getByModel($article);

        return $data;
    }

    public static function getInherited($id)
    {
        $article = Article::with('product.tags.tag_group')->findOrFail($id);

        return self::getInheritedByProduct($article->product_id, $article->product_type);
    }

    public static function getInheritedByProduct($product_id, $product_type)
    {
        switch ($product_type) {
            case 'App\Models\Botanic\Variety':
                $product = Varieties::get($product_id);
                if (!$product) {
                    break;
                }
                $data[] = [
                    'name' => 'Espèces',
                    'description' => Species::getDescription($product->specie_id),
                    'tags' => Species::getTags($product->specie_id),
                ];
                $data[] = [
                    'name' => 'Variétés',
                    'description' => $product->description,
                    'tags' => $product->tags->toArray(),
                ];
                break;
            case 'App\Models\Botanic\Specie':
                $product = Species::get($product_id);
                if (!$product) {
                    break;
                }
                $data[] = [
                    'name' => 'Espèces',
                    'description' => $product->description,
                    'tags' => $product->tags->toArray(),
                ];
                break;
            case 'App\Models\Shop\Merchandise':
                $product = Merchandises::get($product_id);
                if (!$product) {
                    break;
                }
                $data[] = [
                    'name' => 'Marchandise',
                    'description' => $product->description,
                    'tags' => $product->tags->toArray(),
                ];
                break;
        }

        return $data ?? false;
    }

    public static function getInheritedImagesByProduct($product_id, $product_type)
    {
        switch ($product_type) {
            case 'App\Models\Botanic\Variety':
                $images = Varieties::getImages($product_id);
                break;
            case 'App\Models\Botanic\Specie':
                $images = Species::getImages($product_id);
                break;
            case 'App\Models\Shop\Merchandise':
                $images = Merchandises::getImages($product_id);
                break;
        }

        return $images ?? false ? ['images' => $images] : false;
    }

    public static function getMeta(&$data = [])
    {
        switch ($data['article']['product_type'] ?? false) {
            case 'App\Models\Botanic\Variety':
                $data['products'] = Varieties::getOptionsWithSpecie();
                break;
            case 'App\Models\Botanic\Specie':
                $data['products'] = Species::getOptions();
                break;
            case 'App\Models\Shop\Merchandise':
                $data['products'] = Merchandises::getOptions();
                break;
            default:
                $data['products'] = [];
        }

        $data['categories_options'] = Categories::getOptions();
        $data['natures_options'] = ArticleNatures::getOptions();
        // $data['packages'] = ($data['article']['article_family_id'] ?? false) ? Packages::getSelectByFamily($data['article']['article_family_id']) : [];
        $data['tags_list'] = TagGroups::getTreeTags();
        $data['models_options'] = [
            'App\Models\Botanic\Specie' => 'Espèces',
            'App\Models\Botanic\Variety' => 'Variétés',
            'App\Models\Shop\Merchandise' => 'Marchandise',
        ];

        return $data;
    }

    public static function getByCategory($category_id)
    {
        return Article::byCategory($category_id)->with(['prices', 'product', 'image'])->get();
    }

    public static function getCategoriesByArticle($article)
    {
        return $article->categories->pluck('id')->toArray();
    }

    public static function getProductTypeByCategory($category_id)
    {
        $models = self::getProductTypesModelsByCategory($category_id);

        return (($models[0] ?? false) == Merchandise::class) ? 'merchandise' : 'botanic';
    }

    public static function getProductTypesModelsByCategory($category_id)
    {
        return Article::byCategory($category_id)->select('product_type')->distinct()->get();
    }

    public static function countProductTypesByCategory($category_id)
    {
        return Article::byCategory($category_id)->select('product_type')->distinct()->count();
    }

    public static function getCategoriesNameByArticle($article)
    {
        return $article->categories->pluck('name', 'id')->toArray();
    }

    public static function getTagsByArticle($article)
    {
        return $article->tags->pluck('id')->toArray();
    }

    public static function getTagsNameByArticle($article)
    {
        return $article->tags->pluck('name', 'id')->toArray();
    }

    public static function getTagsSlugByArticle($article)
    {
        return $article->tags->pluck('slug', 'id')->toArray();
    }

    public static function getFullTagsSlugByArticle($article)
    {
        $data = [];

        switch ($article->product_type) {
            case 'App\Models\Botanic\Variety':
                $data += $article->product->tags->toArray();
                if ($article->product->specie ?? false) {
                    $data += $article->product->specie->tags->toArray();
                }
                break;
            case 'App\Models\Botanic\Specie':
                $data += $article->product->tags->toArray();
                break;
            case 'App\Models\Shop\Merchandise':
                $data += $article->product->tags->toArray();
                $data += $article->product->producer->tags->toArray();
                break;
            default:
        }
        $data += $article->tags->toArray();

        foreach ($data as $tag) {
            if (! isset($tags[$tag['group']][$tag['name']])) {
                $tags[$tag['group']][] = $tag['name'];
            }
        }

        return $tags ?? null;
    }

    public static function getPricesByArticle($article)
    {
        return Prices::getByArticle($article->id);
    }

    public static function getFullImagesByArticleId($id)
    {
        $article = self::get($id);

        return $article ? self::getFullImagesByArticle($article) : false;
    }

    public static function countFullImagesByArticleId($id)
    {
        $article = self::get($id);

        return $article ? self::countFullImagesByArticle($article) : 0;
    }

    public static function countFullImagesByArticle($article)
    {
        return count(self::getFullImagesByArticle($article));
    }

    public static function getFullImagesByArticle($article)
    {
        $images = count($article->images) ? $article->images : collect([]);
        switch ($article->product_type) {
            case 'App\Models\Botanic\Variety':
                $variety = $article->product ?? false;
                $specie = $variety->specie ?? false;
                $images = $variety ? (count($variety->images ?? []) ? $images->merge($variety->images) : $images) : $images;
                $images = $specie ? (count($specie->images ?? []) ? $images->merge($specie->images) : $images) : $images;
                break;
            case 'App\Models\Botanic\Specie':
                $specie = $article->product ?? false;
                $images = count($specie->images ?? []) ? $specie->images : $images;
                break;
            case 'App\Models\Shop\Merchandise':
                $merchandise = $article->product ?? false;
                $images = count($merchandise->images ?? []) ? $merchandise->images : $images;
                break;
        }

        return $images;
    }

    public static function getFullImageById($id)
    {
        return self::getFullImageByArticle(self::get($id));
    }

    public static function getFullImageByArticle($article)
    {
        $image = $article->image;
        if ($image) {
            return $image;
        }
        switch ($article->product_type) {
            case 'App\Models\Botanic\Variety':
                $image = $article->product->image ?? ($article->product->specie->image ?? false);
                break;
            case 'App\Models\Botanic\Specie':
                $image = $article->product->image ?? false;
                break;
            case 'App\Models\Shop\Merchandise':
                $image = $article->product->image ?? false;
                break;
        }

        return $image;
    }

    public static function storeFull($data)
    {
        $images = $data['images'] ?? false;
        unset($data['images']);

        $categories = $data['categories'] ?? false;
        unset($data['categories']);

        $tags = $data['tags'] ?? false;
        unset($data['tags']);

        $prices = $data['prices'] ?? false;
        unset($data['prices']);

        $article = self::store($data);
        self::storeImages($article, $images);
        self::storeCategories($article, $categories);
        self::storeTags($article, $tags);

        return $article->id;
    }

    public static function storeCategories($article, $categories)
    {
        if (! $categories) {
            return false;
        }
        $categories = collect($categories)->transform(
            function ($item, $key) {
                return (int) $item;
            }
        )->toArray();

        return $article->syncCategories($categories, true);
    }

    public static function storeTags($article, $tags)
    {
        return Tag::storeTags($article, $tags);
    }

    public static function toggleVisible($id, $visible)
    {
        return self::update(['visible' => $visible], $id);
    }

    public static function toggleHomepage($id, $homepage)
    {
        return self::update(['homepage' => $homepage], $id);
    }

    public static function getNumericHash($id)
    {
        return hexdec(self::getHash($id));
    }

    public static function getHash($id)
    {
        $name = self::get($id)->name ?? false;

        return $name ? hash('crc32c', Str::slug($name)) : false;
    }

    public static function getModel()
    {
        return Article::query();
    }
}
