<?php

namespace App\Models;

use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\Traits\LogsActivity;

class ElectricWater extends Model
{
    //
    use SoftDeletes;
    use LogsActivity;

    protected static $logAttributes = ['*'];

    protected $fillable = [
        'start_electric',
        'end_electric',
        'start_water',
        'end_water',
        'delta_electric',
        'delta_water',
        'room_id',
        'hostel_id',
        'created_at',
        'updated_at',
        'deleted_at',
        'date_action',


        'hostel_name',
        'room_name',
        'contract_id',
        'contract_code',
        'date_execution',

        'start_electric_image',
        'end_electric_image',
        'start_water_image',
        'end_water_image',
        'user_id',
        'price_electric',
        'price_water'
    ];

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


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

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

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

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

    public static function boot()
    {
        parent::boot();
        static::creating(function ($item) {
            $priceWater = 0;
            $priceElectric = 0;
            $feeElectric = HostelFee::query()
                ->where('hostel_id', $item->hostel_id)
                ->where('type', HostelFee::ELECTRIC_BY_CLOCK)
                ->first();

            if ($feeElectric) {
                $priceElectric = $feeElectric->fee;
            }

            $feeWater = HostelFee::query()
                ->where('hostel_id', $item->hostel_id)
                ->where('type', HostelFee::WATER_BY_CLOCK)
                ->first();

            if ($feeWater) {
                $priceWater = $feeWater->fee;
            }
            $item->price_electric = $priceElectric;
            $item->price_water = $priceWater;
        });
        static::created(function ($item) {
            if (auth('backend')->check()) {
                $item->user_id = auth('backend')->user()->id;
            } else {
                $token = \request()->header('authorization');
                if ($token) {
                    $user = \JWTAuth::parseToken()->toUser();
                    if ($user) {
                        $item->user_id = $user->id;
                    }
                }
            }
            if(empty($item->date_execution))
            {
                $item->date_execution = Carbon::now();
            }

            $item->save();
        });
    }
}
