gurl_o/plugins/tps/birzha/components/Singleoffer.php

80 lines
2.1 KiB
PHP

<?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;
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());
}
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;
}