<?php

namespace CouponsPlus\App\Conditions\BuiltIn\Conditions;

use CouponsPlus\App\Conditions\Condition;
use CouponsPlus\Original\Collections\Collection;
use CouponsPlus\Original\Collections\Mapper\Types;

#[\AllowDynamicProperties]
Class CouponUsageNumberOfTimesPerUser extends Condition
{
    const TYPE = 'CouponUsageNumberOfTimesPerUser';

    static public function getName() : string
    {
        return __('Usage Limits per User', 'coupons-plus-for-woocommerce');
    }

    static public function getDescription() : string
    {
        return 'Restrict the number of times this coupon can be used by each customer';
    }
    
    static public function getUseCases(): Collection
    {
        return new Collection([
            __('Limit to 1 per customer', 'coupons-plus-for-woocommerce'),
        ]);    
    } 

    // desc:
    // USER MUST BE LOGGED IN (AKA HAVE AN ACCOUNT) FOR THESE CHECKS TO WORK, 
    // IF THE USER IS NOT LOGGED IN (AKA A SIMPLE GUEST/VISITOR), THIS CONDITION WILL ALWAYS FAIL REGARDLESS OF 
    // THE OPTIONS SET.
    public static function getOptions() : Collection
    {
        return new Collection([
            'quantity' => [
                'type' => Types::STRING()->allowed([
                    __('Maximum', 'coupons-plus-for-woocommerce') => 'maximum',
                ]),
                'amount' => Types::INTEGER()->meta([
                    'name' => '',
                ])->withDefault(1),
            ],
        ]);
    }

    protected function test() : bool
    {
        (integer) $userId = get_current_user_id();
        (integer) $maxUsagePerUser = $this->options->quantity->amount;

        if (!$userId) {
            return false;
        }

        if (
            !$this->coupon
            || !$this->coupon->get_id()
            || !$this->coupon->get_data_store()
        ) {
            return false;
        }


        if (!apply_filters(
            'woocommerce_coupon_validate_user_usage_limit',
            $maxUsagePerUser > 0,
            $userId,
            $this->coupon,
            $this
        )) {
            return false;
        }


        (integer) $usageCount = $this->coupon->get_data_store()->get_usage_by_user_id(
            $this->coupon,
            $userId
        );

        return $usageCount < $maxUsagePerUser;
    }
}
