<?php

namespace App\Helpers\FirstParty\Purchase;

use Illuminate\Support\Facades\App;

class PurchaseHelper
{
    public static function getPricingPageSubscriptions()
    {

        $subscriptions = self::getSubscriptions('subscription_plans', true, true);

        $subscriptions = self::filterShowInPricing($subscriptions);

        $subscriptions = self::setSystemPlan($subscriptions, 'stripe.current_stripe_price_id.month', 'stripe_monthly_price_id');

        $subscriptions = self::filterUnsetSystem($subscriptions);

        $subscriptions = self::reiterateArray($subscriptions);

        return $subscriptions;
    }

    public static function getPricingPageOneTime()
    {
        $one_time = self::getOneTimePurchases(true, true);

        $one_time = PurchaseHelper::filterShowInPricing($one_time);

        $one_time = PurchaseHelper::setSystemPlan($one_time, 'stripe.current_stripe_price_id', 'stripe_price_id');

        $one_time = PurchaseHelper::filterUnsetSystem($one_time);

        $one_time = self::reiterateArray($one_time);

        return $one_time;
    }

    public static function getSubscriptionPlanByStripePriceID($stripe_price_id)
    {
        $plans = self::getSubscriptions('subscription_plans', true, true);

        foreach ($plans as $plan) {

            if ($plan['id'] == 'free') {
                continue;
            }

            $stripe_price_ids = self::getPlanSystemProperty($plan, 'stripe.stripe_price_ids');

            if (is_array($stripe_price_ids)) {
                if (isset($stripe_price_ids['month']) && in_array($stripe_price_id, $stripe_price_ids['month'])) {
                    return $plan;
                }
                if (isset($stripe_price_ids['year']) && in_array($stripe_price_id, $stripe_price_ids['year'])) {
                    return $plan;
                }
            }
        }

        return null;
    }

    public static function getPlanSystemProperty($plan, $property)
    {
        // Get the environment (test or prod)
        $environment = self::getStripeEnvironment();

        // Split the property path
        $propertyParts = explode('.', $property);

        // Check if this is a stripe-related property that needs environment injection
        if (count($propertyParts) >= 2 && $propertyParts[0] === 'stripe') {
            // Inject environment into the path
            // stripe.product_id.month becomes system.stripe.product_id.{env}.month
            array_splice($propertyParts, 2, 0, $environment);
            $fullPath = 'system.'.implode('.', $propertyParts);
        } else {
            // For non-stripe properties, just prepend 'system.'
            $fullPath = 'system.'.$property;
        }

        return data_get($plan, $fullPath);
    }

    public static function getSubscriptions($type, $enabled = null, $system = false)
    {

        $tmp_subscriptions = config('platform.purchases.subscriptions');

        if (isset($enabled)) {

            $tmp_subscriptions = array_filter($tmp_subscriptions, function ($value) use ($type) {
                return $value['type'] == $type;
            });

            $tmp_subscriptions = array_filter($tmp_subscriptions, function ($value) use ($enabled) {
                return $value['enabled'] == $enabled;
            });

            if (! $system) {
                $tmp_subscriptions = array_map(function ($item) {

                    unset($item['system']);

                    return $item;
                }, $tmp_subscriptions);
            }
        }

        $env = App::environment();

        return $tmp_subscriptions;
    }

    public static function getOneTimePurchases(?bool $enabled, $system = false)
    {
        $tmp_otp = config('platform.purchases.one_time');

        if (isset($enabled)) {
            $tmp_otp = array_filter($tmp_otp, function ($value) use ($enabled) {
                return $value['enabled'] == $enabled;
            });
        }

        if (! $system) {
            $tmp_otp = array_map(function ($item) {

                unset($item['system']);

                return $item;
            }, $tmp_otp);
        }

        return $tmp_otp;
    }

    public static function setSystemPlan($arr, $property, $key_name)
    {
        foreach ($arr as $key => $item) {

            $arr[$key][$key_name] = PurchaseHelper::getPlanSystemProperty($item, $property);

            // $stripe_monthly_price_id = PurchaseHelper::getPlanSystemProperty($subscription, 'stripe.product_id.month');

            // $stripe_current_monthly_price_id = PurchaseHelper::getPlanSystemProperty($subscription, 'stripe.current_stripe_price_id.month');

            // $stripe_all_monthly_price_ids = PurchaseHelper::getPlanSystemProperty($subscription, 'stripe.stripe_price_ids.month');

            // dump($stripe_monthly_price_id);
            // dump($stripe_current_monthly_price_id);
            // dump($stripe_all_monthly_price_ids);
        }

        return $arr;
    }

    public static function filterUnsetSystem($arr)
    {
        return array_map(function ($item) {

            unset($item['system']);

            return $item;
        }, $arr);
    }

    public static function filterShowInPricing($arr)
    {
        return array_filter($arr, function ($item) {
            return $item['show_in_pricing'] == true;
        });
    }

    public static function getStripeEnvironment()
    {
        $env = App::environment();

        // Return 'prod' for production environment, 'test' for everything else
        return $env === 'production' ? 'prod' : 'test';
    }

    private static function reiterateArray($arr)
    {
        $tmp = [];

        foreach ($arr as $key => $item) {
            $tmp[] = $item;
        }

        return $tmp;
    }
}
