<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Article;
use Illuminate\View\View;
use App\ArticleDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\ArticleRequest;
use Illuminate\Http\RedirectResponse;

class ArticleController extends Controller
{

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

    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= __('articles.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index', get_defined_vars());
    }

    /**
     * return data of the pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Article::orderByDesc('articles.id')
            ->join('article_descriptions AS ad', 'articles.id', 'ad.article_id')
            ->join('languages', 'languages.id', 'ad.language_id')
            ->where('local', getCurrentLocale())
            ->select(['ad.title', 'articles.*']);

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

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

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

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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('articles.store');
        $head= metaFields('articles', 'new', getCurrentLocale()) ?? __('articles.new');
        $title= $head;
        $local = getCurrentLocale();
        return view( $this->viewDirectory.'form', get_defined_vars() );
    }

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

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

        $article = Article::create($data);

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

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


    /**
     * Show the form for editing the specified resource.
     *
     * @param Article $article
     * @return View
     */
    public function edit(Article $article) :View
    {
        $action= route('articles.update', $article->id);
        $head = metaFields('articles', 'edit', getCurrentLocale()) ?? __('articles.edit');
        $title = $head;

        $query = ArticleDescription::where('article_id', $article->id)
            ->join('languages', 'languages.id', 'article_descriptions.language_id')
            ->select(['article_descriptions.*', 'languages.local']);

        $articleDescription= $query->get();

        foreach ($articleDescription as $row) {
            $article[$row->local]= $row;
        }

        $local = getCurrentLocale();

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

    /**
     * Update the specified resource in storage.
     *
     * @param ArticleRequest $request
     * @param Article $article
     * @return RedirectResponse|Redirector
     */
    public function update(ArticleRequest $request, Article $article) :RedirectResponse
    {

        $data = $request->all();

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

        // Update image and category id if request has it
        $article->update($data);

        // Delete old description
        ArticleDescription::where('article_id', $article->id)->delete();

        // delete old photos
//        ArticlePhoto::where('article_id', $article->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param ArticleRequest $request
     * @param int $article_id
     * @return void
     */

    private function saveData(ArticleRequest $request, int $article_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'title'=> $requestData['title_'.$lang->local],
                'rating'=> $requestData['rating_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
                'slug'=> $requestData['slug_'.$lang->local],
                'meta_description'=> $requestData['meta_description_'.$lang->local],
                'keywords'=> $requestData['keywords_'.$lang->local],
                'article_id'=> $article_id,
                'language_id'=> $lang->id,
            ];
            ArticleDescription::create($data);
        }

//        if ($request->has('images')){
//
//            foreach ($request->images as $image) {
//                $data=[
//                    'image'=> $image,
//                    'article_id'=> $article_id,
//                ];
//
//                ArticlePhoto::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
    {
        $article = Article::withTrashed()->find($id);
        if ($article) {
            if ($article->deleted_at) {
                $article->forceDelete();
            } else {
                $article->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) {
            Article::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Article::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
    {
        $article = Article::withTrashed()->find($id);

        if ($article){
            $article->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
    {
        $article = Article::whereIn('id', $request->ids)->onlyTrashed();
        if ($article){
            $article->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
