<?php

namespace Modules\Subscription\Traits;

use Modules\LMS\Enums\PurchaseType;
use Modules\Subscription\Models\Subscription\Subscription;
use Modules\Subscription\Models\Subscription\SubscriptionUse;

use function PHPSTORM_META\type;

trait PurchaseExpiryCheckTrait
{
    /**
     * Get the subscription used for a specific purchase.
     *
     * @param int $user_id
     * @param int $itemId
     * @param int $purchaseId
     * @return Subscription|null
     */
    public static function getUsedSubscription($user_id, $itemId, $purchaseId, $type = "course")
    {


        $subscription = null;
        $use = $use = SubscriptionUse::where('sale_id', $purchaseId)
            ->where($type === "course" ? 'course_id' : 'bundle_id', $itemId)
            ->where('user_id', $user_id)
            ->first();
        if (!empty($use)) {
            $subscription = Subscription::where('id', $use->subscription_id)->first();
        }
        return $subscription;
    }

    /**
     * Check if a purchase with a subscription has expired.
     *
     * @param int $itemId
     * @param string $itemName
     * @return bool
     */
    public static function checkExpiredPurchaseWithSubscription($purchaseId, $itemId, $type = "course")
    {
        $user_id = authCheck()->id;
        $result = true;
        $subscription = self::getUsedSubscription($user_id, $itemId, $purchaseId, $type);
        if (!empty($subscription)) {
            $subscriptionSale = self::where('user_id', $user_id)
                ->where('purchase_type', PurchaseType::SUBSCRIPTION)
                ->where('subscription_id', $subscription->id)
                ->latest('created_at')
                ->first();
            if (!empty($subscriptionSale)) {
                $usedDays = (int) get_diff_timestamp_day(now(), $subscriptionSale->created_at);
                if ($usedDays <= $subscription->days) {
                    $result = false;
                }
            }
        }
        return $result;
    }
}
