<?php

namespace App\Http\Controllers\Admin;

use App\Module;
use Exception;
use App\Product;
use App\User;
use App\ProductPhoto;
use App\Models;
use App\Exports\ProductExport;
use Maatwebsite\Excel\Facades\Excel;
use App\City;
use App\Follow;
use App\Device;
use App\Country;
use App\ProductAttribute;
use App\Writer;
use App\Log;
use App\Category;
use Illuminate\View\View;
use App\ProductDescription;
use App\ProductElement;
use App\ProductTag;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\BannerRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class BannerController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath= '/dashboard/banners';
    /** View folder */
    private $viewDirectory= 'admin.banners.';

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return View
     */
    
    public function productShow(Request $request) 
    {
         $query = Category::latest()
        ->join('category_descriptions AS cd', 'categories.id', 'cd.category_id')
        ->join('languages', 'languages.id', 'cd.language_id')
        ->where('local', LaravelLocalization::getCurrentLocale())
        ->select(['cd.name', 'categories.*']);

        if ($request->date_from) {
            $query->whereDate('products.created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('products.created_at', '<=', $request->date_to);
        }

        if ($request->name) {
            $query->where('ad.name', 'LIKE', '%'.$request->name.'%');
        }

        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        $banners= $query->get();

        return Excel::download(new ProductExport($banners), 'report.xlsx');
    }


    public function index(Request $request) :View
    {
        $title= __('banners.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',compact('title'));
    }

    /**
     * return data of the pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
         $query = Category::latest()
        ->join('category_descriptions AS cd', 'categories.id', 'cd.category_id')
        ->join('languages', 'languages.id', 'cd.language_id')
        ->where('local', LaravelLocalization::getCurrentLocale())
        ->select(['cd.name', 'categories.*']);

        if ($request->date_from) {
            $query->whereDate('categories.created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('categories.created_at', '<=', $request->date_to);
        }

        if ($request->name) {
            $query->where('cd.name', 'LIKE', '%'.$request->name.'%');
        }

        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        $banners= $query->paginate(100);

        return view($this->viewDirectory.'grid',compact('banners'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('products.store');
        $head= __('products.new');
        $categories = Category::cursor();
        $writers = Writer::cursor();
        return view( $this->viewDirectory.'form', compact('action', 'categories','head','writers') );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param ProductRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(ProductRequest $request) :RedirectResponse
    {
        
        $product = Product::create($request->all());
       
        // Insert Description
        $this->saveData($request, $product->id);
        
        $title = productnamelang($product->id,'1');
        //$title_en = productnamelang($product->id,'2');
    
    $follow = Follow::where('type','1')->where('target_id',$product->category_id)->pluck('device_id');
    if(!is_null($product->model_id)){
        $ids = Follow::where('type','2')->where('target_id',$product->model_id)->pluck('device_id');
        $follow = $follow->merge($ids);
    }
   
    $follow = $follow->unique();
    foreach($follow as $row){
       
       $user = Device::find($row);
        // if($user->language == 'ar'){
        //     $title = $title_ar;
        // }
        // else{
        //     $title = $title_en;
        // }
       
        $data =array(
        'type' => 'NEW_PROVIDER',
        'provider_id'=> $product->id,
        'title'=> $title,
        'vibrate' => 1,
        'priority' => 'high',
        'visibility'=> 1,
        'foreground'=> true,
        'no-cache' => 1,
        'force-start' => 1,

    );
    $data['notification'] = $data;

    $token['to'] = $user->device_token ;
     

    $res= sendNotification($data, $token);
  
    }
    
          return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param product $product
     * @return View
     */
    public function edit(Category $banner) :View
    {
        $product = $banner;
        $action= route('banners.update', $product->id);
        $head = __('banners.edit');
        $query = ProductDescription::where('product_id', $product->id)
            ->join('languages', 'languages.id', 'product_descriptions.language_id')
            ->select(['product_descriptions.*', 'languages.local']);
        $writers = Writer::cursor();
        $categories = Category::cursor();
        $models = Models::where('category_id',$product->category_id)->get();
        
      
        $productDescription= $query->get();

        foreach ($productDescription as $row) {
            $product[$row->local]= $row;
        }

        return view( $this->viewDirectory.'form', compact('product','banner','categories','action','head','writers','models') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param ProductRequest $request
     * @param product $product
     * @return RedirectResponse|Redirector
     */
    public function update(BannerRequest $request, Category $banner):RedirectResponse
    {
        // Update image and category id if request has it
        $banner->update($request->all());
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'بانر الاقسام الرئيسية','action'=>'اضافة']);
       
        

         return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param ProductRequest $request
     * @param int $product_id
     * @return void
     */

    private function saveData(ProductRequest $request, int $product_id ):void
    {
        
        $requestData= $request->all();
        
        foreach (languages() as $lang) {
            $data=[
                'product_id'=> $product_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],

                
            ];
            ProductDescription::create($data);
        }
        
        if ($request->has('images')){
            $links = $request->links;
            foreach ($request->images as $key=>$image) {
                $data=[
                    'image'=> $image,
                    'link'=> $links[$key],
                    'product_id'=> $product_id,
                ];

                ProductPhoto::create($data);

            }
        }
       
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $product = Product::withTrashed()->find($id);
        if ($product) {
            if ($product->deleted_at) {
                $product->forceDelete();
            } else {
                $product->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Product::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Product::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified category from storage
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $product = Product::withTrashed()->find($id);

        if ($product){
            $product->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

    /**
     * Restore several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $product = Product::whereIn('id', $request->ids)->onlyTrashed();
        if ($product){
            $product->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
