<?php

namespace App\Services\Models;

use App\Models\User;
use App\Models\Order;
use App\Models\Coupon;
use Illuminate\Support\Collection;

class CouponService
{
    public $message;
    public $response;

    public $discount_amount = 0;

    public function checkCoupon($coupon, User $user, $total, $cart = null)
    {
        $coupon = Coupon::where('code', $coupon)->first();

        if ($coupon == null) {
            $this->message = __('The coupon does not exist.');
            $this->response = false;
            return $this;
        }

        // Expire date
        if ($coupon->expire_date < now()) {
            $this->message = __(
                'The coupon is expired. Expire date: :expire_date | Today: :today',
                [
                    'expire_date' => $coupon->expire_date->format('Y-m-d'),
                    'today' => now()->format('Y-m-d'),
                ]
            );
            $this->response = false;
            return $this;
        }

        // Minimum spend
        if ($coupon->minimum_spend > $total) {
            $this->message = __(
                'The minimum requirement is not met. Minimum required: :minimum',
                ['minimum' => number_format($coupon->minimum_spend)]
            );
            $this->response = false;
            return $this;
        }

        // Usage limit
        $usage = Order::where('coupon_id', $coupon->code)->count();
        if ($coupon->usage_limit < $usage) {
            $this->message = __(
                'The coupon usage limit is reached. Limit: :limit',
                ['limit' => $coupon->usage_limit]
            );
            $this->response = false;
            return $this;
        }

        //usage_limit_per_user
        // $usage_per_user = Order::where('coupon', $coupon->code)->where('user_id', $user->id)->get()->count();
        // if ($coupon->usage_limit_per_user < $usage_per_user) {
        //     $this->message = 'The coupon usage limit is met for the current user. The usage limit is: ' . $coupon->usage_limit_per_user;
        //     $this->response = false;
        //     return $this;
        // }

        switch ($coupon->type) {
            case 'Percentage Discount':
                $discount = ($coupon->amount * $total)  / 100;
                $this->discount_amount = $coupon->max_discount != null && $discount > $coupon->max_discount ? $coupon->max_discount : $discount;
                break;
            case 'Fixed Cart Discount':
                $this->discount_amount = $coupon->max_discount !=  null && $coupon->amount > $coupon->max_discount ? $coupon->max_discount :  $coupon->amount;
                break;
            case 'Fixed Product Discount':
                # code...
                break;
        }

        $this->message = 'ok';
        $this->response = true;
        return $this;
    }
}
