<?php

namespace App\Repositories\Shop;

use App\Models\Shop\Article;
use App\Repositories\Botanic\Species;
use App\Repositories\Botanic\Varieties;
use App\Repositories\Shop\SaleChannels;
use App\Repositories\Shop\Customers;
use Illuminate\Support\Facades\Schema;
use App\Repositories\Core\Comments;
use App\Traits\Model\Basic;
use App\Traits\Repository\Imageable;
use Illuminate\Support\Str;

class Articles
{
    use Basic, Imageable;

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

        return $export;
    }

    public static function getIDBySlug($slug)
    {
        return Article::bySlug($slug)->first()->id;
    }

    public static function getOffersGroupedByNature($id, $saleChannelId = false)
    {
        $articleIds = ArticleSiblings::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(),
                'stock' => $offer->stock_current !== null ? (int) $offer->stock_current : null,
            ];
        }

        return $data ?? false;
    }

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

    public static function getOptionsWithNature()
    {
        $data = [];
        $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 getVisibilityMap()
    {
        return Article::pluck('visible', 'id')->toArray();
    }

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

    public static function getArticleToSell($id, $saleChannelId = false)
    {
        $saleChannelId = $saleChannelId ?: SaleChannels::getDefaultID();
        $sessionSaleChannelId = session('shop.default_sale_channel_id');
        $customer = Customers::getAuth();
        $hasDefaultSaleChannelColumn = Schema::hasColumn('shop_customers', 'default_sale_channel_id');
        $customerDefaultSaleChannelId = ($customer && $hasDefaultSaleChannelColumn)
            ? $customer->default_sale_channel_id
            : null;
        $customerSaleChannelIds = [];

        if ($customer) {
            $customer->loadMissing('sale_channels:id');
            $customerSaleChannelIds = $customer->sale_channels->pluck('id')->toArray();
        }
        $data = self::getArticle($id);
        $data['offers'] = self::getOffersGroupedByNature($id, $saleChannelId);

        $currentSaleChannel = $saleChannelId ? SaleChannels::get($saleChannelId) : null;
        $data['current_sale_channel'] = $currentSaleChannel ? $currentSaleChannel->toArray() : null;
        $data['available_sale_channels'] = Offers::getSaleChannelsForArticle($id);
        $data['debug_sale_channel'] = [
            'session_default_sale_channel_id' => $sessionSaleChannelId,
            'customer_default_sale_channel_id' => $customerDefaultSaleChannelId,
            'customer_linked_sale_channel_ids' => $customerSaleChannelIds,
            'resolved_sale_channel_id' => $saleChannelId,
            'has_default_sale_channel_column' => $hasDefaultSaleChannelColumn,
        ];

        return $data;
    }

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

        return $data;
    }

    public static function getFullDescriptionByArticle($article)
    {
        $data = [];
        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 ? $article->product->description : '';
                break;
            case 'App\Models\Shop\Merchandise':
                $merchandise = $article->product;
                $data['merchandise'] = $merchandise ? ($merchandise->description ?? '') : '';
                if ($merchandise && $merchandise->producer) {
                    $data['producer'] = $merchandise->producer->description ?? '';
                }
                break;
            default:
        }
        if ($article->description) {
            $data[strtolower($article->article_nature->name ?? '')] = $article->description;
        }
        $siblings = ArticleSiblings::getSiblingsDescriptions($article->id);
        if ($siblings) {
            array_push($data, $siblings);
        }
        $data['description'] = $article->description;

        return $data;
    }

    public static function getArticlesByHomepage()
    {
        $data = [];
        $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);
        $searchOrder = $options['ids'] ?? false ? array_flip($options['ids']->toArray()) : false;
        foreach ($articles as $article) {
            // Skip articles without an offer/tariff/price list for the resolved sale channel
            if (!isset($article->offers[0]) || ! $article->offers[0]->tariff) {
                continue;
            }

            $price_lists = $article->offers[0]->tariff->price_lists->toArray();
            if (! count($price_lists)) {
                continue;
            }
            if (empty($price_lists[0]['price_list_values'][0] ?? null)) {
                continue;
            }
            if (! is_array($data[$article->name] ?? false)) {
                $data[$article->name] = self::getDataForSale($article);
                if ($searchOrder) {
                    $data[$article->name]['searchOrder'] = $searchOrder[$article->id];
                }
            }
            $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 ?? [];
    }

    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' => ArticleImages::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(),
            'slug' => $article->slug,
        ];
    }

    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);

        return $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();
    }

    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)
    {
        $article_nature_id = $options['article_nature_id'] ?? false;
        $article_nature_ids = $options['article_nature_ids'] ?? false;

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

        return $model;
    }

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

        return self::getMeta($data);
    }

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

        return $data;
    }

    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['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 storeFull($data)
    {
        $images = $data['images'] ?? false;
        unset($data['images']);

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

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

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

        return $article->id;
    }

    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();
    }
}
