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

    public function componentDetails()
    {
        return [
            'name'        => 'Get products by type',
            'description' => 'Get products by type (new or vip)'
        ];
    }

    public function defineProperties()
    {
        return [
            'type' => [
                'title' => 'Select by type (new or vip)',
                'description' => 'Select by type',
                'type' => 'string',
                'default' => ''
            ],
            'perPage' => [
                'title' => 'Number of offers',
                'description' => 'How many offers do you want to display',
                'default' => 1,
                '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() {
        $this->products = $this->loadProducts();
        $this->categories = $this->getCategories();
        $this->cities = $this->getCities();
        $this->type = $this->property('type');
        $this->category = $this->getCategory();
        $this->city = $this->getCity();
        $this->subCategory = $this->getSubCategory();
    }


    protected function getCategories(){
        $categories = Category::where('primary_key', '=', 0)->get();
        return $categories;
    }
    
    protected function getCategory()
    {
        $cSlug = \Input::get('category');
        $category = Category::transWhere('slug', $cSlug, Session::get('rainlab.translate.locale'))->first();
        return $category;
    }

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

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

    protected function getCity()
    {
        $cityId = \Input::get('city');
        $city = City::find($cityId);
        return $city;
    }

    protected function loadProducts() {
        $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;
        }
        
        $type = $this->property('type');        
        $perPage = $this->property('perPage');
        $subCat = \Input::get('subcategory');
        
        $cSlug = null;
        if(isset($subCat) && $subCat != ''){
            $cSlug = $subCat;
        }else{
            $cSlug = \Input::get('category');
        }
        $city = \Input::get('city');
        $minPrice = \Input::get('min_price');
        $maxPrice = \Input::get('max_price');
        $sort = \Input::get('sort');
        
        $products = Product::query();
        
       if (isset($cSlug) && $cSlug != '') {
            $category = Category::transWhere('slug', $cSlug, Session::get('rainlab.translate.locale'))->first();
            if ($category) {
                $products = $category->products();
            } 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("type", $type)->with('vendor')->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");
    }
    
    public function onGetCategorySubs(){
        $data = post();
        $catgegory = null;
        if(strlen($data["mainCat"]) > 0){
            $category = Category::where('slug', $data["mainCat"])->first();
        }
        
        $subs = $this->getSubCatsq($category ? $category->id : $data["mainCat"]);               
        
        $checkSubs = $this->checkSubs($subs);
        
           if($checkSubs == ''){
              $checkSubs = [];
           }
        
        $allCats = $subs + $checkSubs;
        
        $subCatsAll = Category::whereIn("id", $allCats)->orderBy("primary_key", "ASC")->get();
        
        return $subCatsAll;
        
    }
    
    protected function checkSubs($catIds){
        $data = '';
        $subCats = [];
        foreach ($catIds as $id){
            $subs = $this->getSubCatsq($id);
            if(count($subs) > 0){
                foreach($subs as $subId){
                    array_unshift($subCats, $subId);
                }
                array_unshift($subCats, $id);
                $data = $subCats;
            }
        }  
        return $data;
        
    }
    
    protected function getSubCatsq($catId){
        
        $categoriesCustoms = Category::where("primary_key", $catId)->select("id", "primary_key")->get()->pluck("id")->toArray();
        return $categoriesCustoms;
        
    }
 
    protected function checking($catIds){
        $data=[];
        foreach ($catIds as $id){
            
            $subs = $this->getSubCatsq($id);
                $data[] = $id;
            if(count($subs) > 0){
                $data[] = $subs;
            }
          
        }    
    }
    
    
    
}
