<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\ProductRequest;
use App\Product;
use App\ProductDescription;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;

class ProductController extends Controller
{

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

    public function __construct()
    {
        $this->redirectSuccessPath = getCurrentLocale().$this->redirectSuccessPath;
    }

    /**
     * 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',get_defined_vars());
    }

    /**
     * return data of the products.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Product::orderByDesc('products.id')
            ->join('product_descriptions AS pDesc', 'products.id', 'pDesc.product_id')
            ->where('pDesc.language_id', currentLanguage()->id)
            ->select(['pDesc.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('pDesc.name', 'LIKE', '%'.$request->name.'%');
        }
        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

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

        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 = metaFields('products', 'add_new', getCurrentLocale()) ?? __('products.new');
        $points = [];
        return view( $this->viewDirectory.'form', get_defined_vars() );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param ProductRequest $request
     * @return JsonResponse
     */
    public function store(ProductRequest $request) :JsonResponse
    {

        $data = $request->all();
        $data['points'] = [
            'ar' => $request->points['ar'],
            'en' => $request->points['en'],
            'maximum' => $request->maximum,
            'minimum' => $request->minimum,
        ];
        $product = Product::create($data);
        // Insert Description
        $this->saveData( $request, $product->id );
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('products.index')]);
//        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 = metaFields('products', 'edit', getCurrentLocale()) ?? __('products.edit');

        $query = ProductDescription::where('product_id', $product->id)
            ->join('languages', 'languages.id', 'product_descriptions.language_id')
            ->select(['product_descriptions.*', 'languages.local']);

        $productDescription= $query->get();

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


        $points = $product->points;

        return view( $this->viewDirectory.'form', get_defined_vars() );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param ProductRequest $request
     * @param Product $product
     * @return JsonResponse
     */
    public function update(ProductRequest $request, Product $product) :JsonResponse
    {
        // Update image if request has it
        $data = $request->all();
        $data['points'] = [
            'ar' => $request->points['ar'],
            'en' => $request->points['en'],
            'maximum' => $request->maximum,
            'minimum' => $request->minimum,
        ];

        $product->update($data);

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

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

        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('products.index')]);
    }

    /**
     * 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=[
                'name'=> $requestData['name_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
                'advantages'=> $requestData['advantages_'.$lang->local],
                'product_id'=> $product_id,
                'language_id'=> $lang->id,
            ];
            ProductDescription::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
    {
//        if (1 == $id) {
//            return response()->json(['message'=> __('dashboard.noResult')], 400);
//        }

        $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 products by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
//        if ( in_array( 1, $ids) ) {
//            return response()->json(['message'=> __('dashboard.noResult')], 400);
//        }

        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 products by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $products = Product::whereIn('id', $request->ids)->onlyTrashed();
        if ($products){
            $products->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
