<?php
namespace App\Services\Product\Cobon\CobonWays;
use App\Models\CobonProduct;
use App\Models\CobonUser;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class CobonEventService implements CobonInterface
{
    public function calculate($content,$cobon)
    {
        $message =  __('web.invalid_cobon');
        $discount = 0;
        $status = null;
        $cobon_id = null;
        $commission = 0;
        
        if($cobon->status_user != 'all')
        {
            $check_user = false;
            $check_user = CobonUser::where('cobon_id',$cobon->id)->where('user_id',Auth::user()->id)->first();
            if($check_user)
            {
                $check_user = true;
            }
        }
        else
        {
            $check_user = true;
        }
        if(isset($content['product_id']))
        {
            if($cobon->status == 'all')
            {
                $check_product = true;
            }
            else
            {
                $check_product = CobonProduct::where('product_id',$content['product_id'])->where('cobon_id',$cobon->id)->first();
            }
        }
        else
        {
            $check_product =true;
        }
        
        if($check_product && $check_user)
        {
            $message = $cobon->currentDescription->name;
            if($cobon->discount_type == 1)
            {
                $discount = $cobon->discount_amount;
            }
            else
            {
                $discount = $content['total'] * ($cobon->discount_amount / 100 );
            }
            if($cobon->seller_id)
            {
                $seller = User::find($cobon->seller_id);
                $commission = ($seller->commission / 100) * ($content['total'] - $discount);
            }
            $status = 'event';
            $cobon_id = $cobon->id;
        }
        
        
        $total = $content['total'] - $discount;
        
        if($total < 0)
        {
            $discount = $content['total'];
            $total = 0;
        }
            
        return 
        [
            'message' => $message,
            'discount' => $discount,
            'total' => $total,
            'status' => $status,
            'cobon' => $cobon_id,
            'commission' => $commission
        ];
    }
}
