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

    public function componentDetails()
    {
        return [
            'name'        => 'Offers List',
            'description' => 'List of offers'
        ];
    }

    public function defineProperties()
    {
        return [
            'categorySlug' => [
                'title' => 'Select by category :slug',
                'description' => 'Select by category',
                'type' => 'string',
                'default' => ''
            ],
            'vendor_id' => [
                'title' => 'Select by vendor :id',
                'description' => 'Select by vendor',
                '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'
            ],
            'productSlug' => [
                'title' => 'Product Slug',
                'description' => 'Similar offers (the same product)',
                'type' => 'string',
                'default' => ''
            ],
            'offerId' => [
                'title' => 'Offer id',
                'description' => 'Offer id',
                'type' => 'string',
                'default' => ''
            ]
        ];
    }

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

    public function onRun() {
        $this->offers = $this->loadOffers();
        $this->category = $this->getCategory();
        $this->categories = $this->getCategories();
        $this->cities = $this->getCities();
    }

    protected function getCategory(){
        $cSlug = $this->property('categorySlug');
        $category = Category::transWhere('slug', $cSlug, Session::get('rainlab.translate.locale'))->first();
        return $category;
    }

    protected function getCategories(){
        $categories = Category::where('primary_key', '=', 0)->get();
        return $categories;
    }

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

    protected function filterOffers(){
        return "filterOffers";
    }

    protected function loadOffers() {
        $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;
        }
        
        $cSlug = $this->property('categorySlug');
        $vendorId = $this->property('vendor_id');
        $perPage = $this->property('perPage');
        $productSlug = $this->property('productSlug');
        $offerId = $this->property('offerId');

        $query = Product::where('status', 'approved')->with("vendor")->withCount("images")
            ->orderBy('ends_at', $sortOrder);

        if($cSlug != '') {
            $category = Category::transWhere('slug', $cSlug, Session::get('rainlab.translate.locale'))->first();
            if($category) {
                $query = $category->products()
                    ->where('status','approved')
                    ->orderBy('updated_at', $sortOrder);
            } else {
                $query = null;
            }
        }
        if($productSlug != '' && $offerId != '') { // fetch offers with similar products
            $product = Product::transWhere('slug', $productSlug, Session::get('rainlab.translate.locale'))->first();
            if($product) {
                $category = $product->categories->first();
                $query = $category->products()
                    ->where('id','!=',$offerId)
                    ->where('status','approved')
                    ->orderBy('updated_at', $sortOrder);
            } else {
                $query = null;
            }
        }
        if($vendorId != '') {
            $query = Product::where('vendor_id', $vendorId)->where('status', 'approved')->orderBy('updated_at', $sortOrder);
        }

        return $query ? $query->paginate($perPage) : null;
    }
    
    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;
            }
          
        }    
    }
    
    
    
}
