<?php

namespace Database\Seeders;

use Botble\Base\Enums\BaseStatusEnum;
use Botble\Base\Facades\MetaBox;
use Botble\Base\Supports\BaseSeeder;
use Botble\Ecommerce\Enums\ProductTypeEnum;
use Botble\Ecommerce\Models\Order;
use Botble\Ecommerce\Models\OrderAddress;
use Botble\Ecommerce\Models\OrderHistory;
use Botble\Ecommerce\Models\OrderProduct;
use Botble\Ecommerce\Models\Product;
use Botble\Ecommerce\Models\ProductFile;
use Botble\Ecommerce\Models\ProductVariation;
use Botble\Ecommerce\Models\ProductVariationItem;
use Botble\Ecommerce\Models\Shipment;
use Botble\Ecommerce\Models\ShipmentHistory;
use Botble\Ecommerce\Models\Wishlist;
use Botble\Ecommerce\Services\Products\StoreProductService;
use Botble\Payment\Models\Payment;
use Botble\Slug\Facades\SlugHelper;
use Botble\Slug\Models\Slug;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class ProductSeeder extends BaseSeeder
{
    public function run(): void
    {
        $this->uploadFiles('products');

        $products = [
            'Miko Wooden Bluetooth Speaker',
            'Gorgeous Wooden Gloves',
            'Pinkol Enormous Granite Bottle',
            'Gorgeous Aluminum Table',
            'Evo Lightweight Granite Shirt',
            'CLCo. Incredible Paper Car',
            'Progash Durable Granite Hat',
            'Purab Enormous Miranda Bottle',
            'Miklonda Co. Crafted Candles',
            'Pinkol Enormous Granite Bottle',
            'Dual Camera 20MP',
            'Smart Watches',
            'Beat Headphone',
            'Red & Black Headphone',
            'Smart Watch External',
            'Nikon HD camera',
            'Audio Equipment',
            'Smart Televisions',
            'Samsung Smart Phone',
            'Herschel Leather Duffle Bag In Brown Color',
            'Xbox One Wireless Controller Black Color',
            'EPSION Plaster Printer',
            'Sound Intone I65 Earphone White Version',
            'B&O Play Mini Bluetooth Speaker',
            'Apple MacBook Air Retina 13.3-Inch Laptop',
            'Apple MacBook Air Retina 12-Inch Laptop',
            'Samsung Gear VR Virtual Reality Headset',
            'Aveeno Moisturizing Body Shower 450ml',
            'NYX Beauty Couton Pallete Makeup 12',
            'NYX Beauty Couton Pallete Makeup 12',
            'MVMTH Classical Leather Watch In Black',
            'Baxter Care Hair Kit For Bearded Mens',
            'Ciate Palemore Lipstick Bold Red Color',
            'Vimto Squash Remix Apple 1.5 Litres',
            'Crock Pot Slow Cooker',
            'Taylors of Harrogate Yorkshire Coffee',
            'Soft Mochi & Galeto Ice Cream',
            'Naked Noodle Egg Noodles Singapore',
            'Saute Pan Silver',
            'Bar S – Classic Bun Length Franks',
            'Broccoli Crowns',
            'Slimming World Vegan Mac Greens',
            'Häagen-Dazs Salted Caramel',
            'Iceland 3 Solo Exotic Burst',
            'Extreme Budweiser Light Can',
            'Iceland Macaroni Cheese Traybake',
            'Dolmio Bolognese Pasta Sauce',
            'Sitema BakeIT Plastic Box',
            'Wayfair Basics Dinner Plate Storage',
            'Miko The Panda Water Bottle',
            'Sesame Seed Bread',
            'Morrisons The Best Beef',
            'Avocado, Hass Large',
            'Italia Beef Lasagne',
            'Maxwell House Classic Roast Mocha',
            'Bottled Pure Water 500ml',
            'Famart Farmhouse Soft White',
            'Coca-Cola Original Taste',
            'Casillero Diablo Cabernet Sauvignon',
            'Arla Organic Free Range Milk',
            'Aptamil Follow On Baby Milk',
            'Cuisinart Chef’S Classic Hard-Anodized',
            'Corn, Yellow Sweet',
            'Hobnobs The Nobbly Biscuit',
            'Honest Organic Still Lemonade',
            'Ice Beck’s Beer 350ml x 24 Pieces',
            'Iceland 6 Hot Cross Buns',
            'Iceland Luxury 4 Panini Rolls',
            'Iceland Soft Scoop Vanilla',
            'Iceland Spaghetti Bolognese',
            'Kellogg’s Coco Pops Cereal',
            'Kit Kat Chunky Milk Chocolate',
            'Large Green Bell Pepper',
            'Pice 94w Beasley Journal',
            'Province Piece Glass Drinking Glass',
        ];

        Product::query()->truncate();
        DB::table('ec_product_with_attribute_set')->truncate();
        DB::table('ec_product_variations')->truncate();
        DB::table('ec_product_variation_items')->truncate();
        DB::table('ec_product_collection_products')->truncate();
        DB::table('ec_product_label_products')->truncate();
        DB::table('ec_product_category_product')->truncate();
        DB::table('ec_product_related_relations')->truncate();
        Wishlist::query()->truncate();
        Order::query()->truncate();
        OrderAddress::query()->truncate();
        OrderProduct::query()->truncate();
        OrderHistory::query()->truncate();
        Shipment::query()->truncate();
        ShipmentHistory::query()->truncate();
        Payment::query()->truncate();
        ProductFile::query()->truncate();

        foreach ($products as $key => $product) {
            $item = [
                'name' => $product,
            ];

            $item['description'] = '<p>Short Hooded Coat features a straight body, large pockets with button flaps, ventilation air holes, and a string detail along the hemline.</p>';
            $item['content'] = '<p>Short Hooded Coat features a straight body, large pockets with button flaps, ventilation air holes, and a string detail along the hemline. The style is completed with a drawstring hood, featuring Rains&rsquo; signature built-in cap. Made from waterproof, matte PU, this lightweight unisex rain jacket is an ode to nostalgia through its classic silhouette and utilitarian design details.</p>
                                <p>- Casual unisex fit</p>

                                <p>- 64% polyester, 36% polyurethane</p>

                                <p>- Water column pressure: 4000 mm</p>

                                <p>- Model is 187cm tall and wearing a size S / M</p>

                                <p>- Unisex fit</p>

                                <p>- Drawstring hood with built-in cap</p>

                                <p>- Front placket with snap buttons</p>

                                <p>- Ventilation under armpit</p>

                                <p>- Adjustable cuffs</p>

                                <p>- Double welted front pockets</p>

                                <p>- Adjustable elastic string at hempen</p>

                                <p>- Ultrasonically welded seams</p>

                                <p>This is a unisex item, please check our clothing &amp; footwear sizing guide for specific Rains jacket sizing information. RAINS comes from the rainy nation of Denmark at the edge of the European continent, close to the ocean and with prevailing westerly winds; all factors that contribute to an average of 121 rain days each year. Arising from these rainy weather conditions comes the attitude that a quick rain shower may be beautiful, as well as moody- but first and foremost requires the right outfit. Rains focus on the whole experience of going outside on rainy days, issuing an invitation to explore even in the most mercurial weather.</p>';
            $item['status'] = BaseStatusEnum::PUBLISHED;
            $item['sku'] = 'NC-' . rand(100, 200);
            $item['brand_id'] = rand(1, 7);
            $item['views'] = rand(1000, 200000);
            $item['quantity'] = rand(10, 20);
            $item['length'] = rand(10, 20);
            $item['wide'] = rand(10, 20);
            $item['height'] = rand(10, 20);
            $item['weight'] = rand(500, 900);
            $item['with_storehouse_management'] = true;

            $item['price'] = rand(200, 500);
            $item['sale_price'] = rand(150, 200);
            $item['is_featured'] = (bool) rand(0, 1);

            // Support Digital Product
            $productName = $item['name'];
            if ($key % 4 == 0) {
                $item['product_type'] = ProductTypeEnum::DIGITAL;
            }

            $images = [];

            foreach (Arr::random(range(1, 95), rand(5, 12)) as $i) {
                $images[] = "products/product-$i.jpg";
            }

            $item['images'] = json_encode($images);

            $product = Product::query()->create($item);

            $product->productCollections()->sync([rand(1, 3)]);

            if (is_int($product->id) && $product->id % 7 == 0) {
                $product->productLabels()->sync([rand(1, 3)]);
            }

            $product->categories()->sync([
                rand(1, 14),
            ]);

            $product->tags()->sync([
                rand(1, 6),
                rand(1, 6),
                rand(1, 6),
            ]);

            $product->taxes()->sync([1]);

            Slug::query()->create([
                'reference_type' => Product::class,
                'reference_id' => $product->id,
                'key' => Str::slug($productName),
                'prefix' => SlugHelper::getPrefix(Product::class),
            ]);

            MetaBox::saveMetaBoxData(
                $product,
                'faq_schema_config',
                json_decode(
                    '[[{"key":"question","value":"What Shipping Methods Are Available?"},{"key":"answer","value":"Ex Portland Pitchfork irure mustache. Eutra fap before they sold out literally. Aliquip ugh bicycle rights actually mlkshk, seitan squid craft beer tempor."}],[{"key":"question","value":"Do You Ship Internationally?"},{"key":"answer","value":"Hoodie tote bag mixtape tofu. Typewriter jean shorts wolf quinoa, messenger bag organic freegan cray."}],[{"key":"question","value":"How Long Will It Take To Get My Package?"},{"key":"answer","value":"Swag slow-carb quinoa VHS typewriter pork belly brunch, paleo single-origin coffee Wes Anderson. Flexitarian Pitchfork forage, literally paleo fap pour-over. Wes Anderson Pinterest YOLO fanny pack meggings, deep v XOXO chambray sustainable slow-carb raw denim church-key fap chillwave Etsy. +1 typewriter kitsch, American Apparel tofu Banksy Vice."}],[{"key":"question","value":"What Payment Methods Are Accepted?"},{"key":"answer","value":"Fashion axe DIY jean shorts, swag kale chips meh polaroid kogi butcher Wes Anderson chambray next level semiotics gentrify yr. Voluptate photo booth fugiat Vice. Austin sed Williamsburg, ea labore raw denim voluptate cred proident mixtape excepteur mustache. Twee chia photo booth readymade food truck, hoodie roof party swag keytar PBR DIY."}],[{"key":"question","value":"Is Buying On-Line Safe?"},{"key":"answer","value":"Art party authentic freegan semiotics jean shorts chia cred. Neutra Austin roof party Brooklyn, synth Thundercats swag 8-bit photo booth. Plaid letterpress leggings craft beer meh ethical Pinterest."}]]',
                    true
                )
            );
        }

        $countProducts = count($products);

        foreach ($products as $key => $item) {
            $product = Product::query()->skip($key)->first();
            $product->productAttributeSets()->sync([1, 2]);

            $product->crossSales()->sync([
                $this->random(1, $countProducts, [$product->id]),
                $this->random(1, $countProducts, [$product->id]),
                $this->random(1, $countProducts, [$product->id]),
                $this->random(1, $countProducts, [$product->id]),
            ]);

            $upSaleProductIds = array_unique([
                $this->random(1, $countProducts, [$product->id]),
                $this->random(1, $countProducts, [$product->id]),
            ]);

            $upSaleSyncData = [];
            foreach ($upSaleProductIds as $upSaleProductId) {
                $isPercentDiscount = (bool) rand(0, 1);
                $upSaleSyncData[$upSaleProductId] = [
                    'price' => $isPercentDiscount ? rand(5, 20) : rand(5, 50),
                    'price_type' => $isPercentDiscount ? 'percent' : 'fixed',
                ];
            }

            $product->upSales()->sync($upSaleSyncData);

            for ($j = 0; $j < rand(1, 5); $j++) {
                $variation = Product::query()->create([
                    'name' => $product->name,
                    'status' => BaseStatusEnum::PUBLISHED,
                    'sku' => $product->sku . '-A' . $j,
                    'quantity' => $product->quantity,
                    'weight' => $product->weight,
                    'height' => $product->height,
                    'wide' => $product->wide,
                    'length' => $product->length,
                    'price' => $product->price,
                    'sale_price' => is_int(
                        $product->id
                    ) && $product->id % 4 == 0 ? ($product->price - $product->price * rand(10, 30) / 100) : null,
                    'brand_id' => $product->brand_id,
                    'with_storehouse_management' => $product->with_storehouse_management,
                    'is_variation' => true,
                    'images' => json_encode([$product->images[$j] ?? Arr::first($product->images)]),
                    'product_type' => $product->product_type,
                ]);

                $productVariation = ProductVariation::query()->create([
                    'product_id' => $variation->id,
                    'configurable_product_id' => $product->id,
                    'is_default' => $j == 0,
                ]);

                if ($productVariation->is_default) {
                    $product->update([
                        'sku' => $variation->sku,
                        'sale_price' => $variation->sale_price,
                    ]);
                }

                ProductVariationItem::query()->create([
                    'attribute_id' => rand(1, 5),
                    'variation_id' => $productVariation->id,
                ]);

                ProductVariationItem::query()->create([
                    'attribute_id' => rand(6, 10),
                    'variation_id' => $productVariation->id,
                ]);

                if ($product->isTypeDigital()) {
                    foreach ($product->images as $img) {
                        $productFile = database_path('seeders/files/' . $img);

                        if (! File::isFile($productFile)) {
                            continue;
                        }

                        $fileUpload = new UploadedFile(
                            $productFile,
                            Str::replace('products/', '', $img),
                            'image/jpeg',
                            null,
                            true
                        );
                        $productFileData = app(StoreProductService::class)->saveProductFile($fileUpload);
                        $variation->productFiles()->create($productFileData);
                    }
                }
            }
        }
    }
}
