<?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 Competition extends Model
{
    use HasTranslations, SelectTranslations;

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

    public $translatable = ['web_image', 'app_image', 'timer_title', 'timer_subtitle', 'content'];
    public $timestamps = true;


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

    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 getCompetitionDataForApp()
    {
        $competition = self::first();
        if ($competition)
            return self::mapItemsForApp($competition);

        return [];
    }

    public static function mapItemsForApp($competition)
    {
        $now = Carbon::now();
        $competitionEnd = Carbon::createFromFormat('Y-m-d H:i:s', $competition->end);
        $interval = $now->diffAsCarbonInterval($competitionEnd);

        return [
            'title' => $competition->getTranslations('timer_title'),
            'subtitle' => $competition->getTranslations('timer_subtitle'),
            'time_left' => [
                'days' => $interval->d,
                'hours' => $interval->h,
                'minutes' => $interval->i,
                'seconds' => $interval->s
            ],
            'content' => [
                'image' => $competition->getTranslations('app_image'),
                'text' => $competition->getTranslations('content')
            ]
        ];
    }
}