<?php namespace TPS\Birzha\Components;

use Cms\Classes\ComponentBase;
use TPS\Birzha\Models\Product;
use TPS\Birzha\Models\Comment;
use RainLab\User\Facades\Auth;
use Flash;

use TPS\Birzha\Models\Favourites;
use ValidationException;
use Validator;

class Singleoffer extends ComponentBase
{
    public function componentDetails()
    {
        return [
            'name'        => 'Single offer',
            'description' => 'Selected offer'
        ];
    }

    public function defineProperties()
    {
        return [
            'productSlug' => [
                'title' => 'Product slug',
                'description' => 'Product slug',
                'type' => 'string',
                'default' => '{{ :slug }}'
            ],
            'offerId' => [
                'title' => 'Offer id',
                'description' => 'Offer id',
                'type' => 'string',
                'default' => '{{ :id }}'
            ]
        ];
    }

    public function onCommentSave(){
        $data = post();
        
        $comment = new Comment;
        $comment->user_id = \Auth::user()->id;
        $comment->product_id = $data["product_id"];
        $comment->rating = $data["star"];
        $comment->comment = $data["comment"];

        $comment->save();
        Flash::success("Teswir goshuldy");
    }

    public function onRun() {
        $this->rating = $this->calculateRating(); 
        $this->offer = $this->loadOffer();
    }
    
    protected function calculateRating(){
        $product = Product::with("comments")->find($this->property('offerId'));
        $totalRating = 0;
        if($product){
            foreach($product->comments as $item){
                $totalRating = $totalRating + $item->rating; 
            }
        }
        return $totalRating == 0 ? $totalRating : round($totalRating/$product->comments->count());
    }
    
    public function onCreateFav()
    {
        $data = input();
        $validator = Validator::make($data, [
            'product_id' => 'required'
        ]);
        if($validator->fails()) {
            Flash::error("Haryt maglumaty nädogry");
        }
        $favourite = new Favourites;
        $favourite->user_id = \Auth::user()->id;
        $favourite->product_id = (int)$data['product_id'];
        $favourite->save();
        Flash::success("Haryt halanlaryma goşuldy");
    }




    protected function loadOffer() {
        $product = Product::withCount("comments")->find($this->property('offerId'));
        if($product && $product->status == 'approved') {
            $product->number_of_views = $product->number_of_views + 1;
            $product->save();
            return $product;
        }
        return null;
    }
    public $rating;
    public $offer;
}