<?php

namespace Yajny\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;
use Yajny\Traits\SelectTranslations;

class Event extends Model
{
    use HasTranslations, SelectTranslations;

    protected $table = 'events';
    protected $guarded = [];
    protected $appends = ['local_start', 'local_end'];

    public $timestamps = true;
    public $translatable = ['name', 'web_logo', 'app_logo'];

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('active', function (Builder $builder) {
            $now = Carbon::now()->toDateTimeString();
            $builder->where('start', '<=', $now);
            $builder->where('end', '>=', $now);
        });
    }

    public static function getForWeb($slug)
    {
        return self::where('slug', $slug)->where('web_status', true)->first();
    }

    public static function getForApp($slug)
    {
        return self::where('slug', $slug)->where('app_status', true)->first();
    }

    private function convertDateTimeTimezone($date, $fromTz, $toTz)
    {
        return Carbon::createFromFormat('Y-m-d H:i:s', $date, $fromTz)->timezone($toTz)->toDateTimeString();
    }

    public function getLocalStartAttribute()
    {
        return ($this->start) ? $this->convertDateTimeTimezone($this->start, 'UTC', 'Africa/Cairo') : null;
    }

    public function getLocalEndAttribute()
    {
        return ($this->end) ? $this->convertDateTimeTimezone($this->end, 'UTC', 'Africa/Cairo') : null;
    }

    public function setLocalStartAttribute($value)
    {
        $this->attributes['start'] = $this->convertDateTimeTimezone($value, 'Africa/Cairo', 'UTC');
    }

    public function setLocalEndAttribute($value)
    {
        $this->attributes['end'] = $this->convertDateTimeTimezone($value, 'Africa/Cairo', 'UTC');
    }

    public static function getEventDataForApp(Event $event)
    {
        return [
            'name' => $event->getTranslations('name'),
            'app_logo' => $event->getTranslations('app_logo'),
            'background_type' => $event->background_type,
            'background_value' => $event->app_background_value,
            'font_color' => $event->font_color
        ];
    }
}