<?php namespace TPS\Birzha\Components;

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

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

class SearchOffers extends ComponentBase
{
    /**
     * @var Collection A collection of user's posts
     */
    public $products;
    public $params;
    public $keyword;
        
    public function componentDetails()
    {
        return [
            'name'        => 'Search offers List',
            'description' => 'List of searched offers'
        ];
    }

    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() {
        $allParams = \Input::all();

        $params = '';
    
        foreach ($allParams as $key => $item) {
            if($key != 'page'){
                $params .= '&'.$key.'='.$item;
            }
        }

        $this->keyword = \Input::get('name');
        $this->params = $params;
        $this->products = $this->loadProducts();
    }

    protected function loadProducts() {
        $perPage = $this->property('perPage');
        $sort = \Input::get('sort');
        $products = Product::query();
        $title = \Input::get('name');

        if (isset($sort) && $sort != '') {
            $sort = self::getSort($sort);
            $products = $products->where('keyword', 'like', '%'.$title.'%')->withCount("images")->orderBy( $sort[0], $sort[1]);
        }else{
            $products = $products->where('keyword', 'like', '%'.$title.'%')->withCount("images");
        }

        $products = $products->with("vendor")->paginate($perPage);
        return $products;
    }

    private static function getSort($sort): array
    {
        $sort_key = trim($sort, '-');

        if (str_contains($sort, '-') && strpos($sort, '-') == 0) {
            $sort_direction = 'desc';
        }

        return [
            $sort_key,
            $sort_direction ?? 'asc'
        ];
    }
    
    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");
    }




    
}
