<?php

namespace App\Traits;

use Tymon\JWTAuth\Facades\JWTAuth;

trait UserProductRestriction
{
    /**
     * List of restricted user emails
     */
    protected static $restrictedUserEmails = [
        'sdone@gmail.com',
        'sdtwo@gmail.com',
    ];

    /**
     * List of restricted product slugs
     */
    protected static $restrictedProductSlugs = [
        'morphia-mitra-next-generation-alkaloids-100mg-tablet-4x-serving-20ct-display',
        'pure-infinity-botanicals-premium-kava-extract-chewable-tablets-6ct-pack-18ct-display',
        'seven-roots-by-mamba-high-potency-kava-150mg-60ml-shot-12ct-box',
        'ketamind-euphoric-botanical-blend-675mg-3ct-pack-10ct-box',
        'pure-infinity-botanicals-premium-kava-powder-2oz',
        'pure-infinity-botanicals-premium-kava-powder-1kg',
        'pure-infinity-botanicals-premium-kava-powder-8oz',
        'pure-infinity-botanicals-fijian-kava-1kg-premium-powder',
        'relax-aid-dietary-supplements-2-capsules-x-6ct-box',
    ];

    /**
     * List of restricted product SKUs
     */
    protected static $restrictedProductSKUs = [
        'MORPHIAMITRA',
        'PIBKAVATAB6CT',
        'SRKAVA150MGSHT',
        'KETAMIND675MG',
        'PIBKAVA2OZ',
        'PIBKAVA1KG',
        'PIBKAVA8OZ',
        'PIBFIJIKAVA1KG',
        'RELAXAID2CAP6CT',
    ];

    /**
     * Check if the current authenticated user is a restricted user
     *
     * @return array ['isRestricted' => bool, 'userEmail' => string|null]
     */
    protected function checkRestrictedUser()
    {
        try {
            $user = JWTAuth::parseToken()->authenticate();
            if ($user && $user->user_email) {
                $isRestricted = in_array($user->user_email, self::$restrictedUserEmails);
                return [
                    'isRestricted' => $isRestricted,
                    'userEmail' => $user->user_email,
                    'user' => $user
                ];
            }
        } catch (\Throwable $th) {
            // User not authenticated
        }
        
        return [
            'isRestricted' => false,
            'userEmail' => null,
            'user' => null
        ];
    }

    /**
     * Check if a product slug is restricted
     *
     * @param string $slug
     * @return bool
     */
    protected function isProductSlugRestricted($slug)
    {
        return in_array($slug, self::$restrictedProductSlugs);
    }

    /**
     * Check if a product SKU is restricted
     *
     * @param string $sku
     * @return bool
     */
    protected function isProductSKURestricted($sku)
    {
        return in_array($sku, self::$restrictedProductSKUs);
    }

    /**
     * Get the list of restricted product slugs
     *
     * @return array
     */
    protected function getRestrictedProductSlugs()
    {
        return self::$restrictedProductSlugs;
    }

    /**
     * Get the list of restricted product SKUs
     *
     * @return array
     */
    protected function getRestrictedProductSKUs()
    {
        return self::$restrictedProductSKUs;
    }

    /**
     * Filter products collection to exclude restricted products for restricted users
     *
     * @param \Illuminate\Support\Collection $products
     * @param bool $isRestrictedUser
     * @return \Illuminate\Support\Collection
     */
    protected function filterRestrictedProducts($products, $isRestrictedUser)
    {
        if (!$isRestrictedUser) {
            return $products;
        }

        return $products->filter(function ($product) {
            $slug = $product->post_name ?? $product->slug ?? '';
            $sku = '';
            
            // Try to get SKU from meta
            if (isset($product->meta)) {
                $skuMeta = $product->meta->where('meta_key', '_sku')->first();
                $sku = $skuMeta ? $skuMeta->meta_value : '';
            }

            // Filter out if slug or SKU is restricted
            return !$this->isProductSlugRestricted($slug) && !$this->isProductSKURestricted($sku);
        });
    }

    /**
     * Apply restriction filter to a query builder for restricted users
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param bool $isRestrictedUser
     * @return \Illuminate\Database\Eloquent\Builder
     */
    protected function applyRestrictionToQuery($query, $isRestrictedUser)
    {
        if (!$isRestrictedUser) {
            return $query;
        }

        // Filter out restricted product slugs
        $query->whereNotIn('post_name', self::$restrictedProductSlugs);

        return $query;
    }
}
