<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Event extends Model
{
    protected $keyType = 'string';
    public $incrementing = false;

    protected $fillable = [
        'user_id',
        'title',
        'starts_at',
        'ends_at',
        'start_date',
        'end_date',
        'is_all_day',
        'notes',
        'reminders',
        'exceptions',
        'participants',
        'color',
        'google_event_id',
        'recurrence',
        'recurrence_end_date',
    ];

    protected $casts = [
        'starts_at'            => 'datetime',
        'ends_at'              => 'datetime',
        'start_date'           => 'datetime',
        'end_date'             => 'datetime',
        'is_all_day'           => 'boolean',
        'reminders'            => 'array',
        'exceptions'           => 'array',
        'participants'         => 'array',
        'recurrence_end_date'  => 'date:Y-m-d',
    ];

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

        static::creating(function ($model) {
            if (!$model->id) {
                $model->id = (string) Str::uuid();
            }
        });
    }

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

    public function users()
    {
        return $this->belongsToMany(User::class, 'event_user');
    }

    public function contacts()
    {
        return $this->belongsToMany(\App\Models\Contact::class, 'event_contact');
    }

    public function isMultiDay(): bool
    {
        if (!$this->ends_at) {
            return false;
        }

        return $this->starts_at->toDateString() !== $this->ends_at->toDateString();
    }


    public function spansMultipleDays(): bool
    {
        return $this->ends_at
            && !$this->starts_at->isSameDay($this->ends_at);
    }

    public function getDisplayTimeForDate(string $date, string $tz): array
    {
        $start = $this->starts_at->timezone($tz);
        $end = $this->ends_at?->timezone($tz);

        $displayStart = $start;
        $displayEnd = $end;

        $exceptions = $this->exceptions;

        if (is_string($exceptions)) {
            $exceptions = json_decode($exceptions, true);
        }

        if (is_array($exceptions)) {
            foreach ($exceptions as $ex) {

                if (($ex['date'] ?? null) === $date) {

                    if (!empty($ex['start'])) {
                        $displayStart = $start->copy()->setTimeFromTimeString($ex['start']);
                    }

                    if (!empty($ex['end'])) {
                        $displayEnd = $start->copy()->setTimeFromTimeString($ex['end']);
                    }

                }
            }
        }

        return [
            'start' => $displayStart,
            'end' => $displayEnd,
        ];
    }
}
