<?php

namespace WoWPress\Frontend\Widgets;

use Illuminate\Support\Collection;
use WoWPress\Models\User;

class Birthdays extends Widget {

    protected $template_path = "birthdays.php";
    protected $title = "Geburtstage";
    protected $base_id = "wowpress_birthdays";
    public $name = "Geburtstagsliste";
    protected $restricted = "wowpress_view_birthdays";


    public function getList(){
        $out = new Collection();
        foreach(User::all() as $user){
            $bday = $user->getMeta('birthday');
            if($bday){
               $ts = strtotime($bday);
               $thisyear = strtotime(date('Y-m-d',strtotime(date('Y-').date('m-d',$ts))));
               $nextyear = strtotime(date('Y-m-d',strtotime(date('Y-').date('m-d',$ts)))."+1 year");
               $today = strtotime(date('0:00'));
               if($thisyear < $today){
                $age = intval(($nextyear-$ts)/31536000);
                $sort = $nextyear;
                $party = false;
               }elseif($thisyear > $today){
                $age = intval(($thisyear-$ts)/31536000);
                $sort= $thisyear;
                $party = false;
               }else{
                $age = intval(($thisyear-$ts)/31536000);
                $sort = $thisyear;
                $party = true;
               }

               $next = date('Y-m-d',strtotime('next '.date('m-d',$ts)));
               $out[] = [
                'user' => $user->username,
                'next' => date('d.m.',$ts),
                'sort' => date('Y-m-d',$sort),
               // 'sort' => date('Y-m-d',strtotime('next '.date('Y-m-d',$ts))),
                'age' => $age,
                'party' => $party,
               ];
            }

        }
        return $out->sortBy(fn($a) => $a['sort']);

    }


    public function form( $instance ) {
	}

	public function update( $new_instance, $old_instance ) {
		$instance          = array();
		return $instance;
	}

}