<?php

namespace App\Models;

use App\Components\Functions;
use App\Events\LogAction;
use App\Jobs\UpdateStatistic;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\Traits\LogsActivity;

/**
 * MoneyInfo
 *
 * @mixin \Eloquent
 */
class MoneyInfo extends Model
{
    //
    use SoftDeletes;
    use LogsActivity;

    protected static $logAttributes = ['*'];

    const VOUCHER_ROOM_PRICE = 0;
    const VOUCHER_CONTRACT = 1;
    const VOUCHER_SERVICE = 2;
    const VOUCHER_DEPOSIT = 3;
    const VOUCHER_OTHER = 4;

    protected $fillable = [
        'date_display',
        'name',
        'contract_id',
        'hostel_id',
        'room_id',
        'amount',
        'pay',
        'remain',
        'discount',
        'date_action',
        'created_at',
        'updated_at',
        'deleted_at',
        'user_id',
        'type',
        'money_info_name',
        'bed_id',
        'note'
    ];

    protected $dates = [
        'date_action',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

//	protected $casts = [
//		'date_action' => 'datetime:m/Y',
//	];

    public function details()
    {
        return $this->hasMany(MoneyDetail::class, 'money_info_id', 'id');
    }

    public function collectSpends()
    {
        return $this->hasMany(CollectSpend::class, 'money_info_id', 'id');
    }

    public static function boot()
    {
        parent::boot();
        static::creating(function ($item) {
            if (empty($item->money_info_name)) {
                if (!in_array($item->type, [MoneyInfo::VOUCHER_CONTRACT, MoneyInfo::VOUCHER_ROOM_PRICE])) {
                    if ($item->date_action) {
                        $name = 'Thu tiền dịch vụ tháng ' . $item->date_action->format('m/Y');
                    } else {
                        $name = 'Thu tiền dịch vụ';
                    }
                    $item->money_info_name = $name;
                }
            }
        });

        static::created(function ($item) {

            if ($item->type == self::VOUCHER_CONTRACT) {
                if ($item->pay > $item->amount) {
                    MoneyInfo::query()->where('id', $item->id)
                        ->update([
                            'pay' => $item->amount,
                            'remain' => 0
                        ]);


                    MoneyDetail::query()->where('money_info_id', $item->id)
                        ->update([
                            'amount' => $item->amount
                        ]);
                }
            }

            if ($item->type != self::VOUCHER_ROOM_PRICE && $item->type != self::VOUCHER_CONTRACT) {
                StatisticMonth::create([
                    'month' => $item->date_action->month,
                    'year' => $item->date_action->year,
                    'amount' => $item->pay,
                    'contract_id' => $item->contract_id,
                    'room_id' => !empty($item->room) ? $item->room->id : null,
                    'hostel_id' => !empty($item->hostel) ? $item->hostel->id : null,
                    'money_info_id' => $item->id,
                ]);
            }

            if ($item->amount == 0) {
                if (in_array($item->type, [MoneyInfo::VOUCHER_ROOM_PRICE, MoneyInfo::VOUCHER_CONTRACT])) {
                    $moneyDetail = MoneyDetail::query()
                        ->where('money_info_id', $item->id)
                        ->first();
                    if ($moneyDetail) {
                        $qty = $moneyDetail->qty;
                        $contract = $item->contract;
                        if ($contract) {
                            $roomPrice = $contract->room_price;
                            //$roomPrice = $moneyDetail->value; // cho phép cập nhật value
                            if (!empty($roomPrice)) {
                                $amount = $roomPrice * $qty;
                                $item->amount = $amount;
                                $item->save();
                                $moneyDetail->amount = $amount;
                                $moneyDetail->sum_amount = $amount;
                                $moneyDetail->save();
                            }
                        }
                    }
                } else {
                    $amount = MoneyDetail::query()
                        ->where('money_info_id', $item->id)
                        ->sum('amount');
                    $item->amount = $amount;
                    $item->remain = $amount - $item->pay;
                    $item->save();
                }
            }

            if (in_array($item->type, [
                self::VOUCHER_ROOM_PRICE,
                self::VOUCHER_CONTRACT
            ])) {
                if ($item->hostel_id) {
                    $hostelId = $item->hostel_id;
                    $checkDiscount = DiscountHostel::query()
                        ->whereHas('hostels', function ($q) use ($hostelId) {
                            $q->where('hostel_id', $hostelId);
                        })
                        ->whereBetween('date', [
                            $item->date_action->copy()->startOfMonth(),
                            $item->date_action->copy()->endOfMonth(),
                        ])
                        ->first();

                    if ($checkDiscount) {
                        if ($item->discount == 0) {
                            $item->discount = $checkDiscount->discount;
                            $item->remain = $item->amount - $item->pay - $checkDiscount->discount;
                            $item->save();
                        }
                    }
                }
            }

            if ($item->type == MoneyInfo::VOUCHER_SERVICE) {

            }
        });

    }

    public function hostel()
    {
        return $this->belongsTo('App\Models\Hostel');
    }

    public function room()
    {
        return $this->belongsTo('App\Models\Room')->withTrashed();
    }

    public function contract()
    {
        return $this->belongsTo(Contract::class)->withTrashed();
    }

//	public function getCustomerNameAttribute() {
//		if ( ! empty( $this->attributes['contract_id'] ) ) {
//			$contract = Contract::find( $this->attributes['contract_id'] );
//
//			return optional( $contract )->name;
//		} else {
//			$renter = RenterRoom::query()
//			                    ->where( 'room_id', $this->attributes['room_id'] )
//			                    ->whereNotNull( 'room_contract_id' )
//			                    ->first();
//			if ( $renter ) {
//				$contract = Contract::find( $renter->room_contract_id );
//				return optional( $contract )->name;
//			}
//		}
//	}

    public function user()
    {
        return $this->belongsTo(User::class)->withTrashed();
    }

    public function getNameAttribute()
    {
        if (empty($this->attributes['name'])) {
            $dt = Carbon::createFromFormat('Y-m-d H:i:s', $this->attributes['created_at'])->format('dmy');

            return 'HD' . $this->attributes['id'] . $dt;
        }

        return $this->attributes['name'];
    }

    public function scopeValidate($query, $contractId)
    {
        return $query->where('contract_id', $contractId)->where('contract_status', '<>', Contract::LIQUIDATED);
    }
}
