<?php

namespace Modules\Subscription\Services;

use Modules\LMS\Enums\PurchaseType;
use Modules\LMS\Models\Purchase\PurchaseDetails;
use Modules\LMS\Repositories\Order\OrderRepository;
use Modules\Subscription\Models\Subscription\SubscriptionUse;
use Modules\LMS\Repositories\Courses\CourseRepository;
use Modules\LMS\Repositories\Courses\Bundle\BundleRepository;
use Modules\Subscription\Repositories\Subscription\SubscriptionRepository;

class SubscriptionService
{
    /**
     * Method getSubscription
     */
    public static function getSubscription()
    {
        $data = [];
        $subscriptionResponse = SubscriptionRepository::get(options: ['where' => ['status' => 1]]);
        if ($subscriptionResponse['status'] === 'success') {
            $data = $subscriptionResponse['data'] ?? [];
        }
        return $data;
    }

    /**
     *  getActiveSubscription
     *
     * @return object
     */
    public static function getActiveSubscription()
    {
        $activePlan = null;
        $subscription = null;
        $saleCreatedAt = null;
        $userId = authCheck()->id;

        $lastSubscriptionPurchase = PurchaseDetails::where('user_id', $userId)
            ->where('purchase_type', PurchaseType::SUBSCRIPTION)
            ->latest('created_at')
            ->first();

        if ($lastSubscriptionPurchase) {
            $subscription = $lastSubscriptionPurchase->subscription;
            $saleCreatedAt = $lastSubscriptionPurchase->created_at;
        }
        if (!empty($subscription) and !empty($saleCreatedAt)) {
            $useCount = SubscriptionUse::where('user_id', $userId)
                ->where('subscription_id', $subscription->id)
                ->whereHas('purchaseDetails', function ($query) use ($saleCreatedAt) {
                    $query->where('created_at', '>', $saleCreatedAt);
                })
                ->count();
            $subscription->used_count = $useCount;
            $countDayOfSale = (int) get_diff_timestamp_day(now(), $saleCreatedAt);
            if (($subscription->usable_count > $useCount || $subscription->infinite_use) && $subscription->days >= $countDayOfSale) {
                $activePlan = $subscription;
            }
        }
        return $activePlan;
    }

    /**
     *  getDayOfUse
     *
     * @return int
     */
    public static function getDayOfUse(): int
    {
        $userId = authCheck()->id;
        $lastSubscriptionSale = PurchaseDetails::where('user_id', $userId)
            ->where('purchase_type', PurchaseType::SUBSCRIPTION)
            ->latest('created_at')
            ->first();
        return $lastSubscriptionSale ? (int) get_diff_timestamp_day(now(), $lastSubscriptionSale->created_at) : 0;
    }

    /**
     *  diffTimestampDay
     *
     * @param string $firstTime
     * @param string $lastTime 
     */

    public static function applySubscription($slug, $type = "course")
    {
        $response =  match ($type) {
            'course' => $response = CourseRepository::first(
                value: $slug,
                field: 'slug',
                relations: [
                    'instructors',
                    'organization',
                    'courseSetting' => function ($query) {
                        $query->where('is_subscription', 1);
                    }
                ]
            ),
            'bundle' => $response = BundleRepository::first(
                value: $slug,
                field: 'slug',
                relations: [
                    'user',
                    'creator'
                ],

            ),
            default => $response = null,
        };
        $data = $response['data'] ?? null;
        if (!$data) {
            return [
                'status' => 'error',
                'message' => translate('There are no Subscription')
            ];
        }
        $subscription = self::getActiveSubscription();
        if (!$subscription) {
            return [
                'status' => 'error',
                'message' => translate('You have no active subscription')
            ];
        }

        $itemInfo = self::prepareData($data, $subscription, $type);
        $purchaseDetails =  OrderRepository::purchaseDetails($itemInfo);
        SubscriptionRepository::useSubscription(subscriptionId: $subscription->id, itemId: $data->id, saleId: $purchaseDetails->id, type: $type);
        $perSubscriptionPrice =  $subscription->price / $subscription->usable_count;

        if ($type != 'bundle') {
            OrderRepository::profitShareCalculate($data, $perSubscriptionPrice, $type = "subscription");
        } else {
            OrderRepository::bundleProfitShare($data, $perSubscriptionPrice, $type = "subscription");
        }
        return [
            'status' => 'success',
            'message' => translate('Enroll Successfully')
        ];
    }

    /**
     *  prepareData
     *
     * @param object $courseBundle
     * @param object $subscription
     * @param string $type
     */
    public static function prepareData($courseBundle, $subscription, $type = "course")
    {
        return [
            'purchase_number' => strtoupper(orderNumber()),
            'purchase_id' => null,
            'user_id' => authCheck()->id,
            'course_id' =>  $type == "course" ? $courseBundle->id : null, // for Course
            'bundle_id' =>  $type == "bundle" ? $courseBundle->id : null, // for bundle
            'subscription_id' => $subscription->id,
            'price' => 0,
            'platform_fee' => 0,
            'discount_price' =>  0,
            'details' => $courseBundle,
            'type' => PurchaseType::PURCHASE,
            'status' => 'processing',
            'purchase_type' =>  $type == "course" ? PurchaseType::COURSE : PurchaseType::BUNDLE,
        ];
    }
}
