<?php namespace TPS\Birzha\Components;

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

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

class UserOffers extends ComponentBase
{
    /**
     * @var Collection A collection of user's posts
     */
    public $userProducts;
    public $userCategories;
    public $userProfile;
    public $params;
    public $sliders;
    public $currentCat;
    public $chatroom;
    public $result;
    public $authUser;
        
    public function componentDetails()
    {
        return [
            'name'        => 'User offers List',
            'description' => 'List of users 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'
            ],
            'slug' => [
                'title' => 'Select by category :slug',
                'description' => 'Select by category',
                'type' => 'string',
                'default' => ''
            ],
            'id' => [
                'title' => 'Select by vendor :id',
                'description' => 'Select by vendor',
                'type' => 'string',
                'default' => ''
            ],
        ];
    }



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

        $params = '';

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

        $this->params = $params;
        $this->userCategories = $this->loadCategories();
        $this->userProfile = $this->loadUser();
        $this->userProducts = $this->loadProducts();
        $this->sliders = $this->loadSliders();
        $this->currentCat = $this->loadCurrentCategory();
        
        if(\Auth::user()){
            $this->authUser = \Auth::user()->id;    
            $this->chatroom = $this->getChatroom();
            $this->result = $this->getMessages($this->chatroom ? $this->chatroom->id : null);
        }else{
            $this->authUser = null;
            $this->chatroom = null;
            $this->result = null;
        }
    }

    protected function loadProducts() {

        $perPage = $this->property('perPage');
        $sort = \Input::get('sort');
        $vendor_id = $this->property('id');
        $categorySlug = $this->property('slug');
        $category = null;

        if($categorySlug){
            $category = Category::where('slug', $categorySlug)->first();
        }
        $products = Product::query()->approved();


        if($category){
            if (isset($sort) && $sort != '') {
                $sort = self::getSort($sort);
                $products = $category->products()->where('vendor_id', $vendor_id)->withCount("images")->orderBy( $sort[0], $sort[1]);
            }else{
                $products = $category->products()->where('vendor_id', $vendor_id)->withCount("images");
            }
        }else{
            if (isset($sort) && $sort != '') {
                $sort = self::getSort($sort);
                $products = $products->where("vendor_id", $vendor_id)->withCount("images")->orderBy( $sort[0], $sort[1]);
            }else{
                
                $products = $products->where("vendor_id", $vendor_id)->withCount("images")->orderBy( "id", "DESC");
                
            } 
        }
        $products = $products->paginate($perPage);
        
        return $products;
    }

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

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

        return [
            $sort_key,
            $sort_direction ?? 'asc'
        ];
    }

    protected function loadCategories(){
        $user = User::find($this->property('id'));
        if($user){
            $categories = $user->categories()->get();
            return $categories;
        }
        
        return null;
    }
    
    protected function loadCurrentCategory(){
        $currentCat = Category::where("slug", $this->property('slug'))->first();
        if($currentCat){
        return $currentCat;
        }
        
        return null;
    }
    
    public function loadUser(){
        $user = User::with("sliders")->find($this->property('id'));
        return $user;
    }
    
    protected function loadSliders(){
        $user = User::find($this->property('id'));
        return $user->sliders()->get();
    }
    
    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");
    }
    
    protected function getChatroom() {
        if(\Auth::user()->id == $this->property('id')){
            return null;
        }else{
            $chatrooms = \Auth::user()->chatrooms;
            foreach($chatrooms as $room) {
                $room->message_partner = $room->users()->where('users.id','!=',\Auth::user()->id)->first();
                if($room->message_partner->id == $this->property('id')) {
                    return $room;
                }
            }
            $seller = User::findOrFail($this->property('id'));
            $chatroom = new Chatroom;
            $chatroom->save();
            $chatroom->users()->attach($seller->id);
            $chatroom->users()->attach(Auth::user()->id);

            $chatroom->message_partner = $seller;
            return $chatroom;
        }
    }

    public function getMessages($chatroomId){
        if($chatroomId){
            $result = Chatroom::find($chatroomId)->messages()->latest('send_at')->limit(10)->get()->reverse();
            return $result;
        }else{
            return null;
        }
        
    }





    
}
