<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;
class EventAssignment extends Model
{
    use HasFactory;
    protected $table = 'event_assignments'; 
    public $timestamps = false; 
    protected $fillable = ['id', 'fk_user_id', 'fk_event_id'];

    public function event()
    {
        return $this->belongsTo(Event::class, 'fk_event_id', 'id');
    }
	
	public function assignEventToUsers($user_id ,$event_id)
    {
	
			$update = ['fk_user_id'=>$user_id,'fk_event_id'=>$event_id];
			EventAssignment::insert($update);
		
        return true;
    }

   /* public static function getEventsofUser($user_id)
    {
        return EventAssignment::with('event')->select('*', 'event_assignments.is_admin as is_eventadmin')->where('fk_user_id', $user_id)->get();
    }
	*/
	public static function getEventsofUser($user_id)
	{
    // Fetch event assignments along with the related event
    $eventAssignments = EventAssignment::with('event')
        ->select('*', 'event_assignments.is_admin as is_eventadmin')
        ->where('fk_user_id', $user_id)
        ->get();
	
		
		 $user = User::find($user_id);
    
		// Apply mapping to the event assignments so you can manipulate or apply conditions
		$mappedEvents = $eventAssignments->map(function ($eventAssignment) use ($user) {
        // You can add your conditions here and modify the eventAssignment object as needed
		
		if($user->is_admin == "true")
		{
			
			$eventAssignment->visitor_count = $eventAssignment->event->visitors()->count();
		}
		else if($eventAssignment->is_admin == "true")
		{
			
			$eventAssignment->visitor_count = $eventAssignment->event->visitors()->count();
		}
		else 
		{
			$eventAssignment->visitor_count =  $eventAssignment->event->visitors()
            ->where('customer_id', $user->CustomerID) // Assuming 'customer_id' is the column name in the visitors table
            ->count();
		}

        // Return the modified event assignment
        return $eventAssignment;
    });

    // Return the mapped collection
    return $mappedEvents;
	}



    public function user(){
        return $this->hasOne(User::class,'user_id','fk_user_id');
    }
	
}
