<?php


namespace App\Repositories;


use App\News;
use App\Notifications\NewNewsNotification;

class NewsRepository {
    public static function all() {
        return News::all();
    }

    public static function find($id){
        return News::findOrFail($id);
    }

    public static function create(array $data) {
        //1. Comprovem
        if(!isset($data["box_id"]) && !isset($data["company_id"])  ||  isset($data["box_id"]) && isset($data["company_id"]))
            throw new \Exception("Proporciona solo un company_id o un box_id. O uno, o el otro. Ni los dos a la vez, ni ninguno.");

        //2. Creem
        $news = News::create($data);

        //3. Notifiquem
        if($news->box_id!=null) {
            $users_active = BoxRepository::users($news->box_id, true);
        }
        else { //company
            $users_active = CompanyRepository::users($news->company_id, true);
        }
        foreach($users_active as $u) {
            $u->notify(new NewNewsNotification($news));
            if($u->one_signal_player_id!=null) {
                $params = [
                    "title" => "¡Se ha publicado una nueva noticia en tu box! Ves a verla",
                    "user_id" => $u->id
                ];
                NotificationRepository::sendNotification($params);
            }
        }

        //4. Retornem
        return $news;
    }

    public static function update(array $data, $id) {
        News::findOrFail($id)->update($data);
        return News::findOrFail($id);
    }

    public static function delete($id){
        return News::destroy($id);
    }
}
