<?php

namespace App\Observers;

use App\Model\Article;
use App\Model\Review;
use App\Model\Product;

class ReviewObserver
{
    /**
     *  'creating', 'created', 'updating', 'updated',
     * 'deleting', 'deleted', 'saving', 'saved',
     * 'restoring', 'restored',
     */

    /**
     * Listen to the Review created event.
     *
     * @param User $user
     * @return void
     */
    public function saved(Review $review)
    {
        $this->sync($review);
    }

    /**
     * Listen to the Review deleted event.
     *
     * @param User $user
     * @return void
     */
    public function deleted(Review $review)
    {
        $this->sync($review);
    }

    public function sync(Review $review)
    {
        // we want to trigger this only when the review is active!
        if (!$review->is_active && $review->wasRecentlyCreated) {
            return;
        }

        /**
         * We need to update the user destination "cached" cols.
         * Also disable events firing, cos we don't need this here.
         */
        Article::withoutEvents(function () use ($review) {
            $article = $review->article;
            $article->comment_count = $article->reviews()->active()->count();
            $article->save();
        });

    }

}
