<?php

namespace AhmadFatoni\ApiGenerator\Controllers\API;

use Cms\Classes\Controller;
use DB;
use Config;
use AhmadFatoni\ApiGenerator\Helpers\Helpers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use RainLab\Blog\Models\Post;
use TPS\Birzha\Classes\BlogPostResource;
use TPS\Birzha\Models\SliderApp;
use TPS\Birzha\Models\UserSliders;
use TPS\Birzha\Models\Product;
use TPS\Birzha\Models\City;
use TPS\Birzha\Models\Favourites;
use TPS\Birzha\Models\Notification;
use TPS\Birzha\Models\Comment;
use TPS\Birzha\Models\Sections;
use TPS\Birzha\Models\Category;
use RainLab\User\Models\User;
use ToughDeveloper\ImageResizer\Classes\Image;

class BlogPostsApiController extends Controller
{
    protected $Post;

    protected $helpers;

    public function __construct(Post $Post, Favourites $Favourites, Comment $Comment, Helpers $helpers)
    {
        parent::__construct();
        $this->Post = $Post;
        $this->Favourites = $Favourites;
        $this->Comment = $Comment;
        $this->helpers = $helpers;
    }
    
    
    public function onGetCategorySubs($catId){
        
        $subs = $this->getSubCatsq($catId);               
        
        $checkSubs = $this->checkSubs($subs);
        
           if($checkSubs == ''){
              $checkSubs = [];
           }
        
        $allCats = $subs + $checkSubs;
        
        
        //$subCatsAll = Category::whereIn("id", $allCats)->orderBy("primary_key", "ASC")->get();
        
        return $allCats;
        
    }
    
    
   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;
        
    }
    
    
    public function getProductsWithAllSubCats(Request $request){
        $data = $request->all();

        $catIds = $this->onGetCategorySubs($data["category"]);
        
        $cats = Category::whereIn("id", $catIds)->with("subs")->get();
        
       foreach($cats as $cat) {
           foreach($cat->subs as $sub) {
               array_unshift($catIds, $sub->id);
           }
        }
        
        $products = Product::with('categories:id,name')->whereHas('categories', function($q) use($catIds){
                                $q->whereIn('id', $catIds);
                            })
                            ->with([
                                'translations:locale,model_id,attribute_data',
                                'images:attachment_id,attachment_type,disk_name,file_name',
                                'vendor:id,name,email,type,logo,banner,shop_title,slogan,is_instagram,web2',
                                'place'
                            ])
                            ->withCount(['comments as rating_avg' => function($query) {
                                $query->select(DB::raw('avg(rating)'));
                            }])
                            ->approved()
                            ->orderBy("id", "DESC")
                            ->paginate(12);
                            
         $products->map(function ($product) {
            
               $image = new Image($product->images[0]->path);
               $product->images[0]->compressed_image = $image->resize(510)->getCachedImagePath(true);
               
               return $product;
               //foreach($product->images as $compressImage){
               //    $image = new Image($compressImage->path);
               //    $compressImage->compressed_image = $image->resize([ 'quality' => 50])->getCachedImagePath(true);
               //}
               
        });
                            
        return response()->json(array("data"=>$products), 200);
            
    }
    
    
    public function getCategoryDatas(Request $request)
    {
        $path = 'https://gurlushyk.com.tm' . Config::get('cms.storage.media.path');
        
        $data = $request->all();
        
        $catIds = $this->onGetCategorySubs($data["category"]);
        
        $cats = Category::whereIn("id", $catIds)->with("subs")->get();
        
        
        
       foreach($cats as $cat) {
           foreach($cat->subs as $sub) {
               array_unshift($catIds, $sub->id);
           }
        }
        
        $accounts = Category::select("id","name", "icon", "is_file_category", "primary_key")
                                ->where('id', $data["category"])
                                //->whereIn('id', $cats)
                                ->with('users')
                                //->whereHas('users.categories', function($q) use($cats){
                                 //   $q->whereIn('id', $cats);    
                                //})
                                
                                //->with(["users" => function($q) use($cats){
                                //    $q->where("type", "!=", "simple")
                                //      ->with('categories')
                                 //     ->whereHas('categories', function($qq) use($cats){
                                 //         $qq->whereIn('id', $cats);
                                 //     });
                                //}])
                                ->get();
                                
       $userAccounts = User::where('type', '!=', 'simple')
                             ->whereHas('categories', function($q) use($catIds){
                                 $q->whereIn('category_id', $catIds);    
                             })
                             ->get();
        
        $accounts[0]->users = $userAccounts;
        
        $banners = Category::select("id","name", "icon", "is_file_category", "primary_key")
                             ->where('id', $data["category"])
                             ->with(["users" => function($q){
                                    $q->where("is_category", 1)->select("category_id", "user_id", "logo", "banner", "is_instagram");   
                               }])
                             ->get();
        $data = array(
                "path" => $path,
                "accounts" => $accounts,
                "banners" => $banners
            );
        

        
        return response()->json(array("data"=>$data), 200);
    }
    
     public function home(){
        
        $path = 'https://gurlushyk.com.tm' . Config::get('cms.storage.media.path');
        
        $data = Sections::where('id', 1)->first();
        
        $data->image_path = $path;
        $contents = array();
        $dataq = json_decode($data);
        
        for ($i = 0; $i < count($dataq->sections); $i++) {
            //dd($dataq->sections);
            if ($dataq->sections[$i]->section_type == "TPS\Birzha\Models\SliderApp") {
                
               $modified = $dataq->sections[$i]->section_type::where('id', $dataq->sections[$i]->item_id)->get();
               //$modified->makeHidden(['created_at', 'updated_at', 'deleted_at']);
               $product_section = array(
                            "type"=> "slider_banner",
                            "contents"=> $modified
                        );
               $contents = array_merge($contents, array($product_section));
                
            }else if ($dataq->sections[$i]->section_type == "RainLab\User\Models\User") {
                
               $modified = $dataq->sections[$i]->section_type::where('id', $dataq->sections[$i]->item_id)->select('id', 'name', 'email', 'username', 'shop_title', 'banner', 'is_instagram')->get();
               //$modified->makeHidden(['created_at', 'updated_at', 'deleted_at']);
               $product_section = array(
                            "type"=> "vendor_banner",
                            "contents"=> $modified
                        );
               $contents = array_merge($contents, array($product_section));
                
            }else if ($dataq->sections[$i]->section_type == "TPS\Birzha\Models\Product") {
                
               $modified = $dataq->sections[$i]->section_type::where('type', $dataq->sections[$i]->product_type)->select('id', 'name', 'price', 'description', 'place_id', 'vendor_id', 'number_of_views', 'is_home', 'short_description', 'type')->with("place")->with([
                                            'translations:locale,model_id,attribute_data',
                                            'images:attachment_id,attachment_type,disk_name,file_name',
                                            'vendor:id,name,email,type,logo,banner,shop_title,slogan,is_instagram,web2',
                                        ])->orderBy('ends_at', 'DESC')->limit(20)->get();
              // $modified->makeHidden(['created_at', 'updated_at', 'deleted_at']);
               $product_section = array(
                            "type"=> "product_section",
                            "header" => $dataq->sections[$i]->header,
                            "contents"=> $modified
                        );
               $contents = array_merge($contents, array($product_section));
               //$contents = array_merge($contents, array($modified));
                
            }
             
            
        }
        $data->section_contents = $contents;
        $data->makeHidden(['sections']);
        
        return response()->json($data, 200);
        
    }

    //posts list
    public function index(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'locale' => 'required|in:ru,en,tm',
            'per_page' => 'numeric',
            'sort_order' => 'in:asc,desc'
        ]);
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }

        return response()->json(
            BlogPostResource::collection($this->Post::with(['featured_images', 'translations:locale,model_id,attribute_data',])
                ->orderBy('published_at', $data['sort_order'] ?? 'desc')
                ->paginate($data['per_page'] ?? 7))->response()->getData(), 200);
    }
    
    public function getNotifications(){
        
        $data = Notification::with([
            'translations:locale,model_id,attribute_data'
        ])->paginate(9);
        
         return response()->json($data, 200);
        
    }


    public function getAccountSliders($id)
    {
        $data = UserSliders::where('user_id', $id)->paginate(9);
        
        if($data) {
            $data->each(function ($item, $key) {
                $item->img = 'https://gurlushyk.com.tm' . \Config::get('cms.storage.media.path') . $item->img;
            });
        }
        
        return response()->json($data, 200);
    }
    
    
    public function createComment(Request $request)
    {
        $currentUser = \JWTAuth::parseToken()->authenticate();

        $data = $request->all();
        $validator = Validator::make($data, [
            'product_id' => 'required',
            'comment' => 'required',
            'rating' => 'required|numeric'
        ]);
        
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }

        
        $comment = new $this->Comment;
        //dd($favourite);
        $comment->user_id = $currentUser->id;
        $comment->product_id = (int)$data['product_id'];
        $comment->comment = $data['comment'];
        $comment->rating = $data['rating'];

        $comment->save();

        return $this->helpers->apiArrayResponseBuilder(201, 'ok', ['comment' => $comment]);

    }
    
    
    public function getComment(Request $request)
    {
        //$data = $request->all();
       // $validator = Validator::make($data, [
      //      'product_id' => 'required',
      //  ]);
        
       // if($validator->fails()) {
      //      return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
      //  }
        
        $currentUser = \JWTAuth::parseToken()->authenticate();        
        $comment = $this->Comment::where('user_id', $currentUser->id)->with('product')->paginate(9);
        //dd($favourite);

        return response()->json($comment, 200);
        
    }
    
     public function getProductComment(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'product_id' => 'required',
        ]);
        
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }
             
        $comment = $this->Comment::where('product_id', $data["product_id"])->where('is_approve', 1)->with('user')->paginate(15);
        //dd($favourite);

        return response()->json($comment, 200);
        
    }
    
    
    public function createFav(Request $request)
    {
        $currentUser = \JWTAuth::parseToken()->authenticate();

        $data = $request->all();
        $validator = Validator::make($data, [
            'product_id' => 'required'
        ]);
        
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }

        
        $favourite = new $this->Favourites;
        //dd($favourite);
        $favourite->user_id = $currentUser->id;
        $favourite->product_id = (int)$data['product_id'];

        $favourite->save();

        return $this->helpers->apiArrayResponseBuilder(201, 'ok', ['favourite' => $favourite]);
       
        
        
    }
    
    
    public function getFav(Request $request)
    {
        $currentUser = \JWTAuth::parseToken()->authenticate();

        
        $favourite = $this->Favourites::where('user_id', $currentUser->id)
            ->with(['product' => function($q){
               $q->approved()->withTrashed()->with(['images:attachment_id,attachment_type,disk_name,file_name', 'place', 'files', 'translations:locale,model_id,attribute_data', 'vendor:id,name,email,type,logo,banner,shop_title,slogan,is_instagram,web2',]);
            }])->paginate(9);
        //dd($favourite);
        
        $favourite->map(function ($fav) {
            
               $image = new Image($fav->product->images[0]->path);
               $fav->product->images[0]->compressed_image = $image->resize(510)->getCachedImagePath(true);
               
               return $fav;
        });
        
        return response()->json($favourite, 200);
        
    }
    
     public function deleteFav($id){

        $favourite = $this->Favourites->find($id);
        $favourite->delete();

        return $this->helpers->apiArrayResponseBuilder(200, 'success', ['message' => 'Data has been deleted successfully']);
    }


   public function getAccountProducts($id)
   {
        $data = Product::where('vendor_id', $id)
                ->with('categories:id,name')
                ->with('vendor')
                ->with([
                    'translations:locale,model_id,attribute_data',
                    'images:attachment_id,attachment_type,disk_name,file_name',
                    'place'
                ])
                ->approved()
                ->paginate(9);
        
        $data->map(function ($product) {
            
               $image = new Image($product->images[0]->path);
               $product->images[0]->compressed_image = $image->resize(510)->getCachedImagePath(true);
               
               return $product;
               //foreach($product->images as $compressImage){
               //    $image = new Image($compressImage->path);
               //    $compressImage->compressed_image = $image->resize([ 'quality' => 50])->getCachedImagePath(true);
               //}
               
        });
        
        return response()->json($data, 200);
    }
    
    public function getPlaces(Request $request)
    {
         $data = $request->all();
         
         //$id = $data["primary"] ?? 0;
       
        $data = City::with([
                    'translations:locale,model_id,attribute_data',
                ])
                ->where('primary_key', $data["primary"] ?? 0)
                ->paginate(100)->toArray();
        
     //   array_unshift($data["data"], array(    
      //                      "id" => 0,
    //                        "name" => "Ählisi",
     //                       "order" => 0,
     //                   ));
                        
        return response()->json($data, 200);
    }
    
    public function getSubPlaces($id)
    {  
        $data = City::where('primary_key', $id)->get()->toArray();
        
        
        array_unshift($data, array(    
                            "id" => (0).$id,
                            "name" => "Ählisi",
                            "order" => 0,
                        ));
        return $data;
    }
    
    
   public function getAccountDatas($id)
    {
        //$data = User::find($id)->first;
      
        
         $data = User::where('id', $id)
        ->with(['categories' => function($q){
                $q->with('translations:locale,model_id,attribute_data');
            }])
        ->with('sliders')
        ->first();
        
         $data->pathUrl = 'https://gurlushyk.com.tm' . \Config::get('cms.storage.media.path');

         
         $all = array(
                         "id" => 0,
                         "name"=> "Hemmesi",
                         "icon" => "/not_found_img/placeholder.png"
                     ); 
                     
        //array_unshift($data->categories, $all);
        //$testq = is_array($data->categories);
        
        $data->categories->prepend($all);
        
        return response()->json($data, 200);
    }




    public function getAccounts(Request $request)
    {
        $data = $request->all();

        $dataAccounts = User::where('type', '!=', 'simple')->select('id', 'name', 'email', 'username', 'type', 'logo', 'shop_title', 'slogan', 'work_time', 'short_description', 'description', 'map', 'banner', 'is_instagram')
        ->with('categories:id,name,slug,icon')
        ->paginate(9);

        if($data && $data["type"] == "home"){

            $dataAccounts = User::where('is_featured', 1)
            ->select('id', 'name', 'email', 'username', 'type', 'logo', 'shop_title', 'slogan', 'work_time', 'short_description', 'description', 'map', 'banner', 'is_instagram')
            ->with('categories:id,name,slug,icon')
            ->paginate(9);

        }elseif($data && $data["type"] == "category"){

            $dataAccounts = User::where('is_category', 1)
            ->select('id', 'name', 'email', 'username', 'type', 'logo', 'shop_title', 'slogan', 'work_time', 'short_description', 'description', 'map', 'is_instagram')
            ->with('categories:id,name,slug,icon')
            ->paginate(9);

        }
        //$dataSlider["img"] = $path.$dataSlider["img"];

        if($dataAccounts){
            $dataAccounts->each(function ($item, $key) {
                $item->logo = 'https://gurlushyk.com.tm'.Config::get('cms.storage.media.path').$item->logo;
                $item->banner = 'https://gurlushyk.com.tm'.Config::get('cms.storage.media.path').$item->banner;
            });
        }

        return response()->json($dataAccounts, 200);
    }


    public function getSliders(Request $request)
    {
        $path = Config::get('cms.storage.media.path');

        $data = $request->all();
        $validator = Validator::make($data, [
            //'locale' => 'required|in:ru,en,tm',
            'type' => 'required'
        ]);
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }
        $dataSlider = SliderApp::where('type', $data['type'])->orderBy('order', 'desc')->select('id', 'img', 'type', 'order')->paginate(9);

        //$dataSlider["img"] = $path.$dataSlider["img"];

         if($dataSlider){
            $dataSlider->each(function ($item, $key) {
                $item->img = 'https://gurlushyk.com.tm'.Config::get('cms.storage.media.path').$item->img;
            });
        }

        return response()->json($dataSlider, 200);
    }

    //posts item
    public function show($id, Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'locale' => 'required|in:ru,en,tm',
        ]);
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }

        if(!$post = $this->Post::find($id)) {
            return $this->helpers->apiArrayResponseBuilder(404, 'not found', ['error' => "Resource id = {$id} could not be found"]);
        } else {
            return new BlogPostResource($post);
        }
    }
}
