<?php

namespace App\Http\Controllers\Admin;

use App\Module;
use Exception;
use App\Product;
use App\User;
use App\ProductPhoto;
use Illuminate\View\View;
use App\ProductDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\ProductRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ProductController extends Controller
{

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

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('products.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 = Product::latest()
            ->join('product_descriptions AS ad', 'products.id', 'ad.product_id')
            ->join('languages', 'languages.id', 'ad.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['ad.name', 'products.*']);

        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();
        }

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param ProductRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(ProductRequest $request) :RedirectResponse
    {
        $product = Product::create($request->all());

        // update image to youtube api thumbnail if request have not image
        if ($request->video_type == 1){
            $product->update([
                'image' => parseExternalVideoLink($request->video_url)['image'],
                'video' => parseExternalVideoLink($request->video_url)['url'],
            ]);
        }

        // Insert Description
        $this->saveData($request, $product->id);

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


    /**
     * Show the form for editing the specified resource.
     *
     * @param product $product
     * @return View
     */
    public function edit(Product $product) :View
    {
        $action= route('products.update', $product->id);
        $head = 'Product edit';
        $query = ProductDescription::where('product_id', $product->id)
            ->join('languages', 'languages.id', 'product_descriptions.language_id')
            ->select(['product_descriptions.*', 'languages.local']);
        $users = User::cursor();
        $productDescription= $query->get();

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

        return view( $this->viewDirectory.'form', compact('product', 'action','head','users') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param ProductRequest $request
     * @param product $product
     * @return RedirectResponse|Redirector
     */
    public function update(ProductRequest $request, Product $product) :RedirectResponse
    {
        // Update image and category id if request has it
        $product->update($request->all());

        // update image to youtube api thumbnail if request have not image
        if ($request->video_type == 1){
            $product->update([
                'image' => parseExternalVideoLink($request->video_url)['image'],
                'video' => parseExternalVideoLink($request->video_url)['url'],
            ]);
        }

        // Delete old description
        ProductDescription::where('product_id', $product->id)->delete();

        // delete old photos
        ProductPhoto::where('product_id', $product->id)->delete();

        // Insert new description
        $this->saveData( $request, $product->id );

        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],
                'slug'=> $requestData['slug_'.$lang->local],
                'meta_description'=> $requestData['meta_description_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
                'keywords'=> $requestData['keywords_'.$lang->local],
            ];
            ProductDescription::create($data);
        }

        if ($request->has('images')){

            foreach ($request->images as $image) {
                $data=[
                    'image'=> $image,
                    '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')]);
        }
    }
}
