<?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 FilteredProducts extends ComponentBase
{
    /*
    * sort order parametr in a url string
    */
    public $sortParam = '';
    public $products;
    public $params;
    public $category;
    public $categories;
    public $cities;

    public function componentDetails()
    {
        return [
            'name'        => 'Filtered Producs',
            'description' => 'Getting Filtered 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'
            ],
            'sortOrder' => [
                'title' => 'Sort offers',
                'description' => 'How to sort offers',
                'type' => 'dropdown',
                'default' => 'desc'
            ]
        ];
    }

    public function getSortOrderOptions()
    {
        return [
            'asc' => 'Created date (ascending)',
            'desc' => 'Created date (descending)'
        ];
    }

    public function onRun()
    {
        $allParams = \Input::all();


        $params = '';

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

        $this->params = $params;
        $this->products = $this->loadFiltered();
        $this->category = $this->getSubCategory();
        $this->categories = $this->getCategories();
        $this->cities = $this->getCities();
    }

    protected function getSubCategory()
    {
        $cSlug = \Input::get('subcategory');
        $category = Category::transWhere('slug', $cSlug, Session::get('rainlab.translate.locale'))->first();
        return $category;
    }

    protected function getCategories()
    {
        $categories = Category::all();
        return $categories;
    }

    protected function getCities()
    {
        $cities = City::all();
        return $cities;
    }

    protected function loadFiltered()
    {
        $sortOrderParam = strtolower(\Input::get('sort_order'));
        // protect from sql injection
        if ($sortOrderParam != 'asc' && $sortOrderParam != 'desc') {
            $sortOrder = $this->property('sortOrder');
        } else {
            $sortOrder = $sortOrderParam;
            $this->sortParam = $sortOrderParam;
        }
        

        $perPage = $this->property('perPage');
        $products = Product::query();

        $cSlug = \Input::get('subcategory');
        $city = \Input::get('city');
        $minPrice = \Input::get('min_price');
        $maxPrice = \Input::get('max_price');
        $sort = \Input::get('sort');

        if (isset($cSlug) && $cSlug != '') {
            $category = Category::transWhere('slug', $cSlug, Session::get('rainlab.translate.locale'))->first();
            if ($category) {
                $products = $category->products();
                // $products->withPath("filter?category=".$category->slug);
            } else {
                $products = null;
            }
        }
        if (isset($city) && $city != '') {
            $products = $products->where('place_id', $city);
        }
        if (isset($minPrice) && $minPrice != '') {
            $products = $products->where('price', '>=', $minPrice);
        }
        if (isset($maxPrice) && $maxPrice != '') {
            $products = $products->where('price', '<=', $maxPrice);
        }

        if (isset($sort) && $sort != '') {
            $sort = self::getSort($sort);
            $products = $products->orderBy( $sort[0], $sort[1]);
        }

        $products = $products->where('status', 'approved')->withCount("images");
        return $products ? $products->paginate($perPage) : null;
    }

    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");
    }
}
