File "ValidateCoupon.php"

Full Path: /home/clickysoft/public_html/jmapi5.clickysoft.net/app/Rules/ValidateCoupon.php
File size: 869 bytes
MIME-type: text/x-php
Charset: utf-8

<?php

namespace App\Rules;

use App\Models\Coupon;
use Illuminate\Contracts\Validation\InvokableRule;

class ValidateCoupon implements InvokableRule
{
    public function __invoke($attribute, $value, $fail)
    {
        $coupon = Coupon::where('code', $value)->where('status', 1)->first();
        $message = "";
        if ($coupon) {
            if ($coupon->expiry_date) {
                $day_end = $coupon->expiry_date->endOfDay();
                if (!now()->lte($day_end)) {
                    $message = "Coupon has expired.";
                }
            }

            if ($coupon->number_of_usage > 0 && $coupon->redemption_count >= $coupon->number_of_usage) {
                $message = "Coupon usage limit reached.";
            }
        } else {
            $message = "Invalid coupon code";
        }

        if ($message) $fail($message);
    }
}