<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class DeliveryManWarning extends Model
{
    use HasFactory;
    protected $fillable = ['delivery_man_id', 'warning', 'discount_amount'];
    public $maxCountOfWarnings = 5;

    public function getCountOfWarnings($deliveryManId)
    {
        return DeliveryManWarning::where('delivery_man_id', $deliveryManId)->count();
    }

    public function createWarning($deliveryManId, $warning)
    {
        if($this->getCountOfWarnings($deliveryManId) == 0){
            $nameOfDiscountAmountColumn = 'first_warning_discount_amount';
        }else if($this->getCountOfWarnings($deliveryManId) == 1){
            $nameOfDiscountAmountColumn = 'second_warning_discount_amount';
        }else if($this->getCountOfWarnings($deliveryManId) == 2){
            $nameOfDiscountAmountColumn = 'third_warning_discount_amount';
        }else if($this->getCountOfWarnings($deliveryManId) == 3){
            $nameOfDiscountAmountColumn = 'fourth_warning_discount_amount';
        }else{
            $nameOfDiscountAmountColumn = 'fifth_warning_discount_amount';
        }

        $discountAmount = BusinessSetting::where('key', $nameOfDiscountAmountColumn)->first()->value ?? 0;

        DeliveryManWarning::create([
            'delivery_man_id' => $deliveryManId,
            'warning' => $warning,
            'discount_amount' => $discountAmount,
        ]);

        $deliveryManInfo = DeliveryMan::findOrFail($deliveryManId);

        if($discountAmount > 0){
            $current_balance = $deliveryManInfo->wallet?$deliveryManInfo->wallet->collected_cash:0;

            $account_transaction = new AccountTransaction();
            $account_transaction->from_type = 'deliveryman';
            $account_transaction->from_id = $deliveryManId;
            $account_transaction->method = 'تلقائية';
            $account_transaction->ref = 'تم خصم المبلغ من حساب المندوب بسبب توجيه انذار: ' . ($this->getCountOfWarnings($deliveryManId));
            $account_transaction->amount = -1 * $discountAmount;
            $account_transaction->current_balance = $current_balance;
            $account_transaction->transaction_date = null;
            $account_transaction->admin_id = null;
            $account_transaction->save();

            DMLog::createLog($deliveryManId, 'تم خصم مبلغ '. $discountAmount .' ل.س من رصيدك بسبب توجيه انذار لك، السبب: ' . $warning, null, null);
        }

        if($this->getCountOfWarnings($deliveryManId) >= $this->maxCountOfWarnings){
            $deliveryManInfo->status = '0';
            $deliveryManInfo->save();
            DMLog::createLog($deliveryManId, 'تم حظر حسابك بسبب تلقيك عدة انذارات.', null, null);
        }
    }
}
