<?php

namespace App\Models_v2;

use App\Models\District;
use App\Models\HostelType;
use App\Models\Lead;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class FindSession extends Model {
	//
	use SoftDeletes;

	const SEARCHING = 0;
	const FOUND = 1;
	const NOT_FOUND = 2;
	const CANCEL = 3;

	protected $fillable = [
		'user_id',
		'properties',
		'status',
		'min_price',
		'max_price',
		'type',
		'type_rent',
		'note',
		'province_id',
		'created_at',
		'updated_at',
		'lead_id'
	];

	protected $casts = [
		'properties' => 'array'
	];

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

	public static function boot() {
		parent::boot();

		static::created(function($item) {
			User::query()
			    ->where('id', $item->user_id)
			    ->where('type', User::RENTER)
			    ->update([
				    'refer_status' => User::REFER_STATUS_SUCCESS,
				    'refer_reason'=>null
			    ]);
		});

		static::saving( function ( $item ) {
			$properties = $item->properties;
			if ( isset( $properties['min_price'] ) ) {
				$item->min_price = $properties['min_price'];
			}
			if ( isset( $properties['max_price'] ) ) {
				$item->max_price = $properties['max_price'];
			}
			if ( isset( $properties['province_id'] ) ) {
				$item->province_id = $properties['province_id'];
			}
			if ( isset( $properties['type'] ) ) {
				$item->type = $properties['type'];
			}

			if ( isset( $properties['type_rent'] ) ) {
				$item->type_rent = $properties['type_rent'];
			}
		} );

		static::saved( function ( $item ) {
			$properties = $item->properties;
			if ( isset( $properties['district_id'] ) ) {
				$item->districts()->sync( $properties['district_id'] );
			}

			$user = $item->user;
			if ( $user ) {
				$user->last_find_at = Carbon::now()->toDateTimeString();
				$user->save();
			}
		} );
	}

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

	public function lead() {
		return $this->belongsTo( Lead::class );
	}

	public function conversations() {
		return $this->hasMany( Conversation::class, 'find_session_id', 'id' );
	}

	public function districts() {
		return $this->belongsToMany( District::class, 'find_session_districts', 'find_session_id', 'district_id', 'id', 'districtid' );
	}

	public function hostelType() {
		return $this->belongsTo( HostelType::class, 'type', 'id' );
	}


}
