<?php namespace TPS\Birzha\Components;

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

class MyFavourites extends ComponentBase
{
    /**
     * @var Collection A collection of user's posts
     */
    public $favourites;
    
    
    public function componentDetails()
    {
        return [
            'name'        => 'MyFavourites List',
            'description' => 'List of my favourite products',
        ];
    }

    public function defineProperties()
    {
        return [
            'perPage' => [
                'title' => 'Number of offers',
                'description' => 'How many offers do you want to display',
                'default' => 12,
                'validationPattern' => '^[0-9]+$',
                'validationMessage' => 'Only numbers allowed'
            ],
        ];
    }


    public function onRun() {
        $this->favourites = $this->loadFavourites();
    }

    public function onRemove(){
        $data = post();
        $favourites = Favourites::where("user_id", \Auth::user()->id)->where("product_id", $data["product_id"])->first();
        $favourites->delete();
        return \Redirect::back();
    }

    protected function loadFavourites() {
        $perPage = $this->property('perPage');
        return \Auth::user()->favourites()
            ->orderBy('updated_at', 'desc')
            ->paginate($perPage);
    }

    
}
