<?php namespace TPS\Birzha\Components;

use Cms\Classes\ComponentBase;
use TPS\Birzha\Models\Category;
use TPS\Birzha\Models\Product;
use TPS\Birzha\Models\City;
use Session;
use DB;

use TPS\Birzha\Models\Favourites;
use RainLab\User\Facades\Auth;
use ValidationException;
use Validator;
use Flash;

class CategoryProfile extends ComponentBase
{

    public $category;
    public $users;
    public $products;
    public $subcategories;

    public function componentDetails() {
        return [
            'name' => 'Category profile',
            'description' => 'Category profile page component',
        ];
    }



    public function defineProperties()
    {
        return [
            'categorySlug' => [
                'title' => 'Select by category :slug',
                'description' => 'Select by category',
                'type' => 'string',
                'default' => ''
            ],
        ];
    }



    public function onRun() {
        $this->users = $this->getCategoryUsers();
        $this->category = $this->getCategory();
        $this->subcategories = $this->getSubs();
    }

    protected function getCategory(){
        $cSlug = $this->property('categorySlug');
        $category = Category::transWhere('slug', $cSlug, Session::get('rainlab.translate.locale'))->with('users')->first();
        return $category;
    }
    
    protected function getSubs(){
        $cSlug = $this->property('categorySlug');
        $category = Category::transWhere('slug', $cSlug, Session::get('rainlab.translate.locale'))->with('users')->first();
        $subs = Category::where("primary_key", $category->id)->get();
        
        foreach ($subs as $subcategory) {
            $page = input('page', 1);
            $products = $subcategory->products()->paginate(12, $page);
            $subcategory->setRelation('products', $products);
        }
        
        return $subs;
    }

    protected function getCategoryUsers(){
        $cSlug = $this->property('categorySlug');
        $category = Category::where('slug', $cSlug)->first();
        $users = $category->users()->get();
        return $users;
    }
    
    protected function getProducts(){
        $cSlug = $this->property('categorySlug');
        $category = Category::where('slug', $cSlug)->first();
        $users = $category->users()->get();
        return $users;
    }
    
    public function onCreateFav()
    {
        $data = input();
        $validator = Validator::make($data, [
            'product_id' => 'required'
        ]);
        if($validator->fails()) {
            Flash::error("Haryt maglumatyny 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");
    }
}
