<?php

namespace App\Listeners;

use App\Models\Achievement;
use App\Models\Hostel;
use App\Models_v2\Transaction;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class ProcessAchievementWhenHostelCreated {
	/**
	 * Create the event listener.
	 *
	 * @return void
	 */
	public function __construct() {
		//
	}

	/**
	 * Handle the event.
	 *
	 * @param object $event
	 *
	 * @return void
	 */
	public function handle( \App\Events\HostelCreated $event ) {
		//
		$hostel = $event->hostel;
		$owner  = $hostel->owner;
		if ( ! $owner ) {
			return;
		}
		$firstHostel = Hostel::withTrashed()
		                     ->where( 'owner_id', $owner->id )
		                     ->orderBy( 'id', 'asc' )
		                     ->first();

		if ( ! $firstHostel ) {
			return;
		}

		if ( $hostel->id == $firstHostel->id ) {
			return;
		}

		$achievement = Achievement::query()->where( 'id', 2 )->first();
		if ( ! $achievement ) {
			return;
		}
		Transaction::create( [
			'user_id'        => $owner->id,
			'amount'         => $achievement->credits,
			'type'           => Transaction::VOUCHER,
			'hostel_id'      => $hostel->id,
			'achievement_id' => $achievement->id,
			'status'         => Transaction::STATUS_NOT_PROCESS
		] );
	}
}
